blob: ba81c776a95937946a54f8d76bc63e5f6037ef50 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
alan-bakerf67468c2019-11-25 15:51:49 -050039#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040040#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
Kévin Petitbbbda972020-03-03 19:16:31 +000042#include "llvm/Support/MathExtras.h"
David Neto118188e2018-08-24 11:27:54 -040043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040045
SJWf93f5f32020-05-05 07:27:56 -050046// enable spv::HasResultAndType
47#define SPV_ENABLE_UTILITY_CODE
alan-bakere0902602020-03-23 08:43:40 -040048#include "spirv/unified1/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040049
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040051#include "clspv/Option.h"
alan-baker86ce19c2020-08-05 13:09:19 -040052#include "clspv/PushConstant.h"
53#include "clspv/SpecConstant.h"
David Neto85082642018-03-24 06:55:20 -070054#include "clspv/spirv_c_strings.hpp"
55#include "clspv/spirv_glsl.hpp"
alan-baker86ce19c2020-08-05 13:09:19 -040056#include "clspv/spirv_reflection.hpp"
David Neto22f144c2017-06-12 14:26:21 -040057
David Neto4feb7a42017-10-06 17:29:42 -040058#include "ArgKind.h"
alan-bakerf67468c2019-11-25 15:51:49 -050059#include "Builtins.h"
alan-baker06cad652019-12-03 17:56:47 -050060#include "ComputeStructuredOrder.h"
David Neto85082642018-03-24 06:55:20 -070061#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040062#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040063#include "DescriptorCounter.h"
alan-bakerc4579bb2020-04-29 14:15:50 -040064#include "Layout.h"
alan-baker56f7aff2019-05-22 08:06:42 -040065#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040066#include "Passes.h"
alan-bakera1be3322020-04-20 12:48:18 -040067#include "SpecConstant.h"
alan-bakerce179f12019-12-06 19:02:22 -050068#include "Types.h"
David Neto48f56a42017-10-06 16:44:25 -040069
David Neto22f144c2017-06-12 14:26:21 -040070#if defined(_MSC_VER)
71#pragma warning(pop)
72#endif
73
74using namespace llvm;
75using namespace clspv;
SJW173c7e92020-03-16 08:44:47 -050076using namespace clspv::Builtins;
SJW806a5d82020-07-15 12:51:38 -050077using namespace clspv::Option;
David Neto156783e2017-07-05 15:39:41 -040078using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040079
80namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040081
David Neto862b7d82018-06-14 18:48:37 -040082cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
83 cl::desc("Show resource variable creation"));
84
alan-baker5ed87542020-03-23 11:05:22 -040085cl::opt<bool>
86 ShowProducerIR("show-producer-ir", cl::init(false), cl::ReallyHidden,
87 cl::desc("Dump the IR at the start of SPIRVProducer"));
88
David Neto862b7d82018-06-14 18:48:37 -040089// These hacks exist to help transition code generation algorithms
90// without making huge noise in detailed test output.
91const bool Hack_generate_runtime_array_stride_early = true;
92
David Neto3fbb4072017-10-16 11:28:14 -040093// The value of 1/pi. This value is from MSDN
94// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
95const double kOneOverPi = 0.318309886183790671538;
96const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
97
alan-baker86ce19c2020-08-05 13:09:19 -040098// SPIRV Module Sections (per 2.4 of the SPIR-V spec)
SJW69939d52020-04-16 07:29:07 -050099// These are used to collect SPIRVInstructions by type on-the-fly.
100enum SPIRVSection {
101 kCapabilities,
102 kExtensions,
103 kImports,
104 kMemoryModel,
105 kEntryPoints,
106 kExecutionModes,
107
108 kDebug,
109 kAnnotations,
110
111 kTypes,
112 kConstants = kTypes,
113 kGlobalVariables,
114
115 kFunctions,
116
alan-baker86ce19c2020-08-05 13:09:19 -0400117 // This is not a section of the SPIR-V spec and should always immediately
118 // precede kSectionCount. It is a convenient place for the embedded
119 // reflection data.
120 kReflection,
SJW69939d52020-04-16 07:29:07 -0500121 kSectionCount
122};
123
SJW01901d92020-05-21 08:58:31 -0500124class SPIRVID {
125 uint32_t id;
126
127public:
128 SPIRVID(uint32_t _id = 0) : id(_id) {}
129 uint32_t get() const { return id; }
130 bool isValid() const { return id != 0; }
131 bool operator==(const SPIRVID &that) const { return id == that.id; }
SJW806a5d82020-07-15 12:51:38 -0500132 bool operator<(const SPIRVID &that) const { return id < that.id; }
SJW01901d92020-05-21 08:58:31 -0500133};
SJWf93f5f32020-05-05 07:27:56 -0500134
SJW88ed5fe2020-05-11 12:40:57 -0500135enum SPIRVOperandType { NUMBERID, LITERAL_WORD, LITERAL_DWORD, LITERAL_STRING };
David Neto22f144c2017-06-12 14:26:21 -0400136
137struct SPIRVOperand {
SJW88ed5fe2020-05-11 12:40:57 -0500138 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num) : Type(Ty) {
139 LiteralNum[0] = Num;
140 }
David Neto22f144c2017-06-12 14:26:21 -0400141 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
142 : Type(Ty), LiteralStr(Str) {}
143 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
144 : Type(Ty), LiteralStr(Str) {}
SJW88ed5fe2020-05-11 12:40:57 -0500145 explicit SPIRVOperand(ArrayRef<uint32_t> NumVec) {
146 auto sz = NumVec.size();
147 assert(sz >= 1 && sz <= 2);
148 Type = sz == 1 ? LITERAL_WORD : LITERAL_DWORD;
149 LiteralNum[0] = NumVec[0];
150 if (sz == 2) {
151 LiteralNum[1] = NumVec[1];
152 }
153 }
David Neto22f144c2017-06-12 14:26:21 -0400154
alan-baker7506abb2020-09-10 15:02:55 -0400155 SPIRVOperandType getType() const { return Type; }
156 uint32_t getNumID() const { return LiteralNum[0]; }
157 std::string getLiteralStr() const { return LiteralStr; }
158 const uint32_t *getLiteralNum() const { return LiteralNum; }
David Neto22f144c2017-06-12 14:26:21 -0400159
David Neto87846742018-04-11 17:36:22 -0400160 uint32_t GetNumWords() const {
161 switch (Type) {
162 case NUMBERID:
SJW88ed5fe2020-05-11 12:40:57 -0500163 case LITERAL_WORD:
David Neto87846742018-04-11 17:36:22 -0400164 return 1;
SJW88ed5fe2020-05-11 12:40:57 -0500165 case LITERAL_DWORD:
166 return 2;
David Neto87846742018-04-11 17:36:22 -0400167 case LITERAL_STRING:
168 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400169 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400170 }
171 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
172 }
173
David Neto22f144c2017-06-12 14:26:21 -0400174private:
175 SPIRVOperandType Type;
176 std::string LiteralStr;
SJW88ed5fe2020-05-11 12:40:57 -0500177 uint32_t LiteralNum[2];
David Neto22f144c2017-06-12 14:26:21 -0400178};
179
SJW88ed5fe2020-05-11 12:40:57 -0500180typedef SmallVector<SPIRVOperand, 4> SPIRVOperandVec;
David Netoc6f3ab22018-04-06 18:02:31 -0400181
David Neto22f144c2017-06-12 14:26:21 -0400182struct SPIRVInstruction {
SJWf93f5f32020-05-05 07:27:56 -0500183 // Primary constructor must have Opcode, initializes WordCount based on ResID.
184 SPIRVInstruction(spv::Op Opc, SPIRVID ResID = 0)
185 : Opcode(static_cast<uint16_t>(Opc)) {
186 setResult(ResID);
David Neto87846742018-04-11 17:36:22 -0400187 }
David Neto22f144c2017-06-12 14:26:21 -0400188
SJWf93f5f32020-05-05 07:27:56 -0500189 // Creates an instruction with an opcode and no result ID, and with the given
190 // operands. This calls primary constructor to initialize Opcode, WordCount.
191 // Takes ownership of the operands and clears |Ops|.
192 SPIRVInstruction(spv::Op Opc, SPIRVOperandVec &Ops) : SPIRVInstruction(Opc) {
193 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500194 }
SJWf93f5f32020-05-05 07:27:56 -0500195 // Creates an instruction with an opcode and no result ID, and with the given
196 // operands. This calls primary constructor to initialize Opcode, WordCount.
197 // Takes ownership of the operands and clears |Ops|.
198 SPIRVInstruction(spv::Op Opc, SPIRVID ResID, SPIRVOperandVec &Ops)
199 : SPIRVInstruction(Opc, ResID) {
200 setOperands(Ops);
David Netoef5ba2b2019-12-20 08:35:54 -0500201 }
David Netoef5ba2b2019-12-20 08:35:54 -0500202
David Netoee2660d2018-06-28 16:31:29 -0400203 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400204 uint16_t getOpcode() const { return Opcode; }
SJW88ed5fe2020-05-11 12:40:57 -0500205 SPIRVID getResultID() const { return ResultID; }
206 const SPIRVOperandVec &getOperands() const { return Operands; }
David Neto22f144c2017-06-12 14:26:21 -0400207
208private:
SJW01901d92020-05-21 08:58:31 -0500209 void setResult(SPIRVID ResID = 0) {
210 WordCount = 1 + (ResID.isValid() ? 1 : 0);
SJWf93f5f32020-05-05 07:27:56 -0500211 ResultID = ResID;
212 }
213
214 void setOperands(SPIRVOperandVec &Ops) {
215 assert(Operands.empty());
216 Operands = std::move(Ops);
217 for (auto &opd : Operands) {
SJW88ed5fe2020-05-11 12:40:57 -0500218 WordCount += uint16_t(opd.GetNumWords());
SJWf93f5f32020-05-05 07:27:56 -0500219 }
220 }
221
222private:
David Netoee2660d2018-06-28 16:31:29 -0400223 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400224 uint16_t Opcode;
SJW88ed5fe2020-05-11 12:40:57 -0500225 SPIRVID ResultID;
SJWf93f5f32020-05-05 07:27:56 -0500226 SPIRVOperandVec Operands;
David Neto22f144c2017-06-12 14:26:21 -0400227};
228
229struct SPIRVProducerPass final : public ModulePass {
SJW01901d92020-05-21 08:58:31 -0500230 typedef DenseMap<Type *, SPIRVID> TypeMapType;
David Neto22f144c2017-06-12 14:26:21 -0400231 typedef UniqueVector<Type *> TypeList;
SJW88ed5fe2020-05-11 12:40:57 -0500232 typedef DenseMap<Value *, SPIRVID> ValueMapType;
SJW806a5d82020-07-15 12:51:38 -0500233 typedef std::list<SPIRVID> SPIRVIDListType;
SJW01901d92020-05-21 08:58:31 -0500234 typedef std::vector<std::pair<Value *, SPIRVID>> EntryPointVecType;
235 typedef std::set<uint32_t> CapabilitySetType;
SJW88ed5fe2020-05-11 12:40:57 -0500236 typedef std::list<SPIRVInstruction> SPIRVInstructionList;
SJW806a5d82020-07-15 12:51:38 -0500237 typedef std::map<spv::BuiltIn, SPIRVID> BuiltinConstantMapType;
SJW88ed5fe2020-05-11 12:40:57 -0500238 // A vector of pairs, each of which is:
David Neto87846742018-04-11 17:36:22 -0400239 // - the LLVM instruction that we will later generate SPIR-V code for
SJW88ed5fe2020-05-11 12:40:57 -0500240 // - the SPIR-V instruction placeholder that will be replaced
241 typedef std::vector<std::pair<Value *, SPIRVInstruction *>>
David Neto22f144c2017-06-12 14:26:21 -0400242 DeferredInstVecType;
243 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
244 GlobalConstFuncMapType;
245
David Neto44795152017-07-13 15:45:28 -0400246 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 raw_pwrite_stream &out,
alan-baker00e7a582019-06-07 12:54:21 -0400248 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400249 bool outputCInitList)
SJW01901d92020-05-21 08:58:31 -0500250 : ModulePass(ID), module(nullptr), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400251 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Neto0676e6f2017-07-11 18:47:44 -0400252 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500253 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
254 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
SJW01901d92020-05-21 08:58:31 -0500255 WorkgroupSizeVarID(0) {
256 addCapability(spv::CapabilityShader);
257 Ptr = this;
258 }
David Neto22f144c2017-06-12 14:26:21 -0400259
James Price11010dc2019-12-19 13:53:09 -0500260 virtual ~SPIRVProducerPass() {
James Price11010dc2019-12-19 13:53:09 -0500261 }
262
David Neto22f144c2017-06-12 14:26:21 -0400263 void getAnalysisUsage(AnalysisUsage &AU) const override {
264 AU.addRequired<DominatorTreeWrapperPass>();
265 AU.addRequired<LoopInfoWrapperPass>();
266 }
267
268 virtual bool runOnModule(Module &module) override;
269
270 // output the SPIR-V header block
271 void outputHeader();
272
273 // patch the SPIR-V header block
274 void patchHeader();
275
SJW01901d92020-05-21 08:58:31 -0500276 CapabilitySetType &getCapabilitySet() { return CapabilitySet; }
David Neto22f144c2017-06-12 14:26:21 -0400277 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
alan-baker7506abb2020-09-10 15:02:55 -0400278 TypeList &getTypeList() { return Types; }
David Neto22f144c2017-06-12 14:26:21 -0400279 ValueMapType &getValueMap() { return ValueMap; }
SJW69939d52020-04-16 07:29:07 -0500280 SPIRVInstructionList &getSPIRVInstList(SPIRVSection Section) {
281 return SPIRVSections[Section];
282 };
alan-baker7506abb2020-09-10 15:02:55 -0400283 EntryPointVecType &getEntryPointVec() { return EntryPointVec; }
284 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; }
SJW806a5d82020-07-15 12:51:38 -0500285 SPIRVIDListType &getEntryPointInterfacesList() {
286 return EntryPointInterfacesList;
alan-baker7506abb2020-09-10 15:02:55 -0400287 }
SJW01901d92020-05-21 08:58:31 -0500288 SPIRVID getOpExtInstImportID();
alan-baker7506abb2020-09-10 15:02:55 -0400289 std::vector<SPIRVID> &getBuiltinDimVec() { return BuiltinDimensionVec; }
SJW2c317da2020-03-23 07:39:13 -0500290
alan-baker5b86ed72019-02-15 08:26:50 -0500291 bool hasVariablePointersStorageBuffer() {
292 return HasVariablePointersStorageBuffer;
293 }
SJW01901d92020-05-21 08:58:31 -0500294 void setVariablePointersStorageBuffer() {
295 if (!HasVariablePointersStorageBuffer) {
296 addCapability(spv::CapabilityVariablePointersStorageBuffer);
297 HasVariablePointersStorageBuffer = true;
298 }
alan-baker5b86ed72019-02-15 08:26:50 -0500299 }
alan-baker7506abb2020-09-10 15:02:55 -0400300 bool hasVariablePointers() { return HasVariablePointers; }
SJW01901d92020-05-21 08:58:31 -0500301 void setVariablePointers() {
302 if (!HasVariablePointers) {
303 addCapability(spv::CapabilityVariablePointers);
304 HasVariablePointers = true;
305 }
alan-baker7506abb2020-09-10 15:02:55 -0400306 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500307 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
308 return samplerMap;
309 }
David Neto22f144c2017-06-12 14:26:21 -0400310 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
311 return GlobalConstFuncTypeMap;
312 }
313 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
314 return GlobalConstArgumentSet;
315 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500316 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400317
SJW77b87ad2020-04-21 14:37:52 -0500318 void GenerateLLVMIRInfo();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500319 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
320 // *not* be converted to a storage buffer, replace each such global variable
321 // with one in the storage class expecgted by SPIR-V.
SJW77b87ad2020-04-21 14:37:52 -0500322 void FindGlobalConstVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
324 // ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -0500325 void FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400326 void FindTypePerGlobalVar(GlobalVariable &GV);
327 void FindTypePerFunc(Function &F);
SJW77b87ad2020-04-21 14:37:52 -0500328 void FindTypesForSamplerMap();
329 void FindTypesForResourceVars();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500330 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
331 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400332 void FindType(Type *Ty);
SJWf93f5f32020-05-05 07:27:56 -0500333
alan-bakerc3fd07f2020-10-22 09:48:49 -0400334 // Returns the canonical type of |type|.
335 //
336 // By default, clspv maps both __constant and __global address space pointers
337 // to StorageBuffer storage class. In order to prevent duplicate types from
338 // being generated, clspv uses the canonical type as a representative.
339 Type *CanonicalType(Type *type);
340
SJWf93f5f32020-05-05 07:27:56 -0500341 // Lookup or create Types, Constants.
342 // Returns SPIRVID once it has been created.
343 SPIRVID getSPIRVType(Type *Ty);
344 SPIRVID getSPIRVConstant(Constant *Cst);
SJW806a5d82020-07-15 12:51:38 -0500345 SPIRVID getSPIRVInt32Constant(uint32_t CstVal);
SJWf93f5f32020-05-05 07:27:56 -0500346 // Lookup SPIRVID of llvm::Value, may create Constant.
347 SPIRVID getSPIRVValue(Value *V);
348
SJW806a5d82020-07-15 12:51:38 -0500349 SPIRVID getSPIRVBuiltin(spv::BuiltIn BID, spv::Capability Cap);
350
David Neto19a1bad2017-08-25 15:01:41 -0400351 // Generates instructions for SPIR-V types corresponding to the LLVM types
352 // saved in the |Types| member. A type follows its subtypes. IDs are
353 // allocated sequentially starting with the current value of nextID, and
354 // with a type following its subtypes. Also updates nextID to just beyond
355 // the last generated ID.
SJW77b87ad2020-04-21 14:37:52 -0500356 void GenerateSPIRVTypes();
SJW77b87ad2020-04-21 14:37:52 -0500357 void GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400358 void GenerateGlobalVar(GlobalVariable &GV);
SJW77b87ad2020-04-21 14:37:52 -0500359 void GenerateWorkgroupVars();
alan-baker86ce19c2020-08-05 13:09:19 -0400360 // Generate reflection instructions for resource variables associated with
David Neto862b7d82018-06-14 18:48:37 -0400361 // arguments to F.
SJW77b87ad2020-04-21 14:37:52 -0500362 void GenerateSamplers();
David Neto862b7d82018-06-14 18:48:37 -0400363 // Generate OpVariables for %clspv.resource.var.* calls.
SJW77b87ad2020-04-21 14:37:52 -0500364 void GenerateResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400365 void GenerateFuncPrologue(Function &F);
366 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400367 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400368 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
369 spv::Op GetSPIRVCastOpcode(Instruction &I);
370 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
SJW806a5d82020-07-15 12:51:38 -0500371 SPIRVID GenerateClspvInstruction(CallInst *Call,
372 const FunctionInfo &FuncInfo);
373 SPIRVID GenerateImageInstruction(CallInst *Call,
374 const FunctionInfo &FuncInfo);
375 SPIRVID GenerateSubgroupInstruction(CallInst *Call,
376 const FunctionInfo &FuncInfo);
377 SPIRVID GenerateInstructionFromCall(CallInst *Call);
David Neto22f144c2017-06-12 14:26:21 -0400378 void GenerateInstruction(Instruction &I);
379 void GenerateFuncEpilogue();
380 void HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500381 void HandleDeferredDecorations();
David Neto22f144c2017-06-12 14:26:21 -0400382 bool is4xi8vec(Type *Ty) const;
383 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400384 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400385 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400386 // Returns the GLSL extended instruction enum that the given function
387 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500388 glsl::ExtInst getExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400389 // Returns the GLSL extended instruction enum indirectly used by the given
390 // function. That is, to implement the given function, we use an extended
391 // instruction plus one more instruction. If none, then returns the 0 value,
392 // i.e. GLSLstd4580Bad.
SJW61531372020-06-09 07:31:08 -0500393 glsl::ExtInst getIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto3fbb4072017-10-16 11:28:14 -0400394 // Returns the single GLSL extended instruction used directly or
395 // indirectly by the given function call.
SJW61531372020-06-09 07:31:08 -0500396 glsl::ExtInst
397 getDirectOrIndirectExtInstEnum(const Builtins::FunctionInfo &func_info);
David Neto22f144c2017-06-12 14:26:21 -0400398 void WriteOneWord(uint32_t Word);
SJW88ed5fe2020-05-11 12:40:57 -0500399 void WriteResultID(const SPIRVInstruction &Inst);
400 void WriteWordCountAndOpcode(const SPIRVInstruction &Inst);
401 void WriteOperand(const SPIRVOperand &Op);
David Neto22f144c2017-06-12 14:26:21 -0400402 void WriteSPIRVBinary();
SJW69939d52020-04-16 07:29:07 -0500403 void WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList);
David Neto22f144c2017-06-12 14:26:21 -0400404
Alan Baker9bf93fb2018-08-28 16:59:26 -0400405 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500406 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400407
Alan Bakerfcda9482018-10-02 17:09:59 -0400408 // Populate UBO remapped type maps.
SJW77b87ad2020-04-21 14:37:52 -0500409 void PopulateUBOTypeMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400410
alan-baker06cad652019-12-03 17:56:47 -0500411 // Populate the merge and continue block maps.
SJW77b87ad2020-04-21 14:37:52 -0500412 void PopulateStructuredCFGMaps();
alan-baker06cad652019-12-03 17:56:47 -0500413
Alan Bakerfcda9482018-10-02 17:09:59 -0400414 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
415 // uses the internal map, otherwise it falls back on the data layout.
416 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
417 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
418 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
Kévin Petitbbbda972020-03-03 19:16:31 +0000419 uint32_t GetExplicitLayoutStructMemberOffset(StructType *type,
420 unsigned member,
421 const DataLayout &DL);
Alan Bakerfcda9482018-10-02 17:09:59 -0400422
alan-baker5b86ed72019-02-15 08:26:50 -0500423 // Returns the base pointer of |v|.
424 Value *GetBasePointer(Value *v);
425
SJW01901d92020-05-21 08:58:31 -0500426 // Add Capability if not already (e.g. CapabilityGroupNonUniformBroadcast)
427 void addCapability(uint32_t c) { CapabilitySet.emplace(c); }
428
alan-baker5b86ed72019-02-15 08:26:50 -0500429 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
430 // |address_space|.
431 void setVariablePointersCapabilities(unsigned address_space);
432
433 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
434 // variable.
435 bool sameResource(Value *lhs, Value *rhs) const;
436
437 // Returns true if |inst| is phi or select that selects from the same
438 // structure (or null).
439 bool selectFromSameObject(Instruction *inst);
440
alan-bakere9308012019-03-15 10:25:13 -0400441 // Returns true if |Arg| is called with a coherent resource.
442 bool CalledWithCoherentResource(Argument &Arg);
443
SJWf93f5f32020-05-05 07:27:56 -0500444 //
445 // Primary interface for adding SPIRVInstructions to a SPIRVSection.
446 template <enum SPIRVSection TSection = kFunctions>
447 SPIRVID addSPIRVInst(spv::Op Opcode, SPIRVOperandVec &Operands) {
448 bool has_result, has_result_type;
449 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
450 SPIRVID RID = has_result ? incrNextID() : 0;
SJW88ed5fe2020-05-11 12:40:57 -0500451 SPIRVSections[TSection].emplace_back(Opcode, RID, Operands);
SJWf93f5f32020-05-05 07:27:56 -0500452 return RID;
453 }
454 template <enum SPIRVSection TSection = kFunctions>
455 SPIRVID addSPIRVInst(spv::Op Op) {
456 SPIRVOperandVec Ops;
457 return addSPIRVInst<TSection>(Op, Ops);
458 }
459 template <enum SPIRVSection TSection = kFunctions>
460 SPIRVID addSPIRVInst(spv::Op Op, uint32_t V) {
461 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500462 Ops.emplace_back(LITERAL_WORD, V);
SJWf93f5f32020-05-05 07:27:56 -0500463 return addSPIRVInst<TSection>(Op, Ops);
464 }
465 template <enum SPIRVSection TSection = kFunctions>
466 SPIRVID addSPIRVInst(spv::Op Op, const char *V) {
467 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -0500468 Ops.emplace_back(LITERAL_STRING, V);
SJWf93f5f32020-05-05 07:27:56 -0500469 return addSPIRVInst<TSection>(Op, Ops);
470 }
471
SJW88ed5fe2020-05-11 12:40:57 -0500472 //
473 // Add placeholder for llvm::Value that references future values.
474 // Must have result ID just in case final SPIRVInstruction requires.
475 SPIRVID addSPIRVPlaceholder(Value *I) {
476 SPIRVID RID = incrNextID();
477 SPIRVOperandVec Ops;
478 SPIRVSections[kFunctions].emplace_back(spv::OpExtInst, RID, Ops);
479 DeferredInstVec.push_back({I, &SPIRVSections[kFunctions].back()});
480 return RID;
481 }
482 // Replace placeholder with actual SPIRVInstruction on the final pass
483 // (HandleDeferredInstruction).
484 SPIRVID replaceSPIRVInst(SPIRVInstruction *I, spv::Op Opcode,
485 SPIRVOperandVec &Operands) {
486 bool has_result, has_result_type;
487 spv::HasResultAndType(Opcode, &has_result, &has_result_type);
488 SPIRVID RID = has_result ? I->getResultID() : 0;
489 *I = SPIRVInstruction(Opcode, RID, Operands);
490 return RID;
491 }
492
SJW806a5d82020-07-15 12:51:38 -0500493 //
494 // Add global variable and capture entry point interface
495 SPIRVID addSPIRVGlobalVariable(const SPIRVID &TypeID, spv::StorageClass SC,
496 const SPIRVID &InitID = SPIRVID());
497
alan-baker86ce19c2020-08-05 13:09:19 -0400498 SPIRVID getReflectionImport();
499 void GenerateReflection();
500 void GenerateKernelReflection();
501 void GeneratePushConstantReflection();
502 void GenerateSpecConstantReflection();
503 void AddArgumentReflection(SPIRVID kernel_decl, const std::string &name,
504 clspv::ArgKind arg_kind, uint32_t ordinal,
505 uint32_t descriptor_set, uint32_t binding,
506 uint32_t offset, uint32_t size, uint32_t spec_id,
507 uint32_t elem_size);
508
David Neto22f144c2017-06-12 14:26:21 -0400509private:
510 static char ID;
SJW77b87ad2020-04-21 14:37:52 -0500511
512 Module *module;
513
SJW01901d92020-05-21 08:58:31 -0500514 // Set of Capabilities required
515 CapabilitySetType CapabilitySet;
516
SJW806a5d82020-07-15 12:51:38 -0500517 // Map from clspv::BuiltinType to SPIRV Global Variable
518 BuiltinConstantMapType BuiltinConstantMap;
519
David Neto44795152017-07-13 15:45:28 -0400520 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400521 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400522
523 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
524 // convert to other formats on demand?
525
526 // When emitting a C initialization list, the WriteSPIRVBinary method
527 // will actually write its words to this vector via binaryTempOut.
528 SmallVector<char, 100> binaryTempUnderlyingVector;
529 raw_svector_ostream binaryTempOut;
530
531 // Binary output writes to this stream, which might be |out| or
532 // |binaryTempOut|. It's the latter when we really want to write a C
533 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400534 raw_pwrite_stream *binaryOut;
David Neto0676e6f2017-07-11 18:47:44 -0400535 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400536 uint64_t patchBoundOffset;
537 uint32_t nextID;
538
SJWf93f5f32020-05-05 07:27:56 -0500539 SPIRVID incrNextID() { return nextID++; }
540
alan-bakerf67468c2019-11-25 15:51:49 -0500541 // ID for OpTypeInt 32 1.
SJW01901d92020-05-21 08:58:31 -0500542 SPIRVID int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500543 // ID for OpTypeVector %int 4.
SJW01901d92020-05-21 08:58:31 -0500544 SPIRVID v4int32ID;
alan-bakerf67468c2019-11-25 15:51:49 -0500545
David Neto19a1bad2017-08-25 15:01:41 -0400546 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400547 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400548 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400549 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400550 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400551 TypeList Types;
David Neto19a1bad2017-08-25 15:01:41 -0400552 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400553 ValueMapType ValueMap;
SJW69939d52020-04-16 07:29:07 -0500554 SPIRVInstructionList SPIRVSections[kSectionCount];
David Neto862b7d82018-06-14 18:48:37 -0400555
David Neto22f144c2017-06-12 14:26:21 -0400556 EntryPointVecType EntryPointVec;
557 DeferredInstVecType DeferredInstVec;
SJW806a5d82020-07-15 12:51:38 -0500558 SPIRVIDListType EntryPointInterfacesList;
SJW01901d92020-05-21 08:58:31 -0500559 SPIRVID OpExtInstImportID;
560 std::vector<SPIRVID> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500561 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400562 bool HasVariablePointers;
563 Type *SamplerTy;
SJW01901d92020-05-21 08:58:31 -0500564 DenseMap<unsigned, SPIRVID> SamplerLiteralToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700565
566 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700567 // will map F's type to (G, index of the parameter), where in a first phase
568 // G is F's type. During FindTypePerFunc, G will be changed to F's type
569 // but replacing the pointer-to-constant parameter with
570 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700571 // TODO(dneto): This doesn't seem general enough? A function might have
572 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400573 GlobalConstFuncMapType GlobalConstFuncTypeMap;
574 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400575 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700576 // or array types, and which point into transparent memory (StorageBuffer
577 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400578 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700579 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400580
581 // This is truly ugly, but works around what look like driver bugs.
582 // For get_local_size, an earlier part of the flow has created a module-scope
583 // variable in Private address space to hold the value for the workgroup
584 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
585 // When this is present, save the IDs of the initializer value and variable
586 // in these two variables. We only ever do a vector load from it, and
587 // when we see one of those, substitute just the value of the intializer.
588 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700589 // TODO(dneto): Remove this once drivers are fixed.
SJW01901d92020-05-21 08:58:31 -0500590 SPIRVID WorkgroupSizeValueID;
591 SPIRVID WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400592
David Neto862b7d82018-06-14 18:48:37 -0400593 // Bookkeeping for mapping kernel arguments to resource variables.
594 struct ResourceVarInfo {
595 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400596 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400597 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400598 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400599 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
600 const int index; // Index into ResourceVarInfoList
601 const unsigned descriptor_set;
602 const unsigned binding;
603 Function *const var_fn; // The @clspv.resource.var.* function.
604 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400605 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400606 const unsigned addr_space; // The LLVM address space
607 // The SPIR-V ID of the OpVariable. Not populated at construction time.
SJW01901d92020-05-21 08:58:31 -0500608 SPIRVID var_id;
David Neto862b7d82018-06-14 18:48:37 -0400609 };
610 // A list of resource var info. Each one correponds to a module-scope
611 // resource variable we will have to create. Resource var indices are
612 // indices into this vector.
613 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
614 // This is a vector of pointers of all the resource vars, but ordered by
615 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500616 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400617 // Map a function to the ordered list of resource variables it uses, one for
618 // each argument. If an argument does not use a resource variable, it
619 // will have a null pointer entry.
620 using FunctionToResourceVarsMapType =
621 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
622 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
623
624 // What LLVM types map to SPIR-V types needing layout? These are the
625 // arrays and structures supporting storage buffers and uniform buffers.
626 TypeList TypesNeedingLayout;
627 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
628 UniqueVector<StructType *> StructTypesNeedingBlock;
629 // For a call that represents a load from an opaque type (samplers, images),
630 // map it to the variable id it should load from.
SJW01901d92020-05-21 08:58:31 -0500631 DenseMap<CallInst *, SPIRVID> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700632
David Netoc6f3ab22018-04-06 18:02:31 -0400633 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500634 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400635 LocalArgList LocalArgs;
636 // Information about a pointer-to-local argument.
637 struct LocalArgInfo {
638 // The SPIR-V ID of the array variable.
SJW01901d92020-05-21 08:58:31 -0500639 SPIRVID variable_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400640 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500641 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400642 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500643 SPIRVID array_size_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400644 // The ID of the array type.
SJW01901d92020-05-21 08:58:31 -0500645 SPIRVID array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400646 // The ID of the pointer to the array type.
SJW01901d92020-05-21 08:58:31 -0500647 SPIRVID ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400648 // The specialization constant ID of the array size.
649 int spec_id;
650 };
Alan Baker202c8c72018-08-13 13:47:44 -0400651 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500652 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400653 // A mapping from SpecId to its LocalArgInfo.
654 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400655 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500656 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400657 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500658 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
659 RemappedUBOTypeSizes;
alan-baker06cad652019-12-03 17:56:47 -0500660
661 // Maps basic block to its merge block.
662 DenseMap<BasicBlock *, BasicBlock *> MergeBlocks;
663 // Maps basic block to its continue block.
664 DenseMap<BasicBlock *, BasicBlock *> ContinueBlocks;
SJW01901d92020-05-21 08:58:31 -0500665
alan-baker86ce19c2020-08-05 13:09:19 -0400666 SPIRVID ReflectionID;
667 DenseMap<Function *, SPIRVID> KernelDeclarations;
668
SJW01901d92020-05-21 08:58:31 -0500669public:
670 static SPIRVProducerPass *Ptr;
David Neto22f144c2017-06-12 14:26:21 -0400671};
672
673char SPIRVProducerPass::ID;
SJW01901d92020-05-21 08:58:31 -0500674SPIRVProducerPass *SPIRVProducerPass::Ptr = nullptr;
David Netoc6f3ab22018-04-06 18:02:31 -0400675
alan-bakerb6b09dc2018-11-08 16:59:28 -0500676} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400677
678namespace clspv {
alan-baker86ce19c2020-08-05 13:09:19 -0400679ModulePass *
680createSPIRVProducerPass(raw_pwrite_stream &out,
681 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
682 bool outputCInitList) {
683 return new SPIRVProducerPass(out, samplerMap, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400684}
David Netoc2c368d2017-06-30 16:50:17 -0400685} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400686
SJW01901d92020-05-21 08:58:31 -0500687namespace {
688SPIRVOperandVec &operator<<(SPIRVOperandVec &list, uint32_t num) {
689 list.emplace_back(LITERAL_WORD, num);
690 return list;
691}
692
693SPIRVOperandVec &operator<<(SPIRVOperandVec &list, int32_t num) {
694 list.emplace_back(LITERAL_WORD, static_cast<uint32_t>(num));
695 return list;
696}
697
698SPIRVOperandVec &operator<<(SPIRVOperandVec &list, ArrayRef<uint32_t> num_vec) {
699 list.emplace_back(num_vec);
700 return list;
701}
702
703SPIRVOperandVec &operator<<(SPIRVOperandVec &list, StringRef str) {
704 list.emplace_back(LITERAL_STRING, str);
705 return list;
706}
707
708SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Type *t) {
709 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVType(t).get());
710 return list;
711}
712
713SPIRVOperandVec &operator<<(SPIRVOperandVec &list, Value *v) {
714 list.emplace_back(NUMBERID, SPIRVProducerPass::Ptr->getSPIRVValue(v).get());
715 return list;
716}
717
SJW806a5d82020-07-15 12:51:38 -0500718SPIRVOperandVec &operator<<(SPIRVOperandVec &list, const SPIRVID &v) {
SJW01901d92020-05-21 08:58:31 -0500719 list.emplace_back(NUMBERID, v.get());
720 return list;
721}
722} // namespace
723
SJW77b87ad2020-04-21 14:37:52 -0500724bool SPIRVProducerPass::runOnModule(Module &M) {
SJW01901d92020-05-21 08:58:31 -0500725 // TODO(sjw): Need to reset all data members for each Module, or better
726 // yet create a new SPIRVProducer for every module.. For now only
727 // allow 1 call.
728 assert(module == nullptr);
SJW77b87ad2020-04-21 14:37:52 -0500729 module = &M;
alan-baker5ed87542020-03-23 11:05:22 -0400730 if (ShowProducerIR) {
SJW77b87ad2020-04-21 14:37:52 -0500731 llvm::outs() << *module << "\n";
alan-baker5ed87542020-03-23 11:05:22 -0400732 }
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut = outputCInitList ? &binaryTempOut : &out;
734
SJW77b87ad2020-04-21 14:37:52 -0500735 PopulateUBOTypeMaps();
736 PopulateStructuredCFGMaps();
Alan Bakerfcda9482018-10-02 17:09:59 -0400737
David Neto22f144c2017-06-12 14:26:21 -0400738 // SPIR-V always begins with its header information
739 outputHeader();
740
741 // Gather information from the LLVM IR that we require.
SJW77b87ad2020-04-21 14:37:52 -0500742 GenerateLLVMIRInfo();
David Neto22f144c2017-06-12 14:26:21 -0400743
David Neto22f144c2017-06-12 14:26:21 -0400744 // Collect information on global variables too.
SJW77b87ad2020-04-21 14:37:52 -0500745 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400746 // If the GV is one of our special __spirv_* variables, remove the
747 // initializer as it was only placed there to force LLVM to not throw the
748 // value away.
Kévin Petitbbbda972020-03-03 19:16:31 +0000749 if (GV.getName().startswith("__spirv_") ||
750 GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
David Neto22f144c2017-06-12 14:26:21 -0400751 GV.setInitializer(nullptr);
752 }
753
754 // Collect types' information from global variable.
755 FindTypePerGlobalVar(GV);
David Neto22f144c2017-06-12 14:26:21 -0400756 }
757
David Neto22f144c2017-06-12 14:26:21 -0400758 // Generate SPIRV instructions for types.
SJW77b87ad2020-04-21 14:37:52 -0500759 GenerateSPIRVTypes();
David Neto22f144c2017-06-12 14:26:21 -0400760
alan-baker09cb9802019-12-10 13:16:27 -0500761 // Generate literal samplers if necessary.
SJW77b87ad2020-04-21 14:37:52 -0500762 GenerateSamplers();
David Neto22f144c2017-06-12 14:26:21 -0400763
764 // Generate SPIRV variables.
SJW77b87ad2020-04-21 14:37:52 -0500765 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400766 GenerateGlobalVar(GV);
767 }
SJW77b87ad2020-04-21 14:37:52 -0500768 GenerateResourceVars();
769 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400770
771 // Generate SPIRV instructions for each function.
SJW77b87ad2020-04-21 14:37:52 -0500772 for (Function &F : *module) {
David Neto22f144c2017-06-12 14:26:21 -0400773 if (F.isDeclaration()) {
774 continue;
775 }
776
777 // Generate Function Prologue.
778 GenerateFuncPrologue(F);
779
780 // Generate SPIRV instructions for function body.
781 GenerateFuncBody(F);
782
783 // Generate Function Epilogue.
784 GenerateFuncEpilogue();
785 }
786
787 HandleDeferredInstruction();
SJW77b87ad2020-04-21 14:37:52 -0500788 HandleDeferredDecorations();
alan-bakera1be3322020-04-20 12:48:18 -0400789
David Neto22f144c2017-06-12 14:26:21 -0400790 // Generate SPIRV module information.
SJW77b87ad2020-04-21 14:37:52 -0500791 GenerateModuleInfo();
David Neto22f144c2017-06-12 14:26:21 -0400792
alan-baker86ce19c2020-08-05 13:09:19 -0400793 // Generate embedded reflection information.
794 GenerateReflection();
795
alan-baker00e7a582019-06-07 12:54:21 -0400796 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400797
798 // We need to patch the SPIR-V header to set bound correctly.
799 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400800
801 if (outputCInitList) {
802 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400803 std::ostringstream os;
804
David Neto57fb0b92017-08-04 15:35:09 -0400805 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400806 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400807 os << ",\n";
808 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400809 first = false;
810 };
811
812 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400813 const std::string str(binaryTempOut.str());
814 for (unsigned i = 0; i < str.size(); i += 4) {
815 const uint32_t a = static_cast<unsigned char>(str[i]);
816 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
817 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
818 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
819 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400820 }
821 os << "}\n";
822 out << os.str();
823 }
824
David Neto22f144c2017-06-12 14:26:21 -0400825 return false;
826}
827
828void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400829 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
830 sizeof(spv::MagicNumber));
SJW806a5d82020-07-15 12:51:38 -0500831 uint32_t minor = 0;
832 if (SpvVersion() == SPIRVVersion::SPIRV_1_3) {
833 minor = 3;
834 }
835 uint32_t version = (1 << 16) | (minor << 8);
836 binaryOut->write(reinterpret_cast<const char *>(&version), sizeof(version));
David Neto22f144c2017-06-12 14:26:21 -0400837
alan-baker0c18ab02019-06-12 10:23:21 -0400838 // use Google's vendor ID
839 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400840 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400841
alan-baker00e7a582019-06-07 12:54:21 -0400842 // we record where we need to come back to and patch in the bound value
843 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400844
alan-baker00e7a582019-06-07 12:54:21 -0400845 // output a bad bound for now
846 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400847
alan-baker00e7a582019-06-07 12:54:21 -0400848 // output the schema (reserved for use and must be 0)
849 const uint32_t schema = 0;
850 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400851}
852
853void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400854 // for a binary we just write the value of nextID over bound
855 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
856 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400857}
858
SJW77b87ad2020-04-21 14:37:52 -0500859void SPIRVProducerPass::GenerateLLVMIRInfo() {
David Neto22f144c2017-06-12 14:26:21 -0400860 // This function generates LLVM IR for function such as global variable for
861 // argument, constant and pointer type for argument access. These information
862 // is artificial one because we need Vulkan SPIR-V output. This function is
863 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400864
SJW77b87ad2020-04-21 14:37:52 -0500865 FindGlobalConstVars();
David Neto5c22a252018-03-15 16:07:41 -0400866
SJW77b87ad2020-04-21 14:37:52 -0500867 FindResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400868
869 bool HasWorkGroupBuiltin = false;
SJW77b87ad2020-04-21 14:37:52 -0500870 for (GlobalVariable &GV : module->globals()) {
David Neto22f144c2017-06-12 14:26:21 -0400871 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
872 if (spv::BuiltInWorkgroupSize == BuiltinType) {
873 HasWorkGroupBuiltin = true;
874 }
875 }
876
SJW77b87ad2020-04-21 14:37:52 -0500877 FindTypesForSamplerMap();
878 FindTypesForResourceVars();
David Neto22f144c2017-06-12 14:26:21 -0400879}
880
SJW77b87ad2020-04-21 14:37:52 -0500881void SPIRVProducerPass::FindGlobalConstVars() {
882 clspv::NormalizeGlobalVariables(*module);
883 const DataLayout &DL = module->getDataLayout();
alan-baker56f7aff2019-05-22 08:06:42 -0400884
David Neto862b7d82018-06-14 18:48:37 -0400885 SmallVector<GlobalVariable *, 8> GVList;
886 SmallVector<GlobalVariable *, 8> DeadGVList;
SJW77b87ad2020-04-21 14:37:52 -0500887 for (GlobalVariable &GV : module->globals()) {
David Neto862b7d82018-06-14 18:48:37 -0400888 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
889 if (GV.use_empty()) {
890 DeadGVList.push_back(&GV);
891 } else {
892 GVList.push_back(&GV);
893 }
894 }
895 }
896
897 // Remove dead global __constant variables.
898 for (auto GV : DeadGVList) {
899 GV->eraseFromParent();
900 }
901 DeadGVList.clear();
902
903 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
904 // For now, we only support a single storage buffer.
alan-baker7506abb2020-09-10 15:02:55 -0400905 if (!GVList.empty()) {
David Neto862b7d82018-06-14 18:48:37 -0400906 assert(GVList.size() == 1);
907 const auto *GV = GVList[0];
908 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400909 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400910 const size_t kConstantMaxSize = 65536;
911 if (constants_byte_size > kConstantMaxSize) {
912 outs() << "Max __constant capacity of " << kConstantMaxSize
913 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
914 llvm_unreachable("Max __constant capacity exceeded");
915 }
916 }
917 } else {
918 // Change global constant variable's address space to ModuleScopePrivate.
919 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
920 for (auto GV : GVList) {
921 // Create new gv with ModuleScopePrivate address space.
922 Type *NewGVTy = GV->getType()->getPointerElementType();
923 GlobalVariable *NewGV = new GlobalVariable(
SJW77b87ad2020-04-21 14:37:52 -0500924 *module, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
David Neto862b7d82018-06-14 18:48:37 -0400925 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
926 NewGV->takeName(GV);
927
928 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
929 SmallVector<User *, 8> CandidateUsers;
930
931 auto record_called_function_type_as_user =
932 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
933 // Find argument index.
934 unsigned index = 0;
935 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
936 if (gv == call->getOperand(i)) {
937 // TODO(dneto): Should we break here?
938 index = i;
939 }
940 }
941
942 // Record function type with global constant.
943 GlobalConstFuncTyMap[call->getFunctionType()] =
944 std::make_pair(call->getFunctionType(), index);
945 };
946
947 for (User *GVU : GVUsers) {
948 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
949 record_called_function_type_as_user(GV, Call);
950 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
951 // Check GEP users.
952 for (User *GEPU : GEP->users()) {
953 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
954 record_called_function_type_as_user(GEP, GEPCall);
955 }
956 }
957 }
958
959 CandidateUsers.push_back(GVU);
960 }
961
962 for (User *U : CandidateUsers) {
963 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500964 if (!isa<Constant>(U)) {
965 // #254: Can't change operands of a constant, but this shouldn't be
966 // something that sticks around in the module.
967 U->replaceUsesOfWith(GV, NewGV);
968 }
David Neto862b7d82018-06-14 18:48:37 -0400969 }
970
971 // Delete original gv.
972 GV->eraseFromParent();
973 }
974 }
975}
976
SJW77b87ad2020-04-21 14:37:52 -0500977void SPIRVProducerPass::FindResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -0400978 ResourceVarInfoList.clear();
979 FunctionToResourceVarsMap.clear();
980 ModuleOrderedResourceVars.reset();
981 // Normally, there is one resource variable per clspv.resource.var.*
982 // function, since that is unique'd by arg type and index. By design,
983 // we can share these resource variables across kernels because all
984 // kernels use the same descriptor set.
985 //
986 // But if the user requested distinct descriptor sets per kernel, then
987 // the descriptor allocator has made different (set,binding) pairs for
988 // the same (type,arg_index) pair. Since we can decorate a resource
989 // variable with only exactly one DescriptorSet and Binding, we are
990 // forced in this case to make distinct resource variables whenever
Kévin Petitbbbda972020-03-03 19:16:31 +0000991 // the same clspv.resource.var.X function is seen with disintct
David Neto862b7d82018-06-14 18:48:37 -0400992 // (set,binding) values.
993 const bool always_distinct_sets =
994 clspv::Option::DistinctKernelDescriptorSets();
SJW77b87ad2020-04-21 14:37:52 -0500995 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -0400996 // Rely on the fact the resource var functions have a stable ordering
997 // in the module.
SJW61531372020-06-09 07:31:08 -0500998 if (Builtins::Lookup(&F) == Builtins::kClspvResource) {
David Neto862b7d82018-06-14 18:48:37 -0400999 // Find all calls to this function with distinct set and binding pairs.
1000 // Save them in ResourceVarInfoList.
1001
1002 // Determine uniqueness of the (set,binding) pairs only withing this
1003 // one resource-var builtin function.
1004 using SetAndBinding = std::pair<unsigned, unsigned>;
1005 // Maps set and binding to the resource var info.
1006 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1007 bool first_use = true;
1008 for (auto &U : F.uses()) {
1009 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1010 const auto set = unsigned(
1011 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1012 const auto binding = unsigned(
1013 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1014 const auto arg_kind = clspv::ArgKind(
1015 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1016 const auto arg_index = unsigned(
1017 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001018 const auto coherent = unsigned(
1019 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001020
1021 // Find or make the resource var info for this combination.
1022 ResourceVarInfo *rv = nullptr;
1023 if (always_distinct_sets) {
1024 // Make a new resource var any time we see a different
1025 // (set,binding) pair.
1026 SetAndBinding key{set, binding};
1027 auto where = set_and_binding_map.find(key);
1028 if (where == set_and_binding_map.end()) {
alan-baker7506abb2020-09-10 15:02:55 -04001029 rv = new ResourceVarInfo(
1030 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1031 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001032 ResourceVarInfoList.emplace_back(rv);
1033 set_and_binding_map[key] = rv;
1034 } else {
1035 rv = where->second;
1036 }
1037 } else {
1038 // The default is to make exactly one resource for each
1039 // clspv.resource.var.* function.
1040 if (first_use) {
1041 first_use = false;
alan-baker7506abb2020-09-10 15:02:55 -04001042 rv = new ResourceVarInfo(
1043 static_cast<int>(ResourceVarInfoList.size()), set, binding,
1044 &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001045 ResourceVarInfoList.emplace_back(rv);
1046 } else {
1047 rv = ResourceVarInfoList.back().get();
1048 }
1049 }
1050
1051 // Now populate FunctionToResourceVarsMap.
1052 auto &mapping =
1053 FunctionToResourceVarsMap[call->getParent()->getParent()];
1054 while (mapping.size() <= arg_index) {
1055 mapping.push_back(nullptr);
1056 }
1057 mapping[arg_index] = rv;
1058 }
1059 }
1060 }
1061 }
1062
1063 // Populate ModuleOrderedResourceVars.
SJW77b87ad2020-04-21 14:37:52 -05001064 for (Function &F : *module) {
David Neto862b7d82018-06-14 18:48:37 -04001065 auto where = FunctionToResourceVarsMap.find(&F);
1066 if (where != FunctionToResourceVarsMap.end()) {
1067 for (auto &rv : where->second) {
1068 if (rv != nullptr) {
1069 ModuleOrderedResourceVars.insert(rv);
1070 }
1071 }
1072 }
1073 }
1074 if (ShowResourceVars) {
1075 for (auto *info : ModuleOrderedResourceVars) {
1076 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1077 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1078 << "\n";
1079 }
1080 }
1081}
1082
David Neto22f144c2017-06-12 14:26:21 -04001083void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1084 // Investigate global variable's type.
1085 FindType(GV.getType());
1086}
1087
1088void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1089 // Investigate function's type.
1090 FunctionType *FTy = F.getFunctionType();
1091
1092 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1093 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001094 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001095 if (GlobalConstFuncTyMap.count(FTy)) {
1096 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1097 SmallVector<Type *, 4> NewFuncParamTys;
1098 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1099 Type *ParamTy = FTy->getParamType(i);
1100 if (i == GVCstArgIdx) {
1101 Type *EleTy = ParamTy->getPointerElementType();
1102 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1103 }
1104
1105 NewFuncParamTys.push_back(ParamTy);
1106 }
1107
1108 FunctionType *NewFTy =
1109 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1110 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1111 FTy = NewFTy;
1112 }
1113
1114 FindType(FTy);
1115 } else {
1116 // As kernel functions do not have parameters, create new function type and
1117 // add it to type map.
1118 SmallVector<Type *, 4> NewFuncParamTys;
1119 FunctionType *NewFTy =
1120 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1121 FindType(NewFTy);
1122 }
1123
1124 // Investigate instructions' type in function body.
1125 for (BasicBlock &BB : F) {
1126 for (Instruction &I : BB) {
1127 if (isa<ShuffleVectorInst>(I)) {
1128 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1129 // Ignore type for mask of shuffle vector instruction.
1130 if (i == 2) {
1131 continue;
1132 }
1133
1134 Value *Op = I.getOperand(i);
1135 if (!isa<MetadataAsValue>(Op)) {
1136 FindType(Op->getType());
1137 }
1138 }
1139
1140 FindType(I.getType());
1141 continue;
1142 }
1143
David Neto862b7d82018-06-14 18:48:37 -04001144 CallInst *Call = dyn_cast<CallInst>(&I);
1145
SJW61531372020-06-09 07:31:08 -05001146 if (Call) {
1147 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
1148 if (func_info.getType() == Builtins::kClspvResource ||
1149 func_info.getType() == Builtins::kClspvLocal) {
1150 // This is a fake call representing access to a resource/workgroup
1151 // variable. We handle that elsewhere.
1152 continue;
1153 }
Alan Baker202c8c72018-08-13 13:47:44 -04001154 }
1155
alan-bakerf083bed2020-01-29 08:15:42 -05001156 // #497: InsertValue and ExtractValue map to OpCompositeInsert and
1157 // OpCompositeExtract which takes literal values for indices. As a result
1158 // don't map the type of indices.
1159 if (I.getOpcode() == Instruction::ExtractValue) {
1160 FindType(I.getOperand(0)->getType());
1161 continue;
1162 }
1163 if (I.getOpcode() == Instruction::InsertValue) {
1164 FindType(I.getOperand(0)->getType());
1165 FindType(I.getOperand(1)->getType());
1166 continue;
1167 }
1168
1169 // #497: InsertElement and ExtractElement map to OpCompositeExtract if
1170 // the index is a constant. In such a case don't map the index type.
1171 if (I.getOpcode() == Instruction::ExtractElement) {
1172 FindType(I.getOperand(0)->getType());
1173 Value *op1 = I.getOperand(1);
1174 if (!isa<Constant>(op1) || isa<GlobalValue>(op1)) {
1175 FindType(op1->getType());
1176 }
1177 continue;
1178 }
1179 if (I.getOpcode() == Instruction::InsertElement) {
1180 FindType(I.getOperand(0)->getType());
1181 FindType(I.getOperand(1)->getType());
1182 Value *op2 = I.getOperand(2);
1183 if (!isa<Constant>(op2) || isa<GlobalValue>(op2)) {
1184 FindType(op2->getType());
1185 }
1186 continue;
1187 }
1188
David Neto22f144c2017-06-12 14:26:21 -04001189 // Work through the operands of the instruction.
1190 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1191 Value *const Op = I.getOperand(i);
1192 // If any of the operands is a constant, find the type!
1193 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1194 FindType(Op->getType());
1195 }
1196 }
1197
1198 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001199 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001200 // Avoid to check call instruction's type.
1201 break;
1202 }
Alan Baker202c8c72018-08-13 13:47:44 -04001203 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
SJW61531372020-06-09 07:31:08 -05001204 if (Builtins::Lookup(OpCall->getCalledFunction()) ==
1205 Builtins::kClspvLocal) {
Alan Baker202c8c72018-08-13 13:47:44 -04001206 // This is a fake call representing access to a workgroup variable.
1207 // We handle that elsewhere.
1208 continue;
1209 }
1210 }
David Neto22f144c2017-06-12 14:26:21 -04001211 if (!isa<MetadataAsValue>(&Op)) {
1212 FindType(Op->getType());
1213 continue;
1214 }
1215 }
1216
David Neto22f144c2017-06-12 14:26:21 -04001217 // We don't want to track the type of this call as we are going to replace
1218 // it.
SJW61531372020-06-09 07:31:08 -05001219 if (Call && Builtins::Lookup(Call->getCalledFunction()) ==
1220 Builtins::kClspvSamplerVarLiteral) {
David Neto22f144c2017-06-12 14:26:21 -04001221 continue;
1222 }
1223
1224 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1225 // If gep's base operand has ModuleScopePrivate address space, make gep
1226 // return ModuleScopePrivate address space.
1227 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1228 // Add pointer type with private address space for global constant to
1229 // type list.
1230 Type *EleTy = I.getType()->getPointerElementType();
1231 Type *NewPTy =
1232 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1233
1234 FindType(NewPTy);
1235 continue;
1236 }
1237 }
1238
1239 FindType(I.getType());
1240 }
1241 }
1242}
1243
SJW77b87ad2020-04-21 14:37:52 -05001244void SPIRVProducerPass::FindTypesForSamplerMap() {
David Neto862b7d82018-06-14 18:48:37 -04001245 // If we are using a sampler map, find the type of the sampler.
SJW77b87ad2020-04-21 14:37:52 -05001246 if (module->getFunction(clspv::LiteralSamplerFunction()) ||
alan-baker7506abb2020-09-10 15:02:55 -04001247 !getSamplerMap().empty()) {
SJW77b87ad2020-04-21 14:37:52 -05001248 auto SamplerStructTy = module->getTypeByName("opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001249 if (!SamplerStructTy) {
SJW77b87ad2020-04-21 14:37:52 -05001250 SamplerStructTy =
1251 StructType::create(module->getContext(), "opencl.sampler_t");
David Neto862b7d82018-06-14 18:48:37 -04001252 }
1253
1254 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1255
1256 FindType(SamplerTy);
1257 }
1258}
1259
SJW77b87ad2020-04-21 14:37:52 -05001260void SPIRVProducerPass::FindTypesForResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04001261 // Record types so they are generated.
1262 TypesNeedingLayout.reset();
1263 StructTypesNeedingBlock.reset();
1264
1265 // To match older clspv codegen, generate the float type first if required
1266 // for images.
1267 for (const auto *info : ModuleOrderedResourceVars) {
alan-bakerf6bc8252020-09-23 14:58:55 -04001268 if (info->arg_kind == clspv::ArgKind::SampledImage ||
1269 info->arg_kind == clspv::ArgKind::StorageImage) {
alan-bakerf67468c2019-11-25 15:51:49 -05001270 if (IsIntImageType(info->var_fn->getReturnType())) {
1271 // Nothing for now...
1272 } else if (IsUintImageType(info->var_fn->getReturnType())) {
SJW77b87ad2020-04-21 14:37:52 -05001273 FindType(Type::getInt32Ty(module->getContext()));
alan-bakerf67468c2019-11-25 15:51:49 -05001274 }
1275
1276 // We need "float" either for the sampled type or for the Lod operand.
SJW77b87ad2020-04-21 14:37:52 -05001277 FindType(Type::getFloatTy(module->getContext()));
David Neto862b7d82018-06-14 18:48:37 -04001278 }
1279 }
1280
1281 for (const auto *info : ModuleOrderedResourceVars) {
1282 Type *type = info->var_fn->getReturnType();
1283
1284 switch (info->arg_kind) {
1285 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001286 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001287 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1288 StructTypesNeedingBlock.insert(sty);
1289 } else {
1290 errs() << *type << "\n";
1291 llvm_unreachable("Buffer arguments must map to structures!");
1292 }
1293 break;
1294 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001295 case clspv::ArgKind::PodUBO:
1296 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04001297 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1298 StructTypesNeedingBlock.insert(sty);
1299 } else {
1300 errs() << *type << "\n";
1301 llvm_unreachable("POD arguments must map to structures!");
1302 }
1303 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04001304 case clspv::ArgKind::SampledImage:
1305 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001306 case clspv::ArgKind::Sampler:
1307 // Sampler and image types map to the pointee type but
1308 // in the uniform constant address space.
1309 type = PointerType::get(type->getPointerElementType(),
1310 clspv::AddressSpace::UniformConstant);
1311 break;
1312 default:
1313 break;
1314 }
1315
1316 // The converted type is the type of the OpVariable we will generate.
1317 // If the pointee type is an array of size zero, FindType will convert it
1318 // to a runtime array.
1319 FindType(type);
1320 }
1321
alan-bakerdcd97412019-09-16 15:32:30 -04001322 // If module constants are clustered in a storage buffer then that struct
1323 // needs layout decorations.
1324 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
SJW77b87ad2020-04-21 14:37:52 -05001325 for (GlobalVariable &GV : module->globals()) {
alan-bakerdcd97412019-09-16 15:32:30 -04001326 PointerType *PTy = cast<PointerType>(GV.getType());
1327 const auto AS = PTy->getAddressSpace();
1328 const bool module_scope_constant_external_init =
1329 (AS == AddressSpace::Constant) && GV.hasInitializer();
1330 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
1331 if (module_scope_constant_external_init &&
1332 spv::BuiltInMax == BuiltinType) {
1333 StructTypesNeedingBlock.insert(
1334 cast<StructType>(PTy->getPointerElementType()));
1335 }
1336 }
1337 }
1338
SJW77b87ad2020-04-21 14:37:52 -05001339 for (const GlobalVariable &GV : module->globals()) {
Kévin Petitbbbda972020-03-03 19:16:31 +00001340 if (GV.getAddressSpace() == clspv::AddressSpace::PushConstant) {
1341 auto Ty = cast<PointerType>(GV.getType())->getPointerElementType();
1342 assert(Ty->isStructTy() && "Push constants have to be structures.");
1343 auto STy = cast<StructType>(Ty);
1344 StructTypesNeedingBlock.insert(STy);
1345 }
1346 }
1347
David Neto862b7d82018-06-14 18:48:37 -04001348 // Traverse the arrays and structures underneath each Block, and
1349 // mark them as needing layout.
1350 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1351 StructTypesNeedingBlock.end());
1352 while (!work_list.empty()) {
1353 Type *type = work_list.back();
1354 work_list.pop_back();
1355 TypesNeedingLayout.insert(type);
1356 switch (type->getTypeID()) {
1357 case Type::ArrayTyID:
1358 work_list.push_back(type->getArrayElementType());
1359 if (!Hack_generate_runtime_array_stride_early) {
1360 // Remember this array type for deferred decoration.
1361 TypesNeedingArrayStride.insert(type);
1362 }
1363 break;
1364 case Type::StructTyID:
1365 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1366 work_list.push_back(elem_ty);
1367 }
1368 default:
1369 // This type and its contained types don't get layout.
1370 break;
1371 }
1372 }
1373}
1374
SJWf93f5f32020-05-05 07:27:56 -05001375void SPIRVProducerPass::GenerateWorkgroupVars() {
Alan Baker202c8c72018-08-13 13:47:44 -04001376 // The SpecId assignment for pointer-to-local arguments is recorded in
1377 // module-level metadata. Translate that information into local argument
1378 // information.
SJWf93f5f32020-05-05 07:27:56 -05001379 LLVMContext &Context = module->getContext();
SJW77b87ad2020-04-21 14:37:52 -05001380 NamedMDNode *nmd = module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001381 if (!nmd)
1382 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001383 for (auto operand : nmd->operands()) {
1384 MDTuple *tuple = cast<MDTuple>(operand);
1385 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1386 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001387 ConstantAsMetadata *arg_index_md =
1388 cast<ConstantAsMetadata>(tuple->getOperand(1));
1389 int arg_index = static_cast<int>(
1390 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1391 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001392
1393 ConstantAsMetadata *spec_id_md =
1394 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001395 int spec_id = static_cast<int>(
1396 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001397
Alan Baker202c8c72018-08-13 13:47:44 -04001398 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001399 if (LocalSpecIdInfoMap.count(spec_id))
1400 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001401
SJWf93f5f32020-05-05 07:27:56 -05001402 // Generate the spec constant.
1403 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001404 Ops << Type::getInt32Ty(Context) << 1;
SJWf93f5f32020-05-05 07:27:56 -05001405 SPIRVID ArraySizeID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
Alan Baker202c8c72018-08-13 13:47:44 -04001406
SJWf93f5f32020-05-05 07:27:56 -05001407 // Generate the array type.
1408 Type *ElemTy = arg->getType()->getPointerElementType();
1409 Ops.clear();
1410 // The element type must have been created.
SJW01901d92020-05-21 08:58:31 -05001411 Ops << ElemTy << ArraySizeID;
SJWf93f5f32020-05-05 07:27:56 -05001412
1413 SPIRVID ArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1414
1415 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001416 Ops << spv::StorageClassWorkgroup << ArrayTypeID;
SJWf93f5f32020-05-05 07:27:56 -05001417 SPIRVID PtrArrayTypeID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1418
1419 // Generate OpVariable.
1420 //
1421 // Ops[0] : Result Type ID
1422 // Ops[1] : Storage Class
SJW806a5d82020-07-15 12:51:38 -05001423 SPIRVID VariableID =
1424 addSPIRVGlobalVariable(PtrArrayTypeID, spv::StorageClassWorkgroup);
SJWf93f5f32020-05-05 07:27:56 -05001425
1426 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05001427 Ops << ArraySizeID << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05001428 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1429
1430 LocalArgInfo info{VariableID, ElemTy, ArraySizeID,
1431 ArrayTypeID, PtrArrayTypeID, spec_id};
1432 LocalSpecIdInfoMap[spec_id] = info;
Alan Baker202c8c72018-08-13 13:47:44 -04001433 }
1434}
1435
David Neto22f144c2017-06-12 14:26:21 -04001436void SPIRVProducerPass::FindType(Type *Ty) {
1437 TypeList &TyList = getTypeList();
1438
1439 if (0 != TyList.idFor(Ty)) {
1440 return;
1441 }
1442
1443 if (Ty->isPointerTy()) {
1444 auto AddrSpace = Ty->getPointerAddressSpace();
1445 if ((AddressSpace::Constant == AddrSpace) ||
1446 (AddressSpace::Global == AddrSpace)) {
1447 auto PointeeTy = Ty->getPointerElementType();
1448
1449 if (PointeeTy->isStructTy() &&
1450 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1451 FindType(PointeeTy);
1452 auto ActualPointerTy =
1453 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1454 FindType(ActualPointerTy);
1455 return;
1456 }
1457 }
1458 }
1459
David Neto862b7d82018-06-14 18:48:37 -04001460 // By convention, LLVM array type with 0 elements will map to
1461 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1462 // has a constant number of elements. We need to support type of the
1463 // constant.
1464 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1465 if (arrayTy->getNumElements() > 0) {
1466 LLVMContext &Context = Ty->getContext();
1467 FindType(Type::getInt32Ty(Context));
1468 }
David Neto22f144c2017-06-12 14:26:21 -04001469 }
1470
1471 for (Type *SubTy : Ty->subtypes()) {
1472 FindType(SubTy);
1473 }
1474
1475 TyList.insert(Ty);
1476}
1477
David Neto22f144c2017-06-12 14:26:21 -04001478spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1479 switch (AddrSpace) {
1480 default:
1481 llvm_unreachable("Unsupported OpenCL address space");
1482 case AddressSpace::Private:
1483 return spv::StorageClassFunction;
1484 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001485 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001486 case AddressSpace::Constant:
1487 return clspv::Option::ConstantArgsInUniformBuffer()
1488 ? spv::StorageClassUniform
1489 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001490 case AddressSpace::Input:
1491 return spv::StorageClassInput;
1492 case AddressSpace::Local:
1493 return spv::StorageClassWorkgroup;
1494 case AddressSpace::UniformConstant:
1495 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001496 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001497 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001498 case AddressSpace::ModuleScopePrivate:
1499 return spv::StorageClassPrivate;
Kévin Petitbbbda972020-03-03 19:16:31 +00001500 case AddressSpace::PushConstant:
1501 return spv::StorageClassPushConstant;
David Neto22f144c2017-06-12 14:26:21 -04001502 }
1503}
1504
David Neto862b7d82018-06-14 18:48:37 -04001505spv::StorageClass
1506SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1507 switch (arg_kind) {
1508 case clspv::ArgKind::Buffer:
1509 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001510 case clspv::ArgKind::BufferUBO:
1511 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001512 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04001513 return spv::StorageClassStorageBuffer;
1514 case clspv::ArgKind::PodUBO:
1515 return spv::StorageClassUniform;
1516 case clspv::ArgKind::PodPushConstant:
1517 return spv::StorageClassPushConstant;
David Neto862b7d82018-06-14 18:48:37 -04001518 case clspv::ArgKind::Local:
1519 return spv::StorageClassWorkgroup;
alan-bakerf6bc8252020-09-23 14:58:55 -04001520 case clspv::ArgKind::SampledImage:
1521 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04001522 case clspv::ArgKind::Sampler:
1523 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001524 default:
1525 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001526 }
1527}
1528
David Neto22f144c2017-06-12 14:26:21 -04001529spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1530 return StringSwitch<spv::BuiltIn>(Name)
1531 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1532 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1533 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1534 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1535 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
alan-bakerbed3a882020-04-21 14:42:41 -04001536 .Case("__spirv_WorkDim", spv::BuiltInWorkDim)
alan-bakere1996972020-05-04 08:38:12 -04001537 .Case("__spirv_GlobalOffset", spv::BuiltInGlobalOffset)
David Neto22f144c2017-06-12 14:26:21 -04001538 .Default(spv::BuiltInMax);
1539}
1540
SJW01901d92020-05-21 08:58:31 -05001541SPIRVID SPIRVProducerPass::getOpExtInstImportID() {
1542 if (OpExtInstImportID == 0) {
1543 //
1544 // Generate OpExtInstImport.
1545 //
1546 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001547
SJW01901d92020-05-21 08:58:31 -05001548 OpExtInstImportID =
1549 addSPIRVInst<kImports>(spv::OpExtInstImport, "GLSL.std.450");
1550 }
1551 return OpExtInstImportID;
SJWf93f5f32020-05-05 07:27:56 -05001552}
1553
SJW806a5d82020-07-15 12:51:38 -05001554SPIRVID SPIRVProducerPass::addSPIRVGlobalVariable(const SPIRVID &TypeID,
1555 spv::StorageClass SC,
1556 const SPIRVID &InitID) {
1557 // Generate OpVariable.
1558 //
1559 // Ops[0] : Result Type ID
1560 // Ops[1] : Storage Class
1561 // Ops[2] : Initialization Value ID (optional)
1562
1563 SPIRVOperandVec Ops;
1564 Ops << TypeID << SC;
1565 if (InitID.isValid()) {
1566 Ops << InitID;
1567 }
1568
1569 SPIRVID VID = addSPIRVInst<kGlobalVariables>(spv::OpVariable, Ops);
1570
1571 if (SC == spv::StorageClassInput) {
1572 getEntryPointInterfacesList().push_back(VID);
1573 }
1574
1575 return VID;
1576}
1577
alan-bakerc3fd07f2020-10-22 09:48:49 -04001578Type *SPIRVProducerPass::CanonicalType(Type *type) {
1579 if (type->getNumContainedTypes() != 0) {
1580 switch (type->getTypeID()) {
1581 case Type::PointerTyID: {
1582 // For the purposes of our Vulkan SPIR-V type system, constant and global
1583 // are conflated.
1584 auto *ptr_ty = cast<PointerType>(type);
1585 unsigned AddrSpace = ptr_ty->getAddressSpace();
1586 if (AddressSpace::Constant == AddrSpace) {
1587 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1588 AddrSpace = AddressSpace::Global;
1589 // The canonical type of __constant is __global unless constants are
1590 // passed in uniform buffers.
1591 auto *GlobalTy =
1592 ptr_ty->getPointerElementType()->getPointerTo(AddrSpace);
1593 return GlobalTy;
1594 }
1595 }
1596 break;
1597 }
1598 case Type::StructTyID: {
1599 SmallVector<Type *, 8> subtypes;
1600 bool changed = false;
1601 for (auto *subtype : type->subtypes()) {
1602 auto canonical = CanonicalType(subtype);
1603 subtypes.push_back(canonical);
1604 if (canonical != subtype) {
1605 changed = true;
1606 }
1607 }
1608 if (changed) {
1609 return StructType::get(type->getContext(), subtypes,
1610 cast<StructType>(type)->isPacked());
1611 }
1612 break;
1613 }
1614 case Type::ArrayTyID: {
1615 auto *elem_ty = type->getArrayElementType();
1616 auto *equiv_elem_ty = CanonicalType(elem_ty);
1617 if (equiv_elem_ty != elem_ty) {
1618 return ArrayType::get(equiv_elem_ty,
1619 cast<ArrayType>(type)->getNumElements());
1620 }
1621 break;
1622 }
1623 case Type::FunctionTyID: {
1624 auto *func_ty = cast<FunctionType>(type);
1625 auto *return_ty = CanonicalType(func_ty->getReturnType());
1626 SmallVector<Type *, 8> params;
1627 for (unsigned i = 0; i < func_ty->getNumParams(); ++i) {
1628 params.push_back(CanonicalType(func_ty->getParamType(i)));
1629 }
1630 return FunctionType::get(return_ty, params, func_ty->isVarArg());
1631 }
1632 default:
1633 break;
1634 }
1635 }
1636
1637 return type;
1638}
1639
SJW01901d92020-05-21 08:58:31 -05001640SPIRVID SPIRVProducerPass::getSPIRVType(Type *Ty) {
SJWf93f5f32020-05-05 07:27:56 -05001641 auto TI = TypeMap.find(Ty);
1642 if (TI != TypeMap.end()) {
SJW01901d92020-05-21 08:58:31 -05001643 assert(TI->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05001644 return TI->second;
1645 }
1646
alan-bakerc3fd07f2020-10-22 09:48:49 -04001647 auto Canonical = CanonicalType(Ty);
1648 if (Canonical != Ty) {
1649 auto CanonicalTI = TypeMap.find(Canonical);
1650 if (CanonicalTI != TypeMap.end()) {
1651 assert(CanonicalTI->second.isValid());
1652 return CanonicalTI->second;
1653 }
1654 }
1655
1656 // Perform the mapping with the canonical type.
1657
SJWf93f5f32020-05-05 07:27:56 -05001658 const auto &DL = module->getDataLayout();
1659
SJW01901d92020-05-21 08:58:31 -05001660 SPIRVID RID;
SJWf93f5f32020-05-05 07:27:56 -05001661
alan-bakerc3fd07f2020-10-22 09:48:49 -04001662 switch (Canonical->getTypeID()) {
SJWf93f5f32020-05-05 07:27:56 -05001663 default: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001664 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001665 llvm_unreachable("Unsupported type???");
1666 break;
1667 }
1668 case Type::MetadataTyID:
1669 case Type::LabelTyID: {
1670 // Ignore these types.
1671 break;
1672 }
1673 case Type::PointerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001674 PointerType *PTy = cast<PointerType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001675 unsigned AddrSpace = PTy->getAddressSpace();
1676
1677 if (AddrSpace != AddressSpace::UniformConstant) {
1678 auto PointeeTy = PTy->getElementType();
1679 if (PointeeTy->isStructTy() &&
1680 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1681 // TODO(sjw): assert always an image?
1682 RID = getSPIRVType(PointeeTy);
1683 break;
1684 }
1685 }
1686
SJWf93f5f32020-05-05 07:27:56 -05001687 //
1688 // Generate OpTypePointer.
1689 //
1690
1691 // OpTypePointer
1692 // Ops[0] = Storage Class
1693 // Ops[1] = Element Type ID
1694 SPIRVOperandVec Ops;
1695
SJW01901d92020-05-21 08:58:31 -05001696 Ops << GetStorageClass(AddrSpace) << PTy->getElementType();
SJWf93f5f32020-05-05 07:27:56 -05001697
1698 RID = addSPIRVInst<kTypes>(spv::OpTypePointer, Ops);
1699 break;
1700 }
1701 case Type::StructTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001702 StructType *STy = cast<StructType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001703
1704 // Handle sampler type.
1705 if (STy->isOpaque()) {
1706 if (STy->getName().equals("opencl.sampler_t")) {
1707 //
1708 // Generate OpTypeSampler
1709 //
1710 // Empty Ops.
1711
1712 RID = addSPIRVInst<kTypes>(spv::OpTypeSampler);
1713 break;
1714 } else if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001715 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001716 STy->getName().startswith("opencl.image1d_wo_t") ||
1717 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001718 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001719 STy->getName().startswith("opencl.image1d_array_wo_t") ||
1720 STy->getName().startswith("opencl.image2d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001721 STy->getName().startswith("opencl.image2d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001722 STy->getName().startswith("opencl.image2d_wo_t") ||
1723 STy->getName().startswith("opencl.image2d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001724 STy->getName().startswith("opencl.image2d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001725 STy->getName().startswith("opencl.image2d_array_wo_t") ||
1726 STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001727 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001728 STy->getName().startswith("opencl.image3d_wo_t")) {
SJW01901d92020-05-21 08:58:31 -05001729 if (STy->getName().startswith("opencl.image1d_")) {
1730 if (STy->getName().contains(".sampled"))
1731 addCapability(spv::CapabilitySampled1D);
1732 else
1733 addCapability(spv::CapabilityImage1D);
1734 }
1735
SJWf93f5f32020-05-05 07:27:56 -05001736 //
1737 // Generate OpTypeImage
1738 //
1739 // Ops[0] = Sampled Type ID
1740 // Ops[1] = Dim ID
1741 // Ops[2] = Depth (Literal Number)
1742 // Ops[3] = Arrayed (Literal Number)
1743 // Ops[4] = MS (Literal Number)
1744 // Ops[5] = Sampled (Literal Number)
1745 // Ops[6] = Image Format ID
1746 //
1747 SPIRVOperandVec Ops;
1748
SJW01901d92020-05-21 08:58:31 -05001749 SPIRVID SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001750 if (STy->getName().contains(".float")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001751 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001752 } else if (STy->getName().contains(".uint")) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001753 SampledTyID = getSPIRVType(Type::getInt32Ty(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001754 } else if (STy->getName().contains(".int")) {
1755 // Generate a signed 32-bit integer if necessary.
1756 if (int32ID == 0) {
1757 SPIRVOperandVec intOps;
SJW01901d92020-05-21 08:58:31 -05001758 intOps << 32 << 1;
SJWf93f5f32020-05-05 07:27:56 -05001759 int32ID = addSPIRVInst<kTypes>(spv::OpTypeInt, intOps);
1760 }
1761 SampledTyID = int32ID;
1762
1763 // Generate a vec4 of the signed int if necessary.
1764 if (v4int32ID == 0) {
1765 SPIRVOperandVec vecOps;
SJW01901d92020-05-21 08:58:31 -05001766 vecOps << int32ID << 4;
SJWf93f5f32020-05-05 07:27:56 -05001767 v4int32ID = addSPIRVInst<kTypes>(spv::OpTypeVector, vecOps);
1768 }
1769 } else {
1770 // This was likely an UndefValue.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001771 SampledTyID = getSPIRVType(Type::getFloatTy(Canonical->getContext()));
SJWf93f5f32020-05-05 07:27:56 -05001772 }
SJW01901d92020-05-21 08:58:31 -05001773 Ops << SampledTyID;
SJWf93f5f32020-05-05 07:27:56 -05001774
1775 spv::Dim DimID = spv::Dim2D;
1776 if (STy->getName().startswith("opencl.image1d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001777 STy->getName().startswith("opencl.image1d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001778 STy->getName().startswith("opencl.image1d_wo_t") ||
1779 STy->getName().startswith("opencl.image1d_array_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001780 STy->getName().startswith("opencl.image1d_array_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001781 STy->getName().startswith("opencl.image1d_array_wo_t")) {
1782 DimID = spv::Dim1D;
1783 } else if (STy->getName().startswith("opencl.image3d_ro_t") ||
alan-bakerf6bc8252020-09-23 14:58:55 -04001784 STy->getName().startswith("opencl.image3d_rw_t") ||
SJWf93f5f32020-05-05 07:27:56 -05001785 STy->getName().startswith("opencl.image3d_wo_t")) {
1786 DimID = spv::Dim3D;
1787 }
SJW01901d92020-05-21 08:58:31 -05001788 Ops << DimID;
SJWf93f5f32020-05-05 07:27:56 -05001789
1790 // TODO: Set up Depth.
SJW01901d92020-05-21 08:58:31 -05001791 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001792
1793 uint32_t arrayed = STy->getName().contains("_array_") ? 1 : 0;
SJW01901d92020-05-21 08:58:31 -05001794 Ops << arrayed;
SJWf93f5f32020-05-05 07:27:56 -05001795
1796 // TODO: Set up MS.
SJW01901d92020-05-21 08:58:31 -05001797 Ops << 0;
SJWf93f5f32020-05-05 07:27:56 -05001798
1799 // Set up Sampled.
1800 //
1801 // From Spec
1802 //
1803 // 0 indicates this is only known at run time, not at compile time
1804 // 1 indicates will be used with sampler
1805 // 2 indicates will be used without a sampler (a storage image)
1806 uint32_t Sampled = 1;
1807 if (!STy->getName().contains(".sampled")) {
1808 Sampled = 2;
1809 }
SJW01901d92020-05-21 08:58:31 -05001810 Ops << Sampled;
SJWf93f5f32020-05-05 07:27:56 -05001811
1812 // TODO: Set up Image Format.
SJW01901d92020-05-21 08:58:31 -05001813 Ops << spv::ImageFormatUnknown;
SJWf93f5f32020-05-05 07:27:56 -05001814 RID = addSPIRVInst<kTypes>(spv::OpTypeImage, Ops);
1815
alan-bakerf6bc8252020-09-23 14:58:55 -04001816 // Only need a sampled version of the type if it is used with a sampler.
1817 if (Sampled == 1) {
1818 Ops.clear();
1819 Ops << RID;
alan-bakerc3fd07f2020-10-22 09:48:49 -04001820 getImageTypeMap()[Canonical] =
alan-bakerf6bc8252020-09-23 14:58:55 -04001821 addSPIRVInst<kTypes>(spv::OpTypeSampledImage, Ops);
1822 }
SJWf93f5f32020-05-05 07:27:56 -05001823 break;
1824 }
1825 }
1826
1827 //
1828 // Generate OpTypeStruct
1829 //
1830 // Ops[0] ... Ops[n] = Member IDs
1831 SPIRVOperandVec Ops;
1832
1833 for (auto *EleTy : STy->elements()) {
SJW01901d92020-05-21 08:58:31 -05001834 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001835 }
1836
1837 RID = addSPIRVInst<kTypes>(spv::OpTypeStruct, Ops);
1838
alan-bakerc3fd07f2020-10-22 09:48:49 -04001839 // Generate OpMemberDecorate unless we are generating it for the canonical
1840 // type.
1841 StructType *canonical = cast<StructType>(CanonicalType(STy));
1842 if (TypesNeedingLayout.idFor(STy) &&
1843 (canonical == STy || !TypesNeedingLayout.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001844 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1845 MemberIdx++) {
1846 // Ops[0] = Structure Type ID
1847 // Ops[1] = Member Index(Literal Number)
1848 // Ops[2] = Decoration (Offset)
1849 // Ops[3] = Byte Offset (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05001850 const auto ByteOffset =
1851 GetExplicitLayoutStructMemberOffset(STy, MemberIdx, DL);
1852
SJW01901d92020-05-21 08:58:31 -05001853 Ops.clear();
1854 Ops << RID << MemberIdx << spv::DecorationOffset << ByteOffset;
SJWf93f5f32020-05-05 07:27:56 -05001855
1856 addSPIRVInst<kAnnotations>(spv::OpMemberDecorate, Ops);
1857 }
1858 }
1859
alan-bakerc3fd07f2020-10-22 09:48:49 -04001860 // Generate OpDecorate unless we are generating it for the canonical type.
1861 if (StructTypesNeedingBlock.idFor(STy) &&
1862 (canonical == STy || !StructTypesNeedingBlock.idFor(canonical))) {
SJWf93f5f32020-05-05 07:27:56 -05001863 Ops.clear();
1864 // Use Block decorations with StorageBuffer storage class.
SJW01901d92020-05-21 08:58:31 -05001865 Ops << RID << spv::DecorationBlock;
SJWf93f5f32020-05-05 07:27:56 -05001866
1867 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1868 }
1869 break;
1870 }
1871 case Type::IntegerTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001872 uint32_t bit_width =
1873 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
SJWf93f5f32020-05-05 07:27:56 -05001874
alan-bakere2a62752020-07-09 22:53:23 -04001875 if (clspv::Option::Int8Support() && bit_width == 8) {
SJW01901d92020-05-21 08:58:31 -05001876 addCapability(spv::CapabilityInt8);
alan-bakere2a62752020-07-09 22:53:23 -04001877 } else if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001878 addCapability(spv::CapabilityInt16);
alan-bakere2a62752020-07-09 22:53:23 -04001879 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001880 addCapability(spv::CapabilityInt64);
1881 }
1882
alan-bakere2a62752020-07-09 22:53:23 -04001883 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05001884 RID = addSPIRVInst<kTypes>(spv::OpTypeBool);
1885 } else {
alan-bakere2a62752020-07-09 22:53:23 -04001886 if (!clspv::Option::Int8Support() && bit_width == 8) {
SJWf93f5f32020-05-05 07:27:56 -05001887 // i8 is added to TypeMap as i32.
alan-bakerc3fd07f2020-10-22 09:48:49 -04001888 RID = getSPIRVType(Type::getIntNTy(Canonical->getContext(), 32));
SJWf93f5f32020-05-05 07:27:56 -05001889 } else {
1890 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001891 Ops << bit_width << 0 /* not signed */;
SJWf93f5f32020-05-05 07:27:56 -05001892 RID = addSPIRVInst<kTypes>(spv::OpTypeInt, Ops);
1893 }
1894 }
1895 break;
1896 }
1897 case Type::HalfTyID:
1898 case Type::FloatTyID:
1899 case Type::DoubleTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001900 uint32_t bit_width =
1901 static_cast<uint32_t>(Canonical->getPrimitiveSizeInBits());
alan-bakere2a62752020-07-09 22:53:23 -04001902 if (bit_width == 16) {
SJW01901d92020-05-21 08:58:31 -05001903 addCapability(spv::CapabilityFloat16);
alan-bakere2a62752020-07-09 22:53:23 -04001904 } else if (bit_width == 64) {
SJW01901d92020-05-21 08:58:31 -05001905 addCapability(spv::CapabilityFloat64);
1906 }
1907
SJWf93f5f32020-05-05 07:27:56 -05001908 SPIRVOperandVec Ops;
alan-bakere2a62752020-07-09 22:53:23 -04001909 Ops << bit_width;
SJWf93f5f32020-05-05 07:27:56 -05001910
1911 RID = addSPIRVInst<kTypes>(spv::OpTypeFloat, Ops);
1912 break;
1913 }
1914 case Type::ArrayTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001915 ArrayType *ArrTy = cast<ArrayType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001916 const uint64_t Length = ArrTy->getArrayNumElements();
1917 if (Length == 0) {
1918 // By convention, map it to a RuntimeArray.
1919
1920 Type *EleTy = ArrTy->getArrayElementType();
1921
1922 //
1923 // Generate OpTypeRuntimeArray.
1924 //
1925 // OpTypeRuntimeArray
1926 // Ops[0] = Element Type ID
1927 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05001928 Ops << EleTy;
SJWf93f5f32020-05-05 07:27:56 -05001929
1930 RID = addSPIRVInst<kTypes>(spv::OpTypeRuntimeArray, Ops);
1931
1932 if (Hack_generate_runtime_array_stride_early) {
1933 // Generate OpDecorate.
1934
1935 // Ops[0] = Target ID
1936 // Ops[1] = Decoration (ArrayStride)
1937 // Ops[2] = Stride Number(Literal Number)
1938 Ops.clear();
1939
SJW01901d92020-05-21 08:58:31 -05001940 Ops << RID << spv::DecorationArrayStride
1941 << static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL));
SJWf93f5f32020-05-05 07:27:56 -05001942
1943 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
1944 }
1945
1946 } else {
1947
1948 //
1949 // Generate OpConstant and OpTypeArray.
1950 //
1951
1952 //
1953 // Generate OpConstant for array length.
1954 //
1955 // Add constant for length to constant list.
1956 Constant *CstLength =
1957 ConstantInt::get(Type::getInt32Ty(module->getContext()), Length);
SJWf93f5f32020-05-05 07:27:56 -05001958
1959 // Remember to generate ArrayStride later
alan-bakerc3fd07f2020-10-22 09:48:49 -04001960 getTypesNeedingArrayStride().insert(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001961
1962 //
1963 // Generate OpTypeArray.
1964 //
1965 // Ops[0] = Element Type ID
1966 // Ops[1] = Array Length Constant ID
1967 SPIRVOperandVec Ops;
1968
SJW01901d92020-05-21 08:58:31 -05001969 Ops << ArrTy->getElementType() << CstLength;
SJWf93f5f32020-05-05 07:27:56 -05001970
1971 RID = addSPIRVInst<kTypes>(spv::OpTypeArray, Ops);
1972 }
1973 break;
1974 }
1975 case Type::FixedVectorTyID: {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001976 auto VecTy = cast<VectorType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05001977 // <4 x i8> is changed to i32 if i8 is not generally supported.
1978 if (!clspv::Option::Int8Support() &&
1979 VecTy->getElementType() == Type::getInt8Ty(module->getContext())) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001980 if (VecTy->getElementCount().getKnownMinValue() == 4) {
SJWf93f5f32020-05-05 07:27:56 -05001981 RID = getSPIRVType(VecTy->getElementType());
1982 break;
1983 } else {
alan-bakerc3fd07f2020-10-22 09:48:49 -04001984 Canonical->print(errs());
SJWf93f5f32020-05-05 07:27:56 -05001985 llvm_unreachable("Support above i8 vector type");
1986 }
1987 }
1988
1989 // Ops[0] = Component Type ID
1990 // Ops[1] = Component Count (Literal Number)
1991 SPIRVOperandVec Ops;
alan-baker5a8c3be2020-09-09 13:44:26 -04001992 Ops << VecTy->getElementType()
1993 << VecTy->getElementCount().getKnownMinValue();
SJWf93f5f32020-05-05 07:27:56 -05001994
1995 RID = addSPIRVInst<kTypes>(spv::OpTypeVector, Ops);
1996 break;
1997 }
1998 case Type::VoidTyID: {
1999 RID = addSPIRVInst<kTypes>(spv::OpTypeVoid);
2000 break;
2001 }
2002 case Type::FunctionTyID: {
2003 // Generate SPIRV instruction for function type.
alan-bakerc3fd07f2020-10-22 09:48:49 -04002004 FunctionType *FTy = cast<FunctionType>(Canonical);
SJWf93f5f32020-05-05 07:27:56 -05002005
2006 // Ops[0] = Return Type ID
2007 // Ops[1] ... Ops[n] = Parameter Type IDs
2008 SPIRVOperandVec Ops;
2009
2010 // Find SPIRV instruction for return type
SJW01901d92020-05-21 08:58:31 -05002011 Ops << FTy->getReturnType();
SJWf93f5f32020-05-05 07:27:56 -05002012
2013 // Find SPIRV instructions for parameter types
2014 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2015 // Find SPIRV instruction for parameter type.
2016 auto ParamTy = FTy->getParamType(k);
2017 if (ParamTy->isPointerTy()) {
2018 auto PointeeTy = ParamTy->getPointerElementType();
2019 if (PointeeTy->isStructTy() &&
2020 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2021 ParamTy = PointeeTy;
2022 }
2023 }
2024
SJW01901d92020-05-21 08:58:31 -05002025 Ops << ParamTy;
SJWf93f5f32020-05-05 07:27:56 -05002026 }
2027
2028 RID = addSPIRVInst<kTypes>(spv::OpTypeFunction, Ops);
2029 break;
2030 }
2031 }
2032
SJW01901d92020-05-21 08:58:31 -05002033 if (RID.isValid()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04002034 TypeMap[Canonical] = RID;
2035 if (Ty != Canonical) {
2036 // Speed up future lookups of this type by also caching the non-canonical
2037 // type.
2038 TypeMap[Ty] = RID;
2039 }
SJWf93f5f32020-05-05 07:27:56 -05002040 }
2041 return RID;
David Neto22f144c2017-06-12 14:26:21 -04002042}
2043
SJW77b87ad2020-04-21 14:37:52 -05002044void SPIRVProducerPass::GenerateSPIRVTypes() {
David Neto22f144c2017-06-12 14:26:21 -04002045 for (Type *Ty : getTypeList()) {
SJWf93f5f32020-05-05 07:27:56 -05002046 getSPIRVType(Ty);
David Netoc6f3ab22018-04-06 18:02:31 -04002047 }
David Neto22f144c2017-06-12 14:26:21 -04002048}
2049
SJW806a5d82020-07-15 12:51:38 -05002050SPIRVID SPIRVProducerPass::getSPIRVInt32Constant(uint32_t CstVal) {
2051 Type *i32 = Type::getInt32Ty(module->getContext());
2052 Constant *Cst = ConstantInt::get(i32, CstVal);
2053 return getSPIRVValue(Cst);
2054}
2055
SJWf93f5f32020-05-05 07:27:56 -05002056SPIRVID SPIRVProducerPass::getSPIRVConstant(Constant *Cst) {
David Neto22f144c2017-06-12 14:26:21 -04002057 ValueMapType &VMap = getValueMap();
David Neto482550a2018-03-24 05:21:07 -07002058 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002059
SJW01901d92020-05-21 08:58:31 -05002060 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04002061
SJWf93f5f32020-05-05 07:27:56 -05002062 //
2063 // Generate OpConstant.
2064 //
2065 // Ops[0] = Result Type ID
2066 // Ops[1] .. Ops[n] = Values LiteralNumber
2067 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002068
SJW01901d92020-05-21 08:58:31 -05002069 Ops << Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04002070
SJWf93f5f32020-05-05 07:27:56 -05002071 std::vector<uint32_t> LiteralNum;
2072 spv::Op Opcode = spv::OpNop;
David Neto22f144c2017-06-12 14:26:21 -04002073
SJWf93f5f32020-05-05 07:27:56 -05002074 if (isa<UndefValue>(Cst)) {
David Neto22f144c2017-06-12 14:26:21 -04002075 // Ops[0] = Result Type ID
SJWf93f5f32020-05-05 07:27:56 -05002076 Opcode = spv::OpUndef;
2077 if (hack_undef && IsTypeNullable(Cst->getType())) {
2078 Opcode = spv::OpConstantNull;
2079 }
2080 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
alan-bakere2a62752020-07-09 22:53:23 -04002081 unsigned bit_width = CI->getBitWidth();
2082 if (bit_width == 1) {
SJWf93f5f32020-05-05 07:27:56 -05002083 // If the bitwidth of constant is 1, generate OpConstantTrue or
2084 // OpConstantFalse.
2085 if (CI->getZExtValue()) {
2086 // Ops[0] = Result Type ID
2087 Opcode = spv::OpConstantTrue;
David Neto22f144c2017-06-12 14:26:21 -04002088 } else {
SJWf93f5f32020-05-05 07:27:56 -05002089 // Ops[0] = Result Type ID
2090 Opcode = spv::OpConstantFalse;
David Neto22f144c2017-06-12 14:26:21 -04002091 }
SJWf93f5f32020-05-05 07:27:56 -05002092 } else {
2093 auto V = CI->getZExtValue();
2094 LiteralNum.push_back(V & 0xFFFFFFFF);
2095
alan-bakere2a62752020-07-09 22:53:23 -04002096 if (bit_width > 32) {
SJWf93f5f32020-05-05 07:27:56 -05002097 LiteralNum.push_back(V >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002098 }
2099
2100 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002101
SJW01901d92020-05-21 08:58:31 -05002102 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002103 }
2104 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2105 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2106 Type *CFPTy = CFP->getType();
2107 if (CFPTy->isFloatTy()) {
2108 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2109 } else if (CFPTy->isDoubleTy()) {
2110 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2111 LiteralNum.push_back(FPVal >> 32);
2112 } else if (CFPTy->isHalfTy()) {
2113 LiteralNum.push_back(FPVal & 0xFFFF);
2114 } else {
2115 CFPTy->print(errs());
2116 llvm_unreachable("Implement this ConstantFP Type");
2117 }
David Neto22f144c2017-06-12 14:26:21 -04002118
SJWf93f5f32020-05-05 07:27:56 -05002119 Opcode = spv::OpConstant;
David Neto49351ac2017-08-26 17:32:20 -04002120
SJW01901d92020-05-21 08:58:31 -05002121 Ops << LiteralNum;
SJWf93f5f32020-05-05 07:27:56 -05002122 } else if (isa<ConstantDataSequential>(Cst) &&
2123 cast<ConstantDataSequential>(Cst)->isString()) {
2124 Cst->print(errs());
2125 llvm_unreachable("Implement this Constant");
David Neto49351ac2017-08-26 17:32:20 -04002126
SJWf93f5f32020-05-05 07:27:56 -05002127 } else if (const ConstantDataSequential *CDS =
2128 dyn_cast<ConstantDataSequential>(Cst)) {
2129 // Let's convert <4 x i8> constant to int constant specially.
2130 // This case occurs when all the values are specified as constant
2131 // ints.
2132 Type *CstTy = Cst->getType();
2133 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002134 //
2135 // Generate OpConstant with OpTypeInt 32 0.
2136 //
2137 uint32_t IntValue = 0;
2138 for (unsigned k = 0; k < 4; k++) {
2139 const uint64_t Val = CDS->getElementAsInteger(k);
2140 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto49351ac2017-08-26 17:32:20 -04002141 }
2142
SJW806a5d82020-07-15 12:51:38 -05002143 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002144 } else {
2145
David Neto49351ac2017-08-26 17:32:20 -04002146 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002147 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
SJW01901d92020-05-21 08:58:31 -05002148 Ops << CDS->getElementAsConstant(k);
David Neto22f144c2017-06-12 14:26:21 -04002149 }
2150
2151 Opcode = spv::OpConstantComposite;
SJWf93f5f32020-05-05 07:27:56 -05002152 }
2153 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2154 // Let's convert <4 x i8> constant to int constant specially.
2155 // This case occurs when at least one of the values is an undef.
2156 Type *CstTy = Cst->getType();
2157 if (is4xi8vec(CstTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002158 //
2159 // Generate OpConstant with OpTypeInt 32 0.
2160 //
2161 uint32_t IntValue = 0;
2162 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2163 I != E; ++I) {
2164 uint64_t Val = 0;
2165 const Value *CV = *I;
2166 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2167 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002168 }
SJWf93f5f32020-05-05 07:27:56 -05002169 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002170 }
2171
SJW806a5d82020-07-15 12:51:38 -05002172 RID = getSPIRVInt32Constant(IntValue);
SJWf93f5f32020-05-05 07:27:56 -05002173 } else {
2174
David Neto22f144c2017-06-12 14:26:21 -04002175 // We use a constant composite in SPIR-V for our constant aggregate in
2176 // LLVM.
2177 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002178
2179 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
David Neto22f144c2017-06-12 14:26:21 -04002180 // And add an operand to the composite we are constructing
SJW01901d92020-05-21 08:58:31 -05002181 Ops << CA->getAggregateElement(k);
David Neto22f144c2017-06-12 14:26:21 -04002182 }
David Neto22f144c2017-06-12 14:26:21 -04002183 }
SJWf93f5f32020-05-05 07:27:56 -05002184 } else if (Cst->isNullValue()) {
2185 Opcode = spv::OpConstantNull;
2186 } else {
2187 Cst->print(errs());
2188 llvm_unreachable("Unsupported Constant???");
2189 }
David Neto22f144c2017-06-12 14:26:21 -04002190
SJWf93f5f32020-05-05 07:27:56 -05002191 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2192 // Null pointer requires variable pointers.
2193 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2194 }
alan-baker5b86ed72019-02-15 08:26:50 -05002195
SJWf93f5f32020-05-05 07:27:56 -05002196 if (RID == 0) {
2197 RID = addSPIRVInst<kConstants>(Opcode, Ops);
2198 }
2199
2200 VMap[Cst] = RID;
2201
2202 return RID;
2203}
2204
2205SPIRVID SPIRVProducerPass::getSPIRVValue(Value *V) {
2206 auto II = ValueMap.find(V);
2207 if (II != ValueMap.end()) {
SJW01901d92020-05-21 08:58:31 -05002208 assert(II->second.isValid());
SJWf93f5f32020-05-05 07:27:56 -05002209 return II->second;
2210 }
2211 if (Constant *Cst = dyn_cast<Constant>(V)) {
2212 return getSPIRVConstant(Cst);
2213 } else {
2214 llvm_unreachable("Variable not found");
2215 }
2216}
2217
SJW77b87ad2020-04-21 14:37:52 -05002218void SPIRVProducerPass::GenerateSamplers() {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002219 auto &sampler_map = getSamplerMap();
alan-baker09cb9802019-12-10 13:16:27 -05002220 SamplerLiteralToIDMap.clear();
David Neto862b7d82018-06-14 18:48:37 -04002221 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2222 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002223
David Neto862b7d82018-06-14 18:48:37 -04002224 // We might have samplers in the sampler map that are not used
2225 // in the translation unit. We need to allocate variables
2226 // for them and bindings too.
2227 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002228
SJW77b87ad2020-04-21 14:37:52 -05002229 auto *var_fn = module->getFunction(clspv::LiteralSamplerFunction());
alan-baker09cb9802019-12-10 13:16:27 -05002230 // Return if there are no literal samplers.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002231 if (!var_fn)
2232 return;
alan-baker09cb9802019-12-10 13:16:27 -05002233
David Neto862b7d82018-06-14 18:48:37 -04002234 for (auto user : var_fn->users()) {
2235 // Populate SamplerLiteralToDescriptorSetMap and
2236 // SamplerLiteralToBindingMap.
2237 //
2238 // Look for calls like
2239 // call %opencl.sampler_t addrspace(2)*
2240 // @clspv.sampler.var.literal(
2241 // i32 descriptor,
2242 // i32 binding,
alan-baker09cb9802019-12-10 13:16:27 -05002243 // i32 (index-into-sampler-map|sampler_mask))
alan-bakerb6b09dc2018-11-08 16:59:28 -05002244 if (auto *call = dyn_cast<CallInst>(user)) {
alan-baker09cb9802019-12-10 13:16:27 -05002245 const auto third_param = static_cast<unsigned>(
alan-bakerb6b09dc2018-11-08 16:59:28 -05002246 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
alan-baker09cb9802019-12-10 13:16:27 -05002247 auto sampler_value = third_param;
2248 if (clspv::Option::UseSamplerMap()) {
2249 if (third_param >= sampler_map.size()) {
2250 errs() << "Out of bounds index to sampler map: " << third_param;
2251 llvm_unreachable("bad sampler init: out of bounds");
2252 }
2253 sampler_value = sampler_map[third_param].first;
David Neto862b7d82018-06-14 18:48:37 -04002254 }
2255
David Neto862b7d82018-06-14 18:48:37 -04002256 const auto descriptor_set = static_cast<unsigned>(
2257 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2258 const auto binding = static_cast<unsigned>(
2259 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2260
2261 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2262 SamplerLiteralToBindingMap[sampler_value] = binding;
2263 used_bindings.insert(binding);
2264 }
2265 }
2266
alan-baker09cb9802019-12-10 13:16:27 -05002267 DenseSet<size_t> seen;
2268 for (auto user : var_fn->users()) {
2269 if (!isa<CallInst>(user))
2270 continue;
2271
2272 auto call = cast<CallInst>(user);
2273 const unsigned third_param = static_cast<unsigned>(
2274 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
2275
2276 // Already allocated a variable for this value.
2277 if (!seen.insert(third_param).second)
2278 continue;
2279
2280 auto sampler_value = third_param;
2281 if (clspv::Option::UseSamplerMap()) {
2282 sampler_value = sampler_map[third_param].first;
2283 }
2284
SJW806a5d82020-07-15 12:51:38 -05002285 auto sampler_var_id = addSPIRVGlobalVariable(
2286 getSPIRVType(SamplerTy), spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002287
alan-baker09cb9802019-12-10 13:16:27 -05002288 SamplerLiteralToIDMap[sampler_value] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002289
David Neto862b7d82018-06-14 18:48:37 -04002290 unsigned descriptor_set;
2291 unsigned binding;
alan-baker09cb9802019-12-10 13:16:27 -05002292 if (SamplerLiteralToBindingMap.find(sampler_value) ==
alan-bakerb6b09dc2018-11-08 16:59:28 -05002293 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002294 // This sampler is not actually used. Find the next one.
alan-baker7506abb2020-09-10 15:02:55 -04002295 for (binding = 0; used_bindings.count(binding); binding++) {
2296 }
David Neto862b7d82018-06-14 18:48:37 -04002297 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2298 used_bindings.insert(binding);
2299 } else {
alan-baker09cb9802019-12-10 13:16:27 -05002300 descriptor_set = SamplerLiteralToDescriptorSetMap[sampler_value];
2301 binding = SamplerLiteralToBindingMap[sampler_value];
alan-bakercff80152019-06-15 00:38:00 -04002302
alan-baker86ce19c2020-08-05 13:09:19 -04002303 auto import_id = getReflectionImport();
2304 SPIRVOperandVec Ops;
2305 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
2306 << reflection::ExtInstLiteralSampler
2307 << getSPIRVInt32Constant(descriptor_set)
2308 << getSPIRVInt32Constant(binding)
2309 << getSPIRVInt32Constant(sampler_value);
2310 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002311 }
2312
SJW69939d52020-04-16 07:29:07 -05002313 // Ops[0] = Target ID
2314 // Ops[1] = Decoration (DescriptorSet)
2315 // Ops[2] = LiteralNumber according to Decoration
SJW806a5d82020-07-15 12:51:38 -05002316 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002317 Ops << sampler_var_id << spv::DecorationDescriptorSet << descriptor_set;
David Neto22f144c2017-06-12 14:26:21 -04002318
SJWf93f5f32020-05-05 07:27:56 -05002319 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002320
2321 // Ops[0] = Target ID
2322 // Ops[1] = Decoration (Binding)
2323 // Ops[2] = LiteralNumber according to Decoration
2324 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002325 Ops << sampler_var_id << spv::DecorationBinding << binding;
David Neto22f144c2017-06-12 14:26:21 -04002326
SJWf93f5f32020-05-05 07:27:56 -05002327 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002328 }
David Neto862b7d82018-06-14 18:48:37 -04002329}
David Neto22f144c2017-06-12 14:26:21 -04002330
SJW77b87ad2020-04-21 14:37:52 -05002331void SPIRVProducerPass::GenerateResourceVars() {
David Neto862b7d82018-06-14 18:48:37 -04002332 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002333
David Neto862b7d82018-06-14 18:48:37 -04002334 // Generate variables. Make one for each of resource var info object.
2335 for (auto *info : ModuleOrderedResourceVars) {
2336 Type *type = info->var_fn->getReturnType();
2337 // Remap the address space for opaque types.
2338 switch (info->arg_kind) {
2339 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002340 case clspv::ArgKind::SampledImage:
2341 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002342 type = PointerType::get(type->getPointerElementType(),
2343 clspv::AddressSpace::UniformConstant);
2344 break;
2345 default:
2346 break;
2347 }
David Neto22f144c2017-06-12 14:26:21 -04002348
David Neto862b7d82018-06-14 18:48:37 -04002349 const auto sc = GetStorageClassForArgKind(info->arg_kind);
David Neto22f144c2017-06-12 14:26:21 -04002350
SJW806a5d82020-07-15 12:51:38 -05002351 info->var_id = addSPIRVGlobalVariable(getSPIRVType(type), sc);
David Neto862b7d82018-06-14 18:48:37 -04002352
2353 // Map calls to the variable-builtin-function.
2354 for (auto &U : info->var_fn->uses()) {
2355 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2356 const auto set = unsigned(
2357 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2358 const auto binding = unsigned(
2359 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2360 if (set == info->descriptor_set && binding == info->binding) {
2361 switch (info->arg_kind) {
2362 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002363 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002364 case clspv::ArgKind::Pod:
alan-baker9b0ec3c2020-04-06 14:45:34 -04002365 case clspv::ArgKind::PodUBO:
2366 case clspv::ArgKind::PodPushConstant:
David Neto862b7d82018-06-14 18:48:37 -04002367 // The call maps to the variable directly.
2368 VMap[call] = info->var_id;
2369 break;
2370 case clspv::ArgKind::Sampler:
alan-bakerf6bc8252020-09-23 14:58:55 -04002371 case clspv::ArgKind::SampledImage:
2372 case clspv::ArgKind::StorageImage:
David Neto862b7d82018-06-14 18:48:37 -04002373 // The call maps to a load we generate later.
2374 ResourceVarDeferredLoadCalls[call] = info->var_id;
2375 break;
2376 default:
2377 llvm_unreachable("Unhandled arg kind");
2378 }
2379 }
David Neto22f144c2017-06-12 14:26:21 -04002380 }
David Neto862b7d82018-06-14 18:48:37 -04002381 }
2382 }
David Neto22f144c2017-06-12 14:26:21 -04002383
David Neto862b7d82018-06-14 18:48:37 -04002384 // Generate associated decorations.
SJWf93f5f32020-05-05 07:27:56 -05002385 SPIRVOperandVec Ops;
David Neto862b7d82018-06-14 18:48:37 -04002386 for (auto *info : ModuleOrderedResourceVars) {
alan-baker9b0ec3c2020-04-06 14:45:34 -04002387 // Push constants don't need descriptor set or binding decorations.
2388 if (info->arg_kind == clspv::ArgKind::PodPushConstant)
2389 continue;
2390
David Neto862b7d82018-06-14 18:48:37 -04002391 // Decorate with DescriptorSet and Binding.
2392 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002393 Ops << info->var_id << spv::DecorationDescriptorSet << info->descriptor_set;
SJWf93f5f32020-05-05 07:27:56 -05002394 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002395
2396 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002397 Ops << info->var_id << spv::DecorationBinding << info->binding;
SJWf93f5f32020-05-05 07:27:56 -05002398 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto862b7d82018-06-14 18:48:37 -04002399
alan-bakere9308012019-03-15 10:25:13 -04002400 if (info->coherent) {
2401 // Decorate with Coherent if required for the variable.
2402 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002403 Ops << info->var_id << spv::DecorationCoherent;
SJWf93f5f32020-05-05 07:27:56 -05002404 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere9308012019-03-15 10:25:13 -04002405 }
2406
David Neto862b7d82018-06-14 18:48:37 -04002407 // Generate NonWritable and NonReadable
2408 switch (info->arg_kind) {
2409 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002410 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002411 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2412 clspv::AddressSpace::Constant) {
2413 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002414 Ops << info->var_id << spv::DecorationNonWritable;
SJWf93f5f32020-05-05 07:27:56 -05002415 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002416 }
David Neto862b7d82018-06-14 18:48:37 -04002417 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002418 case clspv::ArgKind::StorageImage: {
2419 auto *type = info->var_fn->getReturnType();
2420 auto *struct_ty = cast<StructType>(type->getPointerElementType());
2421 // TODO(alan-baker): This is conservative. If compiling for OpenCL 2.0 or
2422 // above, the compiler treats all write_only images as read_write images.
2423 if (struct_ty->getName().contains("_wo_t")) {
2424 Ops.clear();
2425 Ops << info->var_id << spv::DecorationNonReadable;
2426 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
2427 }
David Neto862b7d82018-06-14 18:48:37 -04002428 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04002429 }
David Neto862b7d82018-06-14 18:48:37 -04002430 default:
2431 break;
David Neto22f144c2017-06-12 14:26:21 -04002432 }
2433 }
2434}
2435
2436void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto22f144c2017-06-12 14:26:21 -04002437 ValueMapType &VMap = getValueMap();
SJW01901d92020-05-21 08:58:31 -05002438 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002439 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002440
2441 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2442 Type *Ty = GV.getType();
2443 PointerType *PTy = cast<PointerType>(Ty);
2444
SJW01901d92020-05-21 08:58:31 -05002445 SPIRVID InitializerID;
David Neto22f144c2017-06-12 14:26:21 -04002446
2447 // Workgroup size is handled differently (it goes into a constant)
2448 if (spv::BuiltInWorkgroupSize == BuiltinType) {
David Neto22f144c2017-06-12 14:26:21 -04002449 uint32_t PrevXDimCst = 0xFFFFFFFF;
2450 uint32_t PrevYDimCst = 0xFFFFFFFF;
2451 uint32_t PrevZDimCst = 0xFFFFFFFF;
alan-baker3b609772020-09-03 19:10:17 -04002452 bool HasMD = true;
David Neto22f144c2017-06-12 14:26:21 -04002453 for (Function &Func : *GV.getParent()) {
2454 if (Func.isDeclaration()) {
2455 continue;
2456 }
2457
2458 // We only need to check kernels.
2459 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2460 continue;
2461 }
2462
2463 if (const MDNode *MD =
2464 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2465 uint32_t CurXDimCst = static_cast<uint32_t>(
2466 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2467 uint32_t CurYDimCst = static_cast<uint32_t>(
2468 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2469 uint32_t CurZDimCst = static_cast<uint32_t>(
2470 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2471
2472 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2473 PrevZDimCst == 0xFFFFFFFF) {
2474 PrevXDimCst = CurXDimCst;
2475 PrevYDimCst = CurYDimCst;
2476 PrevZDimCst = CurZDimCst;
2477 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2478 CurZDimCst != PrevZDimCst) {
alan-baker3b609772020-09-03 19:10:17 -04002479 HasMD = false;
2480 continue;
David Neto22f144c2017-06-12 14:26:21 -04002481 } else {
2482 continue;
2483 }
2484
2485 //
2486 // Generate OpConstantComposite.
2487 //
2488 // Ops[0] : Result Type ID
2489 // Ops[1] : Constant size for x dimension.
2490 // Ops[2] : Constant size for y dimension.
2491 // Ops[3] : Constant size for z dimension.
SJWf93f5f32020-05-05 07:27:56 -05002492 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002493
SJW01901d92020-05-21 08:58:31 -05002494 SPIRVID XDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002495 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(0)));
SJW01901d92020-05-21 08:58:31 -05002496 SPIRVID YDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002497 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(1)));
SJW01901d92020-05-21 08:58:31 -05002498 SPIRVID ZDimCstID =
SJWf93f5f32020-05-05 07:27:56 -05002499 getSPIRVValue(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -04002500
SJW01901d92020-05-21 08:58:31 -05002501 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID
2502 << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002503
SJWf93f5f32020-05-05 07:27:56 -05002504 InitializerID =
2505 addSPIRVInst<kGlobalVariables>(spv::OpConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002506 } else {
alan-baker3b609772020-09-03 19:10:17 -04002507 HasMD = false;
David Neto22f144c2017-06-12 14:26:21 -04002508 }
2509 }
2510
2511 // If all kernels do not have metadata for reqd_work_group_size, generate
2512 // OpSpecConstants for x/y/z dimension.
Kévin Petit21c23c62020-04-29 01:38:28 +01002513 if (!HasMD || clspv::Option::NonUniformNDRangeSupported()) {
David Neto22f144c2017-06-12 14:26:21 -04002514 //
2515 // Generate OpSpecConstants for x/y/z dimension.
2516 //
2517 // Ops[0] : Result Type ID
2518 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
David Neto22f144c2017-06-12 14:26:21 -04002519
alan-bakera1be3322020-04-20 12:48:18 -04002520 // Allocate spec constants for workgroup size.
SJW77b87ad2020-04-21 14:37:52 -05002521 clspv::AddWorkgroupSpecConstants(module);
alan-bakera1be3322020-04-20 12:48:18 -04002522
SJWf93f5f32020-05-05 07:27:56 -05002523 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002524 SPIRVID result_type_id = getSPIRVType(
SJWf93f5f32020-05-05 07:27:56 -05002525 dyn_cast<VectorType>(Ty->getPointerElementType())->getElementType());
David Neto22f144c2017-06-12 14:26:21 -04002526
David Neto257c3892018-04-11 13:19:45 -04002527 // X Dimension
SJW01901d92020-05-21 08:58:31 -05002528 Ops << result_type_id << 1;
2529 SPIRVID XDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002530
2531 // Y Dimension
2532 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002533 Ops << result_type_id << 1;
2534 SPIRVID YDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002535
2536 // Z Dimension
2537 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002538 Ops << result_type_id << 1;
2539 SPIRVID ZDimCstID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002540
David Neto257c3892018-04-11 13:19:45 -04002541 BuiltinDimVec.push_back(XDimCstID);
2542 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002543 BuiltinDimVec.push_back(ZDimCstID);
2544
David Neto22f144c2017-06-12 14:26:21 -04002545 //
2546 // Generate OpSpecConstantComposite.
2547 //
2548 // Ops[0] : Result Type ID
2549 // Ops[1] : Constant size for x dimension.
2550 // Ops[2] : Constant size for y dimension.
2551 // Ops[3] : Constant size for z dimension.
David Neto22f144c2017-06-12 14:26:21 -04002552 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002553 Ops << Ty->getPointerElementType() << XDimCstID << YDimCstID << ZDimCstID;
David Neto22f144c2017-06-12 14:26:21 -04002554
SJWf93f5f32020-05-05 07:27:56 -05002555 InitializerID =
2556 addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002557 }
alan-bakerbed3a882020-04-21 14:42:41 -04002558 } else if (BuiltinType == spv::BuiltInWorkDim) {
2559 // 1. Generate a specialization constant with a default of 3.
2560 // 2. Allocate and annotate a SpecId for the constant.
2561 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002562 SPIRVOperandVec Ops;
alan-bakerbed3a882020-04-21 14:42:41 -04002563
2564 //
2565 // Generate OpSpecConstant.
2566 //
2567 // Ops[0] : Result Type ID
2568 // Ops[1] : Default literal value
alan-bakerbed3a882020-04-21 14:42:41 -04002569
SJW01901d92020-05-21 08:58:31 -05002570 Ops << IntegerType::get(GV.getContext(), 32) << 3;
alan-bakerbed3a882020-04-21 14:42:41 -04002571
SJWf93f5f32020-05-05 07:27:56 -05002572 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakerbed3a882020-04-21 14:42:41 -04002573
2574 //
2575 // Generate SpecId decoration.
2576 //
2577 // Ops[0] : target
2578 // Ops[1] : decoration
2579 // Ops[2] : SpecId
Alan Baker75ccc252020-04-21 17:11:52 -04002580 auto spec_id = AllocateSpecConstant(module, SpecConstant::kWorkDim);
alan-bakerbed3a882020-04-21 14:42:41 -04002581 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002582 Ops << InitializerID << spv::DecorationSpecId << spec_id;
alan-bakerbed3a882020-04-21 14:42:41 -04002583
SJWf93f5f32020-05-05 07:27:56 -05002584 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002585 } else if (BuiltinType == spv::BuiltInGlobalOffset) {
2586 // 1. Generate a spec constant with a default of {0, 0, 0}.
2587 // 2. Allocate and annotate SpecIds for the constants.
2588 // 3. Use the spec constant as the initializer for the variable.
SJWf93f5f32020-05-05 07:27:56 -05002589 SPIRVOperandVec Ops;
alan-bakere1996972020-05-04 08:38:12 -04002590
2591 //
2592 // Generate OpSpecConstant for each dimension.
2593 //
2594 // Ops[0] : Result Type ID
2595 // Ops[1] : Default literal value
2596 //
SJW01901d92020-05-21 08:58:31 -05002597 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2598 SPIRVID x_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002599
alan-bakere1996972020-05-04 08:38:12 -04002600 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002601 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2602 SPIRVID y_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002603
alan-bakere1996972020-05-04 08:38:12 -04002604 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002605 Ops << IntegerType::get(GV.getContext(), 32) << 0;
2606 SPIRVID z_id = addSPIRVInst<kConstants>(spv::OpSpecConstant, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002607
2608 //
2609 // Generate SpecId decoration for each dimension.
2610 //
2611 // Ops[0] : target
2612 // Ops[1] : decoration
2613 // Ops[2] : SpecId
2614 //
2615 auto spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetX);
2616 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002617 Ops << x_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002618 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002619
2620 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetY);
2621 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002622 Ops << y_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002623 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002624
2625 spec_id = AllocateSpecConstant(module, SpecConstant::kGlobalOffsetZ);
2626 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002627 Ops << z_id << spv::DecorationSpecId << spec_id;
SJWf93f5f32020-05-05 07:27:56 -05002628 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
alan-bakere1996972020-05-04 08:38:12 -04002629
2630 //
2631 // Generate OpSpecConstantComposite.
2632 //
2633 // Ops[0] : type id
2634 // Ops[1..n-1] : elements
2635 //
alan-bakere1996972020-05-04 08:38:12 -04002636 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002637 Ops << GV.getType()->getPointerElementType() << x_id << y_id << z_id;
SJWf93f5f32020-05-05 07:27:56 -05002638 InitializerID = addSPIRVInst<kConstants>(spv::OpSpecConstantComposite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002639 }
2640
David Neto85082642018-03-24 06:55:20 -07002641 const auto AS = PTy->getAddressSpace();
SJW806a5d82020-07-15 12:51:38 -05002642 const auto spvSC = GetStorageClass(AS);
David Neto22f144c2017-06-12 14:26:21 -04002643
David Neto85082642018-03-24 06:55:20 -07002644 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002645 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002646 clspv::Option::ModuleConstantsInStorageBuffer();
2647
Kévin Petit23d5f182019-08-13 16:21:29 +01002648 if (GV.hasInitializer()) {
2649 auto GVInit = GV.getInitializer();
2650 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
SJWf93f5f32020-05-05 07:27:56 -05002651 InitializerID = getSPIRVValue(GVInit);
David Neto85082642018-03-24 06:55:20 -07002652 }
2653 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002654
SJW806a5d82020-07-15 12:51:38 -05002655 SPIRVID var_id =
2656 addSPIRVGlobalVariable(getSPIRVType(Ty), spvSC, InitializerID);
David Neto85082642018-03-24 06:55:20 -07002657
SJWf93f5f32020-05-05 07:27:56 -05002658 VMap[&GV] = var_id;
David Neto22f144c2017-06-12 14:26:21 -04002659
alan-bakere1996972020-05-04 08:38:12 -04002660 auto IsOpenCLBuiltin = [](spv::BuiltIn builtin) {
2661 return builtin == spv::BuiltInWorkDim ||
2662 builtin == spv::BuiltInGlobalOffset;
2663 };
2664
alan-bakere1996972020-05-04 08:38:12 -04002665 // If we have a builtin (not an OpenCL builtin).
2666 if (spv::BuiltInMax != BuiltinType && !IsOpenCLBuiltin(BuiltinType)) {
David Neto22f144c2017-06-12 14:26:21 -04002667 //
2668 // Generate OpDecorate.
2669 //
2670 // DOps[0] = Target ID
2671 // DOps[1] = Decoration (Builtin)
2672 // DOps[2] = BuiltIn ID
SJW01901d92020-05-21 08:58:31 -05002673 SPIRVID ResultID;
David Neto22f144c2017-06-12 14:26:21 -04002674
2675 // WorkgroupSize is different, we decorate the constant composite that has
2676 // its value, rather than the variable that we use to access the value.
2677 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2678 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002679 // Save both the value and variable IDs for later.
2680 WorkgroupSizeValueID = InitializerID;
SJWf93f5f32020-05-05 07:27:56 -05002681 WorkgroupSizeVarID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002682 } else {
SJWf93f5f32020-05-05 07:27:56 -05002683 ResultID = getSPIRVValue(&GV);
David Neto22f144c2017-06-12 14:26:21 -04002684 }
2685
SJW806a5d82020-07-15 12:51:38 -05002686 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05002687 Ops << ResultID << spv::DecorationBuiltIn << BuiltinType;
David Neto22f144c2017-06-12 14:26:21 -04002688
SJW01901d92020-05-21 08:58:31 -05002689 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto85082642018-03-24 06:55:20 -07002690 } else if (module_scope_constant_external_init) {
2691 // This module scope constant is initialized from a storage buffer with data
2692 // provided by the host at binding 0 of the next descriptor set.
SJW77b87ad2020-04-21 14:37:52 -05002693 const uint32_t descriptor_set = TakeDescriptorIndex(module);
David Neto85082642018-03-24 06:55:20 -07002694
alan-baker86ce19c2020-08-05 13:09:19 -04002695 // Emit the intializer as a reflection instruction.
David Neto85082642018-03-24 06:55:20 -07002696 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2697 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002698 std::string hexbytes;
2699 llvm::raw_string_ostream str(hexbytes);
2700 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
alan-baker86ce19c2020-08-05 13:09:19 -04002701
2702 // Reflection instruction for constant data.
2703 SPIRVOperandVec Ops;
2704 auto data_id = addSPIRVInst<kDebug>(spv::OpString, str.str().c_str());
2705 Ops << getSPIRVType(Type::getVoidTy(module->getContext()))
2706 << getReflectionImport() << reflection::ExtInstConstantDataStorageBuffer
2707 << getSPIRVInt32Constant(descriptor_set) << getSPIRVInt32Constant(0)
2708 << data_id;
2709 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
David Neto85082642018-03-24 06:55:20 -07002710
David Neto85082642018-03-24 06:55:20 -07002711 // OpDecorate %var DescriptorSet <descriptor_set>
alan-baker86ce19c2020-08-05 13:09:19 -04002712 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002713 Ops << var_id << spv::DecorationDescriptorSet << descriptor_set;
2714 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJW69939d52020-04-16 07:29:07 -05002715
2716 // OpDecorate %var Binding <binding>
SJW01901d92020-05-21 08:58:31 -05002717 Ops.clear();
2718 Ops << var_id << spv::DecorationBinding << 0;
2719 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002720 }
2721}
2722
David Neto22f144c2017-06-12 14:26:21 -04002723void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04002724 ValueMapType &VMap = getValueMap();
2725 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04002726 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2727 auto &GlobalConstArgSet = getGlobalConstArgSet();
2728
2729 FunctionType *FTy = F.getFunctionType();
2730
2731 //
David Neto22f144c2017-06-12 14:26:21 -04002732 // Generate OPFunction.
2733 //
2734
2735 // FOps[0] : Result Type ID
2736 // FOps[1] : Function Control
2737 // FOps[2] : Function Type ID
SJWf93f5f32020-05-05 07:27:56 -05002738 SPIRVOperandVec FOps;
David Neto22f144c2017-06-12 14:26:21 -04002739
2740 // Find SPIRV instruction for return type.
SJW01901d92020-05-21 08:58:31 -05002741 FOps << FTy->getReturnType();
David Neto22f144c2017-06-12 14:26:21 -04002742
2743 // Check function attributes for SPIRV Function Control.
2744 uint32_t FuncControl = spv::FunctionControlMaskNone;
2745 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2746 FuncControl |= spv::FunctionControlInlineMask;
2747 }
2748 if (F.hasFnAttribute(Attribute::NoInline)) {
2749 FuncControl |= spv::FunctionControlDontInlineMask;
2750 }
2751 // TODO: Check llvm attribute for Function Control Pure.
2752 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2753 FuncControl |= spv::FunctionControlPureMask;
2754 }
2755 // TODO: Check llvm attribute for Function Control Const.
2756 if (F.hasFnAttribute(Attribute::ReadNone)) {
2757 FuncControl |= spv::FunctionControlConstMask;
2758 }
2759
SJW01901d92020-05-21 08:58:31 -05002760 FOps << FuncControl;
David Neto22f144c2017-06-12 14:26:21 -04002761
SJW01901d92020-05-21 08:58:31 -05002762 SPIRVID FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002763 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2764 SmallVector<Type *, 4> NewFuncParamTys;
2765 FunctionType *NewFTy =
2766 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
SJWf93f5f32020-05-05 07:27:56 -05002767 FTyID = getSPIRVType(NewFTy);
David Neto22f144c2017-06-12 14:26:21 -04002768 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002769 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002770 if (GlobalConstFuncTyMap.count(FTy)) {
SJWf93f5f32020-05-05 07:27:56 -05002771 FTyID = getSPIRVType(GlobalConstFuncTyMap[FTy].first);
David Neto22f144c2017-06-12 14:26:21 -04002772 } else {
SJWf93f5f32020-05-05 07:27:56 -05002773 FTyID = getSPIRVType(FTy);
David Neto22f144c2017-06-12 14:26:21 -04002774 }
2775 }
2776
SJW01901d92020-05-21 08:58:31 -05002777 FOps << FTyID;
David Neto22f144c2017-06-12 14:26:21 -04002778
SJWf93f5f32020-05-05 07:27:56 -05002779 // Generate SPIRV instruction for function.
2780 SPIRVID FID = addSPIRVInst(spv::OpFunction, FOps);
2781 VMap[&F] = FID;
David Neto22f144c2017-06-12 14:26:21 -04002782
SJWf93f5f32020-05-05 07:27:56 -05002783 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2784 EntryPoints.push_back(std::make_pair(&F, FID));
2785 }
David Neto22f144c2017-06-12 14:26:21 -04002786
David Neto482550a2018-03-24 05:21:07 -07002787 if (clspv::Option::ShowIDs()) {
SJW01901d92020-05-21 08:58:31 -05002788 errs() << "Function " << F.getName() << " is " << FID.get() << "\n";
David Netob05675d2018-02-16 12:37:49 -05002789 }
David Neto22f144c2017-06-12 14:26:21 -04002790
2791 //
2792 // Generate OpFunctionParameter for Normal function.
2793 //
David Neto22f144c2017-06-12 14:26:21 -04002794 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04002795
David Neto22f144c2017-06-12 14:26:21 -04002796 // Iterate Argument for name instead of param type from function type.
2797 unsigned ArgIdx = 0;
2798 for (Argument &Arg : F.args()) {
David Neto22f144c2017-06-12 14:26:21 -04002799 // ParamOps[0] : Result Type ID
SJW01901d92020-05-21 08:58:31 -05002800 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002801
2802 // Find SPIRV instruction for parameter type.
SJW01901d92020-05-21 08:58:31 -05002803 SPIRVID ParamTyID = getSPIRVType(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002804 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2805 if (GlobalConstFuncTyMap.count(FTy)) {
2806 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2807 Type *EleTy = PTy->getPointerElementType();
2808 Type *ArgTy =
2809 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
SJWf93f5f32020-05-05 07:27:56 -05002810 ParamTyID = getSPIRVType(ArgTy);
David Neto22f144c2017-06-12 14:26:21 -04002811 GlobalConstArgSet.insert(&Arg);
2812 }
2813 }
2814 }
SJW01901d92020-05-21 08:58:31 -05002815 Ops << ParamTyID;
David Neto22f144c2017-06-12 14:26:21 -04002816
2817 // Generate SPIRV instruction for parameter.
SJW01901d92020-05-21 08:58:31 -05002818 SPIRVID param_id = addSPIRVInst(spv::OpFunctionParameter, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002819 VMap[&Arg] = param_id;
2820
2821 if (CalledWithCoherentResource(Arg)) {
2822 // If the arg is passed a coherent resource ever, then decorate this
2823 // parameter with Coherent too.
SJW01901d92020-05-21 08:58:31 -05002824 Ops.clear();
2825 Ops << param_id << spv::DecorationCoherent;
2826 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
SJWf93f5f32020-05-05 07:27:56 -05002827 }
David Neto22f144c2017-06-12 14:26:21 -04002828
2829 ArgIdx++;
2830 }
2831 }
2832}
2833
SJW77b87ad2020-04-21 14:37:52 -05002834void SPIRVProducerPass::GenerateModuleInfo() {
David Neto22f144c2017-06-12 14:26:21 -04002835 EntryPointVecType &EntryPoints = getEntryPointVec();
SJW806a5d82020-07-15 12:51:38 -05002836 auto &EntryPointInterfaces = getEntryPointInterfacesList();
SJW01901d92020-05-21 08:58:31 -05002837 std::vector<SPIRVID> &BuiltinDimVec = getBuiltinDimVec();
David Neto22f144c2017-06-12 14:26:21 -04002838
SJWf93f5f32020-05-05 07:27:56 -05002839 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04002840
SJW01901d92020-05-21 08:58:31 -05002841 for (auto Capability : CapabilitySet) {
David Neto22f144c2017-06-12 14:26:21 -04002842 //
SJW01901d92020-05-21 08:58:31 -05002843 // Generate OpCapability
David Neto22f144c2017-06-12 14:26:21 -04002844 //
2845 // Ops[0] = Capability
SJW01901d92020-05-21 08:58:31 -05002846 addSPIRVInst<kCapabilities>(spv::OpCapability, Capability);
alan-baker5b86ed72019-02-15 08:26:50 -05002847 }
2848
2849 // Always add the storage buffer extension
2850 {
David Neto22f144c2017-06-12 14:26:21 -04002851 //
2852 // Generate OpExtension.
2853 //
2854 // Ops[0] = Name (Literal String)
2855 //
SJWf93f5f32020-05-05 07:27:56 -05002856 addSPIRVInst<kExtensions>(spv::OpExtension,
2857 "SPV_KHR_storage_buffer_storage_class");
alan-baker5b86ed72019-02-15 08:26:50 -05002858 }
David Neto22f144c2017-06-12 14:26:21 -04002859
alan-baker5b86ed72019-02-15 08:26:50 -05002860 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
2861 //
2862 // Generate OpExtension.
2863 //
2864 // Ops[0] = Name (Literal String)
2865 //
SJWf93f5f32020-05-05 07:27:56 -05002866 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_variable_pointers");
David Neto22f144c2017-06-12 14:26:21 -04002867 }
2868
2869 //
2870 // Generate OpMemoryModel
2871 //
2872 // Memory model for Vulkan will always be GLSL450.
2873
2874 // Ops[0] = Addressing Model
2875 // Ops[1] = Memory Model
2876 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002877 Ops << spv::AddressingModelLogical << spv::MemoryModelGLSL450;
David Neto22f144c2017-06-12 14:26:21 -04002878
SJWf93f5f32020-05-05 07:27:56 -05002879 addSPIRVInst<kMemoryModel>(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002880
2881 //
2882 // Generate OpEntryPoint
2883 //
2884 for (auto EntryPoint : EntryPoints) {
2885 // Ops[0] = Execution Model
2886 // Ops[1] = EntryPoint ID
2887 // Ops[2] = Name (Literal String)
2888 // ...
2889 //
2890 // TODO: Do we need to consider Interface ID for forward references???
2891 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05002892 const StringRef &name = EntryPoint.first->getName();
SJW01901d92020-05-21 08:58:31 -05002893 Ops << spv::ExecutionModelGLCompute << EntryPoint.second << name;
David Neto22f144c2017-06-12 14:26:21 -04002894
SJW806a5d82020-07-15 12:51:38 -05002895 for (auto &Interface : EntryPointInterfaces) {
SJW01901d92020-05-21 08:58:31 -05002896 Ops << Interface;
David Neto22f144c2017-06-12 14:26:21 -04002897 }
2898
SJWf93f5f32020-05-05 07:27:56 -05002899 addSPIRVInst<kEntryPoints>(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002900 }
2901
alan-baker3b609772020-09-03 19:10:17 -04002902 if (BuiltinDimVec.empty()) {
2903 for (auto EntryPoint : EntryPoints) {
2904 const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2905 ->getMetadata("reqd_work_group_size");
2906 if ((MD != nullptr) && !clspv::Option::NonUniformNDRangeSupported()) {
2907 //
2908 // Generate OpExecutionMode
2909 //
David Neto22f144c2017-06-12 14:26:21 -04002910
alan-baker3b609772020-09-03 19:10:17 -04002911 // Ops[0] = Entry Point ID
2912 // Ops[1] = Execution Mode
2913 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2914 Ops.clear();
2915 Ops << EntryPoint.second << spv::ExecutionModeLocalSize;
2916
2917 uint32_t XDim = static_cast<uint32_t>(
2918 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2919 uint32_t YDim = static_cast<uint32_t>(
2920 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2921 uint32_t ZDim = static_cast<uint32_t>(
2922 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2923
2924 Ops << XDim << YDim << ZDim;
2925
2926 addSPIRVInst<kExecutionModes>(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002927 }
David Neto22f144c2017-06-12 14:26:21 -04002928 }
2929 }
2930
2931 //
2932 // Generate OpSource.
2933 //
2934 // Ops[0] = SourceLanguage ID
2935 // Ops[1] = Version (LiteralNum)
2936 //
SJW01901d92020-05-21 08:58:31 -05002937 uint32_t LangID = spv::SourceLanguageUnknown;
2938 uint32_t LangVer = 0;
Kévin Petitf0515712020-01-07 18:29:20 +00002939 switch (clspv::Option::Language()) {
2940 case clspv::Option::SourceLanguage::OpenCL_C_10:
SJW01901d92020-05-21 08:58:31 -05002941 LangID = spv::SourceLanguageOpenCL_C;
2942 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002943 break;
2944 case clspv::Option::SourceLanguage::OpenCL_C_11:
SJW01901d92020-05-21 08:58:31 -05002945 LangID = spv::SourceLanguageOpenCL_C;
2946 LangVer = 110;
Kévin Petitf0515712020-01-07 18:29:20 +00002947 break;
2948 case clspv::Option::SourceLanguage::OpenCL_C_12:
SJW01901d92020-05-21 08:58:31 -05002949 LangID = spv::SourceLanguageOpenCL_C;
2950 LangVer = 120;
Kévin Petitf0515712020-01-07 18:29:20 +00002951 break;
2952 case clspv::Option::SourceLanguage::OpenCL_C_20:
SJW01901d92020-05-21 08:58:31 -05002953 LangID = spv::SourceLanguageOpenCL_C;
2954 LangVer = 200;
Kévin Petitf0515712020-01-07 18:29:20 +00002955 break;
Kévin Petit77838ff2020-10-19 18:54:51 +01002956 case clspv::Option::SourceLanguage::OpenCL_C_30:
2957 LangID = spv::SourceLanguageOpenCL_C;
2958 LangVer = 300;
2959 break;
Kévin Petitf0515712020-01-07 18:29:20 +00002960 case clspv::Option::SourceLanguage::OpenCL_CPP:
SJW01901d92020-05-21 08:58:31 -05002961 LangID = spv::SourceLanguageOpenCL_CPP;
2962 LangVer = 100;
Kévin Petitf0515712020-01-07 18:29:20 +00002963 break;
2964 default:
Kévin Petitf0515712020-01-07 18:29:20 +00002965 break;
Kévin Petit0fc88042019-04-09 23:25:02 +01002966 }
David Neto22f144c2017-06-12 14:26:21 -04002967
SJW01901d92020-05-21 08:58:31 -05002968 Ops.clear();
2969 Ops << LangID << LangVer;
SJWf93f5f32020-05-05 07:27:56 -05002970 addSPIRVInst<kDebug>(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002971
2972 if (!BuiltinDimVec.empty()) {
2973 //
2974 // Generate OpDecorates for x/y/z dimension.
2975 //
2976 // Ops[0] = Target ID
2977 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04002978 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04002979
2980 // X Dimension
2981 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002982 Ops << BuiltinDimVec[0] << spv::DecorationSpecId << 0;
SJWf93f5f32020-05-05 07:27:56 -05002983 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002984
2985 // Y Dimension
2986 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002987 Ops << BuiltinDimVec[1] << spv::DecorationSpecId << 1;
SJWf93f5f32020-05-05 07:27:56 -05002988 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002989
2990 // Z Dimension
2991 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05002992 Ops << BuiltinDimVec[2] << spv::DecorationSpecId << 2;
SJWf93f5f32020-05-05 07:27:56 -05002993 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002994 }
2995}
2996
David Netob6e2e062018-04-25 10:32:06 -04002997void SPIRVProducerPass::GenerateEntryPointInitialStores() {
2998 // Work around a driver bug. Initializers on Private variables might not
2999 // work. So the start of the kernel should store the initializer value to the
3000 // variables. Yes, *every* entry point pays this cost if *any* entry point
3001 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3002 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003003 // TODO(dneto): Remove this at some point once fixed drivers are widely
3004 // available.
SJW01901d92020-05-21 08:58:31 -05003005 if (WorkgroupSizeVarID.isValid()) {
3006 assert(WorkgroupSizeValueID.isValid());
David Netob6e2e062018-04-25 10:32:06 -04003007
SJWf93f5f32020-05-05 07:27:56 -05003008 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05003009 Ops << WorkgroupSizeVarID << WorkgroupSizeValueID;
David Netob6e2e062018-04-25 10:32:06 -04003010
SJWf93f5f32020-05-05 07:27:56 -05003011 addSPIRVInst(spv::OpStore, Ops);
David Netob6e2e062018-04-25 10:32:06 -04003012 }
3013}
3014
David Neto22f144c2017-06-12 14:26:21 -04003015void SPIRVProducerPass::GenerateFuncBody(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -04003016 ValueMapType &VMap = getValueMap();
3017
David Netob6e2e062018-04-25 10:32:06 -04003018 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003019
3020 for (BasicBlock &BB : F) {
3021 // Register BasicBlock to ValueMap.
David Neto22f144c2017-06-12 14:26:21 -04003022
3023 //
3024 // Generate OpLabel for Basic Block.
3025 //
SJWf93f5f32020-05-05 07:27:56 -05003026 VMap[&BB] = addSPIRVInst(spv::OpLabel);
David Neto22f144c2017-06-12 14:26:21 -04003027
David Neto6dcd4712017-06-23 11:06:47 -04003028 // OpVariable instructions must come first.
3029 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003030 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3031 // Allocating a pointer requires variable pointers.
3032 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003033 setVariablePointersCapabilities(
3034 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003035 }
David Neto6dcd4712017-06-23 11:06:47 -04003036 GenerateInstruction(I);
3037 }
3038 }
3039
David Neto22f144c2017-06-12 14:26:21 -04003040 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003041 if (clspv::Option::HackInitializers()) {
3042 GenerateEntryPointInitialStores();
3043 }
David Neto22f144c2017-06-12 14:26:21 -04003044 }
3045
3046 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003047 if (!isa<AllocaInst>(I)) {
3048 GenerateInstruction(I);
3049 }
David Neto22f144c2017-06-12 14:26:21 -04003050 }
3051 }
3052}
3053
3054spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3055 const std::map<CmpInst::Predicate, spv::Op> Map = {
3056 {CmpInst::ICMP_EQ, spv::OpIEqual},
3057 {CmpInst::ICMP_NE, spv::OpINotEqual},
3058 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3059 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3060 {CmpInst::ICMP_ULT, spv::OpULessThan},
3061 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3062 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3063 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3064 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3065 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3066 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3067 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3068 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3069 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3070 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3071 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3072 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3073 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3074 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3075 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3076 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3077 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3078
3079 assert(0 != Map.count(I->getPredicate()));
3080
3081 return Map.at(I->getPredicate());
3082}
3083
3084spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3085 const std::map<unsigned, spv::Op> Map{
3086 {Instruction::Trunc, spv::OpUConvert},
3087 {Instruction::ZExt, spv::OpUConvert},
3088 {Instruction::SExt, spv::OpSConvert},
3089 {Instruction::FPToUI, spv::OpConvertFToU},
3090 {Instruction::FPToSI, spv::OpConvertFToS},
3091 {Instruction::UIToFP, spv::OpConvertUToF},
3092 {Instruction::SIToFP, spv::OpConvertSToF},
3093 {Instruction::FPTrunc, spv::OpFConvert},
3094 {Instruction::FPExt, spv::OpFConvert},
3095 {Instruction::BitCast, spv::OpBitcast}};
3096
3097 assert(0 != Map.count(I.getOpcode()));
3098
3099 return Map.at(I.getOpcode());
3100}
3101
3102spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003103 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003104 switch (I.getOpcode()) {
3105 default:
3106 break;
3107 case Instruction::Or:
3108 return spv::OpLogicalOr;
3109 case Instruction::And:
3110 return spv::OpLogicalAnd;
3111 case Instruction::Xor:
3112 return spv::OpLogicalNotEqual;
3113 }
3114 }
3115
alan-bakerb6b09dc2018-11-08 16:59:28 -05003116 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003117 {Instruction::Add, spv::OpIAdd},
3118 {Instruction::FAdd, spv::OpFAdd},
3119 {Instruction::Sub, spv::OpISub},
3120 {Instruction::FSub, spv::OpFSub},
3121 {Instruction::Mul, spv::OpIMul},
3122 {Instruction::FMul, spv::OpFMul},
3123 {Instruction::UDiv, spv::OpUDiv},
3124 {Instruction::SDiv, spv::OpSDiv},
3125 {Instruction::FDiv, spv::OpFDiv},
3126 {Instruction::URem, spv::OpUMod},
3127 {Instruction::SRem, spv::OpSRem},
3128 {Instruction::FRem, spv::OpFRem},
3129 {Instruction::Or, spv::OpBitwiseOr},
3130 {Instruction::Xor, spv::OpBitwiseXor},
3131 {Instruction::And, spv::OpBitwiseAnd},
3132 {Instruction::Shl, spv::OpShiftLeftLogical},
3133 {Instruction::LShr, spv::OpShiftRightLogical},
3134 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3135
3136 assert(0 != Map.count(I.getOpcode()));
3137
3138 return Map.at(I.getOpcode());
3139}
3140
SJW806a5d82020-07-15 12:51:38 -05003141SPIRVID SPIRVProducerPass::getSPIRVBuiltin(spv::BuiltIn BID,
3142 spv::Capability Cap) {
3143 SPIRVID RID;
3144
3145 auto ii = BuiltinConstantMap.find(BID);
3146
3147 if (ii != BuiltinConstantMap.end()) {
3148 return ii->second;
3149 } else {
SJW806a5d82020-07-15 12:51:38 -05003150 addCapability(Cap);
3151
3152 Type *type = PointerType::get(IntegerType::get(module->getContext(), 32),
3153 AddressSpace::Input);
3154
3155 RID = addSPIRVGlobalVariable(getSPIRVType(type), spv::StorageClassInput);
3156
3157 BuiltinConstantMap[BID] = RID;
3158
3159 //
3160 // Generate OpDecorate.
3161 //
3162 // Ops[0] : target
3163 // Ops[1] : decoration
3164 // Ops[2] : SpecId
3165 SPIRVOperandVec Ops;
3166 Ops << RID << spv::DecorationBuiltIn << static_cast<int>(BID);
3167
3168 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
3169 }
3170
3171 return RID;
3172}
3173
3174SPIRVID
3175SPIRVProducerPass::GenerateClspvInstruction(CallInst *Call,
3176 const FunctionInfo &FuncInfo) {
3177 SPIRVID RID;
3178
3179 switch (FuncInfo.getType()) {
3180 case Builtins::kClspvCompositeConstruct:
3181 RID = addSPIRVPlaceholder(Call);
3182 break;
3183 case Builtins::kClspvResource: {
3184 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
3185 // Generate an OpLoad
3186 SPIRVOperandVec Ops;
3187
3188 Ops << Call->getType()->getPointerElementType()
3189 << ResourceVarDeferredLoadCalls[Call];
3190
3191 RID = addSPIRVInst(spv::OpLoad, Ops);
3192
3193 } else {
3194 // This maps to an OpVariable we've already generated.
3195 // No code is generated for the call.
3196 }
3197 break;
3198 }
3199 case Builtins::kClspvLocal: {
3200 // Don't codegen an instruction here, but instead map this call directly
3201 // to the workgroup variable id.
3202 int spec_id = static_cast<int>(
3203 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
3204 const auto &info = LocalSpecIdInfoMap[spec_id];
3205 RID = info.variable_id;
3206 break;
3207 }
3208 case Builtins::kClspvSamplerVarLiteral: {
3209 // Sampler initializers become a load of the corresponding sampler.
3210 // Map this to a load from the variable.
3211 const auto third_param = static_cast<unsigned>(
3212 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue());
3213 auto sampler_value = third_param;
3214 if (clspv::Option::UseSamplerMap()) {
3215 sampler_value = getSamplerMap()[third_param].first;
3216 }
3217
3218 // Generate an OpLoad
3219 SPIRVOperandVec Ops;
3220
3221 Ops << SamplerTy->getPointerElementType()
3222 << SamplerLiteralToIDMap[sampler_value];
3223
3224 RID = addSPIRVInst(spv::OpLoad, Ops);
3225 break;
3226 }
3227 case Builtins::kSpirvAtomicXor: {
3228 // Handle SPIR-V intrinsics
3229 SPIRVOperandVec Ops;
3230
3231 if (!Call->getType()->isVoidTy()) {
3232 Ops << Call->getType();
3233 }
3234
3235 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
3236 Ops << Call->getArgOperand(i);
3237 }
3238
3239 RID = addSPIRVInst(spv::OpAtomicXor, Ops);
3240 break;
3241 }
3242 case Builtins::kSpirvOp: {
3243 // Handle SPIR-V intrinsics
3244 auto *arg0 = dyn_cast<ConstantInt>(Call->getArgOperand(0));
3245 spv::Op opcode = static_cast<spv::Op>(arg0->getZExtValue());
3246 if (opcode != spv::OpNop) {
3247 SPIRVOperandVec Ops;
3248
3249 if (!Call->getType()->isVoidTy()) {
3250 Ops << Call->getType();
3251 }
3252
3253 for (unsigned i = 1; i < Call->getNumArgOperands(); i++) {
3254 Ops << Call->getArgOperand(i);
3255 }
3256
3257 RID = addSPIRVInst(opcode, Ops);
3258 }
3259 break;
3260 }
3261 case Builtins::kSpirvCopyMemory: {
3262 //
3263 // Generate OpCopyMemory.
3264 //
3265
3266 // Ops[0] = Dst ID
3267 // Ops[1] = Src ID
3268 // Ops[2] = Memory Access
3269 // Ops[3] = Alignment
3270
3271 auto IsVolatile =
3272 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
3273
3274 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
3275 : spv::MemoryAccessMaskNone;
3276
3277 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
3278
3279 auto Alignment =
3280 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
3281
3282 SPIRVOperandVec Ops;
3283 Ops << Call->getArgOperand(0) << Call->getArgOperand(1) << MemoryAccess
3284 << static_cast<uint32_t>(Alignment);
3285
3286 RID = addSPIRVInst(spv::OpCopyMemory, Ops);
3287 break;
3288 }
3289 default:
3290 llvm_unreachable("Unknown CLSPV Instruction");
3291 break;
3292 }
3293 return RID;
3294}
3295
3296SPIRVID
3297SPIRVProducerPass::GenerateImageInstruction(CallInst *Call,
3298 const FunctionInfo &FuncInfo) {
3299 SPIRVID RID;
3300
3301 LLVMContext &Context = module->getContext();
3302 switch (FuncInfo.getType()) {
3303 case Builtins::kReadImagef:
3304 case Builtins::kReadImageh:
3305 case Builtins::kReadImagei:
3306 case Builtins::kReadImageui: {
3307 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
3308 // Additionally, OpTypeSampledImage is generated.
alan-bakerf6bc8252020-09-23 14:58:55 -04003309 const auto image_ty = Call->getArgOperand(0)->getType();
SJW806a5d82020-07-15 12:51:38 -05003310 const auto &pi = FuncInfo.getParameter(1);
3311 if (pi.isSampler()) {
3312 //
3313 // Generate OpSampledImage.
3314 //
3315 // Ops[0] = Result Type ID
3316 // Ops[1] = Image ID
3317 // Ops[2] = Sampler ID
3318 //
3319 SPIRVOperandVec Ops;
3320
3321 Value *Image = Call->getArgOperand(0);
3322 Value *Sampler = Call->getArgOperand(1);
3323 Value *Coordinate = Call->getArgOperand(2);
3324
3325 TypeMapType &OpImageTypeMap = getImageTypeMap();
3326 Type *ImageTy = Image->getType()->getPointerElementType();
3327 SPIRVID ImageTyID = OpImageTypeMap[ImageTy];
3328
3329 Ops << ImageTyID << Image << Sampler;
3330
3331 SPIRVID SampledImageID = addSPIRVInst(spv::OpSampledImage, Ops);
3332
3333 //
3334 // Generate OpImageSampleExplicitLod.
3335 //
3336 // Ops[0] = Result Type ID
3337 // Ops[1] = Sampled Image ID
3338 // Ops[2] = Coordinate ID
3339 // Ops[3] = Image Operands Type ID
3340 // Ops[4] ... Ops[n] = Operands ID
3341 //
3342 Ops.clear();
3343
3344 const bool is_int_image = IsIntImageType(Image->getType());
3345 SPIRVID result_type;
3346 if (is_int_image) {
3347 result_type = v4int32ID;
3348 } else {
3349 result_type = getSPIRVType(Call->getType());
3350 }
3351
3352 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
3353 Ops << result_type << SampledImageID << Coordinate
3354 << spv::ImageOperandsLodMask << CstFP0;
3355
3356 RID = addSPIRVInst(spv::OpImageSampleExplicitLod, Ops);
3357
3358 if (is_int_image) {
3359 // Generate the bitcast.
3360 Ops.clear();
3361 Ops << Call->getType() << RID;
3362 RID = addSPIRVInst(spv::OpBitcast, Ops);
3363 }
alan-bakerf6bc8252020-09-23 14:58:55 -04003364 } else if (IsStorageImageType(image_ty)) {
3365 // read_image on a storage image is mapped to OpImageRead.
3366 Value *Image = Call->getArgOperand(0);
3367 Value *Coordinate = Call->getArgOperand(1);
3368
3369 //
3370 // Generate OpImageRead
3371 //
3372 // Ops[0] = Result Type ID
3373 // Ops[1] = Image ID
3374 // Ops[2] = Coordinate
3375 // No optional image operands.
3376 //
3377 SPIRVOperandVec Ops;
3378
3379 const bool is_int_image = IsIntImageType(Image->getType());
3380 SPIRVID result_type;
3381 if (is_int_image) {
3382 result_type = v4int32ID;
3383 } else {
3384 result_type = getSPIRVType(Call->getType());
3385 }
3386
3387 Ops << result_type << Image << Coordinate;
3388 RID = addSPIRVInst(spv::OpImageRead, Ops);
3389
3390 if (is_int_image) {
3391 // Generate the bitcast.
3392 Ops.clear();
3393 Ops << Call->getType() << RID;
3394 RID = addSPIRVInst(spv::OpBitcast, Ops);
3395 }
3396
3397 // OpImageRead requires StorageImageReadWithoutFormat.
3398 addCapability(spv::CapabilityStorageImageReadWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003399 } else {
alan-bakerf6bc8252020-09-23 14:58:55 -04003400 // read_image on a sampled image (without a sampler) is mapped to
3401 // OpImageFetch.
SJW806a5d82020-07-15 12:51:38 -05003402 Value *Image = Call->getArgOperand(0);
3403 Value *Coordinate = Call->getArgOperand(1);
3404
3405 //
3406 // Generate OpImageFetch
3407 //
3408 // Ops[0] = Result Type ID
3409 // Ops[1] = Image ID
3410 // Ops[2] = Coordinate ID
3411 // Ops[3] = Lod
3412 // Ops[4] = 0
3413 //
3414 SPIRVOperandVec Ops;
3415
3416 const bool is_int_image = IsIntImageType(Image->getType());
3417 SPIRVID result_type;
3418 if (is_int_image) {
3419 result_type = v4int32ID;
3420 } else {
3421 result_type = getSPIRVType(Call->getType());
3422 }
3423
3424 Ops << result_type << Image << Coordinate << spv::ImageOperandsLodMask
3425 << getSPIRVInt32Constant(0);
3426
3427 RID = addSPIRVInst(spv::OpImageFetch, Ops);
3428
3429 if (is_int_image) {
3430 // Generate the bitcast.
3431 Ops.clear();
3432 Ops << Call->getType() << RID;
3433 RID = addSPIRVInst(spv::OpBitcast, Ops);
3434 }
3435 }
3436 break;
3437 }
3438
3439 case Builtins::kWriteImagef:
3440 case Builtins::kWriteImageh:
3441 case Builtins::kWriteImagei:
3442 case Builtins::kWriteImageui: {
3443 // write_image is mapped to OpImageWrite.
3444 //
3445 // Generate OpImageWrite.
3446 //
3447 // Ops[0] = Image ID
3448 // Ops[1] = Coordinate ID
3449 // Ops[2] = Texel ID
3450 // Ops[3] = (Optional) Image Operands Type (Literal Number)
3451 // Ops[4] ... Ops[n] = (Optional) Operands ID
3452 //
3453 SPIRVOperandVec Ops;
3454
3455 Value *Image = Call->getArgOperand(0);
3456 Value *Coordinate = Call->getArgOperand(1);
3457 Value *Texel = Call->getArgOperand(2);
3458
3459 SPIRVID TexelID = getSPIRVValue(Texel);
3460
3461 const bool is_int_image = IsIntImageType(Image->getType());
3462 if (is_int_image) {
3463 // Generate a bitcast to v4int and use it as the texel value.
3464 Ops << v4int32ID << TexelID;
3465 TexelID = addSPIRVInst(spv::OpBitcast, Ops);
3466 Ops.clear();
3467 }
3468 Ops << Image << Coordinate << TexelID;
SJW806a5d82020-07-15 12:51:38 -05003469 RID = addSPIRVInst(spv::OpImageWrite, Ops);
alan-bakerf6bc8252020-09-23 14:58:55 -04003470
3471 // Image writes require StorageImageWriteWithoutFormat.
3472 addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
SJW806a5d82020-07-15 12:51:38 -05003473 break;
3474 }
3475
3476 case Builtins::kGetImageHeight:
3477 case Builtins::kGetImageWidth:
3478 case Builtins::kGetImageDepth:
3479 case Builtins::kGetImageDim: {
3480 // get_image_* is mapped to OpImageQuerySize or OpImageQuerySizeLod
3481 addCapability(spv::CapabilityImageQuery);
3482
3483 //
3484 // Generate OpImageQuerySize[Lod]
3485 //
3486 // Ops[0] = Image ID
3487 //
3488 // Result type has components equal to the dimensionality of the image,
3489 // plus 1 if the image is arrayed.
3490 //
3491 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3492 SPIRVOperandVec Ops;
3493
3494 // Implement:
3495 // %sizes = OpImageQuerySize[Lod] %uint[2|3|4] %im [%uint_0]
3496 SPIRVID SizesTypeID;
3497
3498 Value *Image = Call->getArgOperand(0);
3499 const uint32_t dim = ImageDimensionality(Image->getType());
3500 const uint32_t components =
3501 dim + (IsArrayImageType(Image->getType()) ? 1 : 0);
3502 if (components == 1) {
3503 SizesTypeID = getSPIRVType(Type::getInt32Ty(Context));
3504 } else {
3505 SizesTypeID = getSPIRVType(
3506 FixedVectorType::get(Type::getInt32Ty(Context), components));
3507 }
3508 Ops << SizesTypeID << Image;
3509 spv::Op query_opcode = spv::OpImageQuerySize;
3510 if (IsSampledImageType(Image->getType())) {
3511 query_opcode = spv::OpImageQuerySizeLod;
3512 // Need explicit 0 for Lod operand.
3513 Ops << getSPIRVInt32Constant(0);
3514 }
3515
3516 RID = addSPIRVInst(query_opcode, Ops);
3517
3518 // May require an extra instruction to create the appropriate result of
3519 // the builtin function.
3520 if (FuncInfo.getType() == Builtins::kGetImageDim) {
3521 if (dim == 3) {
3522 // get_image_dim returns an int4 for 3D images.
3523 //
3524
3525 // Implement:
3526 // %result = OpCompositeConstruct %uint4 %sizes %uint_0
3527 Ops.clear();
3528 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 4) << RID
3529 << getSPIRVInt32Constant(0);
3530
3531 RID = addSPIRVInst(spv::OpCompositeConstruct, Ops);
3532 } else if (dim != components) {
3533 // get_image_dim return an int2 regardless of the arrayedness of the
3534 // image. If the image is arrayed an element must be dropped from the
3535 // query result.
3536 //
3537
3538 // Implement:
3539 // %result = OpVectorShuffle %uint2 %sizes %sizes 0 1
3540 Ops.clear();
3541 Ops << FixedVectorType::get(Type::getInt32Ty(Context), 2) << RID << RID
3542 << 0 << 1;
3543
3544 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
3545 }
3546 } else if (components > 1) {
3547 // Implement:
3548 // %result = OpCompositeExtract %uint %sizes <component number>
3549 Ops.clear();
3550 Ops << Call->getType() << RID;
3551
3552 uint32_t component = 0;
3553 if (FuncInfo.getType() == Builtins::kGetImageHeight)
3554 component = 1;
3555 else if (FuncInfo.getType() == Builtins::kGetImageDepth)
3556 component = 2;
3557 Ops << component;
3558
3559 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
3560 }
3561 break;
3562 }
3563 default:
3564 llvm_unreachable("Unsupported Image builtin");
3565 }
3566
3567 return RID;
3568}
3569
3570SPIRVID
3571SPIRVProducerPass::GenerateSubgroupInstruction(CallInst *Call,
3572 const FunctionInfo &FuncInfo) {
3573 SPIRVID RID;
3574
3575 // requires SPIRV version 1.3 or greater
3576 if (SpvVersion() != SPIRVVersion::SPIRV_1_3) {
3577 // llvm_unreachable("SubGroups extension requires SPIRV 1.3 or greater");
3578 // TODO(sjw): error out gracefully
3579 }
3580
3581 auto loadBuiltin = [this, Call](spv::BuiltIn spvBI,
3582 spv::Capability spvCap =
3583 spv::CapabilityGroupNonUniform) {
3584 SPIRVOperandVec Ops;
3585 Ops << Call->getType() << this->getSPIRVBuiltin(spvBI, spvCap);
3586
3587 return addSPIRVInst(spv::OpLoad, Ops);
3588 };
3589
3590 spv::Op op = spv::OpNop;
3591 switch (FuncInfo.getType()) {
3592 case Builtins::kGetSubGroupSize:
3593 return loadBuiltin(spv::BuiltInSubgroupSize);
3594 case Builtins::kGetNumSubGroups:
3595 return loadBuiltin(spv::BuiltInNumSubgroups);
3596 case Builtins::kGetSubGroupId:
3597 return loadBuiltin(spv::BuiltInSubgroupId);
3598 case Builtins::kGetSubGroupLocalId:
3599 return loadBuiltin(spv::BuiltInSubgroupLocalInvocationId);
3600
3601 case Builtins::kSubGroupBroadcast:
3602 if (SpvVersion() < SPIRVVersion::SPIRV_1_5 &&
3603 !dyn_cast<ConstantInt>(Call->getOperand(1))) {
3604 llvm_unreachable("sub_group_broadcast requires constant lane Id for "
3605 "SPIRV version < 1.5");
3606 }
3607 addCapability(spv::CapabilityGroupNonUniformBallot);
3608 op = spv::OpGroupNonUniformBroadcast;
3609 break;
3610
3611 case Builtins::kSubGroupAll:
3612 addCapability(spv::CapabilityGroupNonUniformVote);
3613 op = spv::OpGroupNonUniformAll;
3614 break;
3615 case Builtins::kSubGroupAny:
3616 addCapability(spv::CapabilityGroupNonUniformVote);
3617 op = spv::OpGroupNonUniformAny;
3618 break;
3619 case Builtins::kSubGroupReduceAdd:
3620 case Builtins::kSubGroupScanExclusiveAdd:
3621 case Builtins::kSubGroupScanInclusiveAdd: {
3622 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3623 if (FuncInfo.getParameter(0).type_id == Type::IntegerTyID) {
3624 op = spv::OpGroupNonUniformIAdd;
3625 } else {
3626 op = spv::OpGroupNonUniformFAdd;
3627 }
3628 break;
3629 }
3630 case Builtins::kSubGroupReduceMin:
3631 case Builtins::kSubGroupScanExclusiveMin:
3632 case Builtins::kSubGroupScanInclusiveMin: {
3633 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3634 auto &param = FuncInfo.getParameter(0);
3635 if (param.type_id == Type::IntegerTyID) {
3636 op = param.is_signed ? spv::OpGroupNonUniformSMin
3637 : spv::OpGroupNonUniformUMin;
3638 } else {
3639 op = spv::OpGroupNonUniformFMin;
3640 }
3641 break;
3642 }
3643 case Builtins::kSubGroupReduceMax:
3644 case Builtins::kSubGroupScanExclusiveMax:
3645 case Builtins::kSubGroupScanInclusiveMax: {
3646 addCapability(spv::CapabilityGroupNonUniformArithmetic);
3647 auto &param = FuncInfo.getParameter(0);
3648 if (param.type_id == Type::IntegerTyID) {
3649 op = param.is_signed ? spv::OpGroupNonUniformSMax
3650 : spv::OpGroupNonUniformUMax;
3651 } else {
3652 op = spv::OpGroupNonUniformFMax;
3653 }
3654 break;
3655 }
3656
3657 case Builtins::kGetEnqueuedNumSubGroups:
3658 // TODO(sjw): requires CapabilityKernel (incompatible with Shader)
3659 case Builtins::kGetMaxSubGroupSize:
3660 // TODO(sjw): use SpecConstant, capability Kernel (incompatible with Shader)
3661 case Builtins::kSubGroupBarrier:
3662 case Builtins::kSubGroupReserveReadPipe:
3663 case Builtins::kSubGroupReserveWritePipe:
3664 case Builtins::kSubGroupCommitReadPipe:
3665 case Builtins::kSubGroupCommitWritePipe:
3666 case Builtins::kGetKernelSubGroupCountForNdrange:
3667 case Builtins::kGetKernelMaxSubGroupSizeForNdrange:
3668 default:
3669 Call->print(errs());
3670 llvm_unreachable("Unsupported sub_group operation");
3671 break;
3672 }
3673
3674 assert(op != spv::OpNop);
3675
3676 SPIRVOperandVec Operands;
3677
3678 //
3679 // Generate OpGroupNonUniform*
3680 //
3681 // Ops[0] = Result Type ID
3682 // Ops[1] = ScopeSubgroup
3683 // Ops[2] = Value ID
3684 // Ops[3] = Local ID
3685
3686 // The result type.
3687 Operands << Call->getType();
3688
3689 // Subgroup Scope
3690 Operands << getSPIRVInt32Constant(spv::ScopeSubgroup);
3691
3692 switch (FuncInfo.getType()) {
3693 case Builtins::kSubGroupReduceAdd:
3694 case Builtins::kSubGroupReduceMin:
3695 case Builtins::kSubGroupReduceMax:
3696 Operands << spv::GroupOperationReduce;
3697 break;
3698 case Builtins::kSubGroupScanExclusiveAdd:
3699 case Builtins::kSubGroupScanExclusiveMin:
3700 case Builtins::kSubGroupScanExclusiveMax:
3701 Operands << spv::GroupOperationExclusiveScan;
3702 break;
3703 case Builtins::kSubGroupScanInclusiveAdd:
3704 case Builtins::kSubGroupScanInclusiveMin:
3705 case Builtins::kSubGroupScanInclusiveMax:
3706 Operands << spv::GroupOperationInclusiveScan;
3707 break;
3708 default:
3709 break;
3710 }
3711
3712 for (Use &use : Call->arg_operands()) {
3713 Operands << use.get();
3714 }
3715
3716 return addSPIRVInst(op, Operands);
3717}
3718
3719SPIRVID SPIRVProducerPass::GenerateInstructionFromCall(CallInst *Call) {
3720 LLVMContext &Context = module->getContext();
3721
3722 auto &func_info = Builtins::Lookup(Call->getCalledFunction());
3723 auto func_type = func_info.getType();
3724
3725 if (BUILTIN_IN_GROUP(func_type, Clspv)) {
3726 return GenerateClspvInstruction(Call, func_info);
3727 } else if (BUILTIN_IN_GROUP(func_type, Image)) {
3728 return GenerateImageInstruction(Call, func_info);
3729 } else if (BUILTIN_IN_GROUP(func_type, SubgroupsKHR)) {
3730 return GenerateSubgroupInstruction(Call, func_info);
3731 }
3732
3733 SPIRVID RID;
3734
3735 switch (func_type) {
3736 case Builtins::kPopcount: {
3737 //
3738 // Generate OpBitCount
3739 //
3740 // Ops[0] = Result Type ID
3741 // Ops[1] = Base ID
3742 SPIRVOperandVec Ops;
3743 Ops << Call->getType() << Call->getOperand(0);
3744
3745 RID = addSPIRVInst(spv::OpBitCount, Ops);
3746 break;
3747 }
3748 default: {
3749 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(func_info);
3750
3751 if (EInst) {
3752 SPIRVID ExtInstImportID = getOpExtInstImportID();
3753
3754 //
3755 // Generate OpExtInst.
3756 //
3757
3758 // Ops[0] = Result Type ID
3759 // Ops[1] = Set ID (OpExtInstImport ID)
3760 // Ops[2] = Instruction Number (Literal Number)
3761 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
3762 SPIRVOperandVec Ops;
3763
3764 Ops << Call->getType() << ExtInstImportID << EInst;
3765
3766 for (auto &use : Call->arg_operands()) {
3767 Ops << use.get();
3768 }
3769
3770 RID = addSPIRVInst(spv::OpExtInst, Ops);
3771
3772 const auto IndirectExtInst = getIndirectExtInstEnum(func_info);
3773 if (IndirectExtInst != kGlslExtInstBad) {
SJW806a5d82020-07-15 12:51:38 -05003774 // Generate one more instruction that uses the result of the extended
3775 // instruction. Its result id is one more than the id of the
3776 // extended instruction.
3777 auto generate_extra_inst = [this, &Context, &Call,
3778 &RID](spv::Op opcode, Constant *constant) {
3779 //
3780 // Generate instruction like:
3781 // result = opcode constant <extinst-result>
3782 //
3783 // Ops[0] = Result Type ID
3784 // Ops[1] = Operand 0 ;; the constant, suitably splatted
3785 // Ops[2] = Operand 1 ;; the result of the extended instruction
3786 SPIRVOperandVec Ops;
3787
3788 Type *resultTy = Call->getType();
3789
3790 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
alan-baker931253b2020-08-20 17:15:38 -04003791 constant =
3792 ConstantVector::getSplat(vectorTy->getElementCount(), constant);
SJW806a5d82020-07-15 12:51:38 -05003793 }
3794 Ops << resultTy << constant << RID;
3795
3796 RID = addSPIRVInst(opcode, Ops);
3797 };
3798
3799 auto IntTy = Type::getInt32Ty(Context);
3800 switch (IndirectExtInst) {
3801 case glsl::ExtInstFindUMsb: // Implementing clz
3802 generate_extra_inst(spv::OpISub, ConstantInt::get(IntTy, 31));
3803 break;
3804 case glsl::ExtInstAcos: // Implementing acospi
3805 case glsl::ExtInstAsin: // Implementing asinpi
3806 case glsl::ExtInstAtan: // Implementing atanpi
3807 case glsl::ExtInstAtan2: // Implementing atan2pi
3808 generate_extra_inst(
3809 spv::OpFMul,
3810 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
3811 break;
3812
3813 default:
3814 assert(false && "internally inconsistent");
3815 }
3816 }
3817 } else {
SJW806a5d82020-07-15 12:51:38 -05003818 // A real function call (not builtin)
3819 // Call instruction is deferred because it needs function's ID.
3820 RID = addSPIRVPlaceholder(Call);
3821 }
3822
3823 break;
3824 }
3825 }
3826
3827 return RID;
3828}
3829
David Neto22f144c2017-06-12 14:26:21 -04003830void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
David Neto22f144c2017-06-12 14:26:21 -04003831 ValueMapType &VMap = getValueMap();
SJW806a5d82020-07-15 12:51:38 -05003832 LLVMContext &Context = module->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003833
SJW806a5d82020-07-15 12:51:38 -05003834 SPIRVID RID;
David Neto22f144c2017-06-12 14:26:21 -04003835
3836 switch (I.getOpcode()) {
3837 default: {
3838 if (Instruction::isCast(I.getOpcode())) {
3839 //
3840 // Generate SPIRV instructions for cast operators.
3841 //
3842
David Netod2de94a2017-08-28 17:27:47 -04003843 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003844 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003845 auto toI8 = Ty == Type::getInt8Ty(Context);
3846 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003847 // Handle zext, sext and uitofp with i1 type specially.
3848 if ((I.getOpcode() == Instruction::ZExt ||
3849 I.getOpcode() == Instruction::SExt ||
3850 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003851 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003852 //
3853 // Generate OpSelect.
3854 //
3855
3856 // Ops[0] = Result Type ID
3857 // Ops[1] = Condition ID
3858 // Ops[2] = True Constant ID
3859 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05003860 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003861
SJW01901d92020-05-21 08:58:31 -05003862 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003863
David Neto22f144c2017-06-12 14:26:21 -04003864 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003865 Ops << ConstantInt::get(I.getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04003866 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003867 Ops << ConstantInt::getSigned(I.getType(), -1);
David Neto22f144c2017-06-12 14:26:21 -04003868 } else {
SJW01901d92020-05-21 08:58:31 -05003869 Ops << ConstantFP::get(Context, APFloat(1.0f));
David Neto22f144c2017-06-12 14:26:21 -04003870 }
David Neto22f144c2017-06-12 14:26:21 -04003871
David Neto22f144c2017-06-12 14:26:21 -04003872 if (I.getOpcode() == Instruction::ZExt) {
SJW01901d92020-05-21 08:58:31 -05003873 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003874 } else if (I.getOpcode() == Instruction::SExt) {
SJW01901d92020-05-21 08:58:31 -05003875 Ops << Constant::getNullValue(I.getType());
David Neto22f144c2017-06-12 14:26:21 -04003876 } else {
SJW01901d92020-05-21 08:58:31 -05003877 Ops << ConstantFP::get(Context, APFloat(0.0f));
David Neto22f144c2017-06-12 14:26:21 -04003878 }
David Neto22f144c2017-06-12 14:26:21 -04003879
SJWf93f5f32020-05-05 07:27:56 -05003880 RID = addSPIRVInst(spv::OpSelect, Ops);
alan-bakerb39c8262019-03-08 14:03:37 -05003881 } else if (!clspv::Option::Int8Support() &&
3882 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003883 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3884 // 8 bits.
3885 // Before:
3886 // %result = trunc i32 %a to i8
3887 // After
3888 // %result = OpBitwiseAnd %uint %a %uint_255
3889
SJWf93f5f32020-05-05 07:27:56 -05003890 SPIRVOperandVec Ops;
David Netod2de94a2017-08-28 17:27:47 -04003891
SJW806a5d82020-07-15 12:51:38 -05003892 Ops << OpTy << I.getOperand(0) << getSPIRVInt32Constant(255);
David Netod2de94a2017-08-28 17:27:47 -04003893
SJWf93f5f32020-05-05 07:27:56 -05003894 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003895 } else {
3896 // Ops[0] = Result Type ID
3897 // Ops[1] = Source Value ID
SJWf93f5f32020-05-05 07:27:56 -05003898 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003899
SJW01901d92020-05-21 08:58:31 -05003900 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04003901
SJWf93f5f32020-05-05 07:27:56 -05003902 RID = addSPIRVInst(GetSPIRVCastOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003903 }
3904 } else if (isa<BinaryOperator>(I)) {
3905 //
3906 // Generate SPIRV instructions for binary operators.
3907 //
3908
3909 // Handle xor with i1 type specially.
3910 if (I.getOpcode() == Instruction::Xor &&
3911 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003912 ((isa<ConstantInt>(I.getOperand(0)) &&
3913 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3914 (isa<ConstantInt>(I.getOperand(1)) &&
3915 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003916 //
3917 // Generate OpLogicalNot.
3918 //
3919 // Ops[0] = Result Type ID
3920 // Ops[1] = Operand
SJWf93f5f32020-05-05 07:27:56 -05003921 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003922
SJW01901d92020-05-21 08:58:31 -05003923 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003924
3925 Value *CondV = I.getOperand(0);
3926 if (isa<Constant>(I.getOperand(0))) {
3927 CondV = I.getOperand(1);
3928 }
SJW01901d92020-05-21 08:58:31 -05003929 Ops << CondV;
David Neto22f144c2017-06-12 14:26:21 -04003930
SJWf93f5f32020-05-05 07:27:56 -05003931 RID = addSPIRVInst(spv::OpLogicalNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003932 } else {
3933 // Ops[0] = Result Type ID
3934 // Ops[1] = Operand 0
3935 // Ops[2] = Operand 1
SJWf93f5f32020-05-05 07:27:56 -05003936 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003937
SJW01901d92020-05-21 08:58:31 -05003938 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04003939
SJWf93f5f32020-05-05 07:27:56 -05003940 RID = addSPIRVInst(GetSPIRVBinaryOpcode(I), Ops);
David Neto22f144c2017-06-12 14:26:21 -04003941 }
alan-bakerc9c55ae2019-12-02 16:01:27 -05003942 } else if (I.getOpcode() == Instruction::FNeg) {
3943 // The only unary operator.
3944 //
3945 // Ops[0] = Result Type ID
3946 // Ops[1] = Operand 0
SJW01901d92020-05-21 08:58:31 -05003947 SPIRVOperandVec Ops;
alan-bakerc9c55ae2019-12-02 16:01:27 -05003948
SJW01901d92020-05-21 08:58:31 -05003949 Ops << I.getType() << I.getOperand(0);
3950 RID = addSPIRVInst(spv::OpFNegate, Ops);
Marco Antognini68e5c512020-09-09 16:08:57 +01003951 } else if (I.getOpcode() == Instruction::Unreachable) {
3952 RID = addSPIRVInst(spv::OpUnreachable);
David Neto22f144c2017-06-12 14:26:21 -04003953 } else {
3954 I.print(errs());
3955 llvm_unreachable("Unsupported instruction???");
3956 }
3957 break;
3958 }
3959 case Instruction::GetElementPtr: {
3960 auto &GlobalConstArgSet = getGlobalConstArgSet();
3961
3962 //
3963 // Generate OpAccessChain.
3964 //
3965 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3966
3967 //
3968 // Generate OpAccessChain.
3969 //
3970
3971 // Ops[0] = Result Type ID
3972 // Ops[1] = Base ID
3973 // Ops[2] ... Ops[n] = Indexes ID
SJWf93f5f32020-05-05 07:27:56 -05003974 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04003975
alan-bakerb6b09dc2018-11-08 16:59:28 -05003976 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003977 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3978 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3979 // Use pointer type with private address space for global constant.
3980 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003981 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003982 }
David Neto257c3892018-04-11 13:19:45 -04003983
SJW01901d92020-05-21 08:58:31 -05003984 Ops << ResultType;
David Neto22f144c2017-06-12 14:26:21 -04003985
David Neto862b7d82018-06-14 18:48:37 -04003986 // Generate the base pointer.
SJW01901d92020-05-21 08:58:31 -05003987 Ops << GEP->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04003988
David Neto862b7d82018-06-14 18:48:37 -04003989 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003990
3991 //
3992 // Follows below rules for gep.
3993 //
David Neto862b7d82018-06-14 18:48:37 -04003994 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3995 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003996 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3997 // first index.
3998 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3999 // use gep's first index.
4000 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
4001 // gep's first index.
4002 //
4003 spv::Op Opcode = spv::OpAccessChain;
4004 unsigned offset = 0;
4005 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04004006 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04004007 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04004008 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04004009 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04004010 }
David Neto862b7d82018-06-14 18:48:37 -04004011 } else {
David Neto22f144c2017-06-12 14:26:21 -04004012 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04004013 }
4014
4015 if (Opcode == spv::OpPtrAccessChain) {
alan-baker7506abb2020-09-10 15:02:55 -04004016 // Shader validation in the SPIR-V spec requires that the base pointer to
4017 // OpPtrAccessChain (in StorageBuffer storage class) be decorated with
4018 // ArrayStride.
alan-baker5b86ed72019-02-15 08:26:50 -05004019 auto address_space = ResultType->getAddressSpace();
4020 setVariablePointersCapabilities(address_space);
4021 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04004022 case spv::StorageClassStorageBuffer:
David Neto1a1a0582017-07-07 12:01:44 -04004023 // Save the need to generate an ArrayStride decoration. But defer
4024 // generation until later, so we only make one decoration.
alan-baker7506abb2020-09-10 15:02:55 -04004025 getTypesNeedingArrayStride().insert(GEP->getPointerOperandType());
4026 break;
4027 case spv::StorageClassWorkgroup:
Alan Bakerfcda9482018-10-02 17:09:59 -04004028 break;
4029 default:
alan-baker7506abb2020-09-10 15:02:55 -04004030 llvm_unreachable(
4031 "OpPtrAccessChain is not supported for this storage class");
Alan Bakerfcda9482018-10-02 17:09:59 -04004032 break;
David Neto1a1a0582017-07-07 12:01:44 -04004033 }
David Neto22f144c2017-06-12 14:26:21 -04004034 }
4035
4036 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
SJW01901d92020-05-21 08:58:31 -05004037 Ops << *II;
David Neto22f144c2017-06-12 14:26:21 -04004038 }
4039
SJWf93f5f32020-05-05 07:27:56 -05004040 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004041 break;
4042 }
4043 case Instruction::ExtractValue: {
4044 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
4045 // Ops[0] = Result Type ID
4046 // Ops[1] = Composite ID
4047 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004048 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004049
SJW01901d92020-05-21 08:58:31 -05004050 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004051
SJW01901d92020-05-21 08:58:31 -05004052 Ops << EVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004053
4054 for (auto &Index : EVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004055 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004056 }
4057
SJWf93f5f32020-05-05 07:27:56 -05004058 RID = addSPIRVInst(spv::OpCompositeExtract, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004059 break;
4060 }
4061 case Instruction::InsertValue: {
4062 InsertValueInst *IVI = cast<InsertValueInst>(&I);
4063 // Ops[0] = Result Type ID
4064 // Ops[1] = Object ID
4065 // Ops[2] = Composite ID
4066 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004067 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004068
SJW01901d92020-05-21 08:58:31 -05004069 Ops << I.getType() << IVI->getInsertedValueOperand()
4070 << IVI->getAggregateOperand();
David Neto22f144c2017-06-12 14:26:21 -04004071
4072 for (auto &Index : IVI->indices()) {
SJW01901d92020-05-21 08:58:31 -05004073 Ops << Index;
David Neto22f144c2017-06-12 14:26:21 -04004074 }
4075
SJWf93f5f32020-05-05 07:27:56 -05004076 RID = addSPIRVInst(spv::OpCompositeInsert, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004077 break;
4078 }
4079 case Instruction::Select: {
4080 //
4081 // Generate OpSelect.
4082 //
4083
4084 // Ops[0] = Result Type ID
4085 // Ops[1] = Condition ID
4086 // Ops[2] = True Constant ID
4087 // Ops[3] = False Constant ID
SJWf93f5f32020-05-05 07:27:56 -05004088 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004089
4090 // Find SPIRV instruction for parameter type.
4091 auto Ty = I.getType();
4092 if (Ty->isPointerTy()) {
4093 auto PointeeTy = Ty->getPointerElementType();
4094 if (PointeeTy->isStructTy() &&
4095 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
4096 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05004097 } else {
4098 // Selecting between pointers requires variable pointers.
4099 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
4100 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
SJW01901d92020-05-21 08:58:31 -05004101 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004102 }
David Neto22f144c2017-06-12 14:26:21 -04004103 }
4104 }
4105
SJW01901d92020-05-21 08:58:31 -05004106 Ops << Ty << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004107
SJWf93f5f32020-05-05 07:27:56 -05004108 RID = addSPIRVInst(spv::OpSelect, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004109 break;
4110 }
4111 case Instruction::ExtractElement: {
4112 // Handle <4 x i8> type manually.
4113 Type *CompositeTy = I.getOperand(0)->getType();
4114 if (is4xi8vec(CompositeTy)) {
4115 //
4116 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
4117 // <4 x i8>.
4118 //
4119
4120 //
4121 // Generate OpShiftRightLogical
4122 //
4123 // Ops[0] = Result Type ID
4124 // Ops[1] = Operand 0
4125 // Ops[2] = Operand 1
4126 //
SJWf93f5f32020-05-05 07:27:56 -05004127 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004128
SJW01901d92020-05-21 08:58:31 -05004129 Ops << CompositeTy << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004130
SJW01901d92020-05-21 08:58:31 -05004131 SPIRVID Op1ID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004132 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4133 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004134 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4135 Op1ID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004136 } else {
4137 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004138 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004139
SJW806a5d82020-07-15 12:51:38 -05004140 TmpOps << Type::getInt32Ty(Context) << I.getOperand(1)
4141 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004142
SJWf93f5f32020-05-05 07:27:56 -05004143 Op1ID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004144 }
SJW01901d92020-05-21 08:58:31 -05004145 Ops << Op1ID;
David Neto22f144c2017-06-12 14:26:21 -04004146
SJW01901d92020-05-21 08:58:31 -05004147 SPIRVID ShiftID = addSPIRVInst(spv::OpShiftRightLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004148
4149 //
4150 // Generate OpBitwiseAnd
4151 //
4152 // Ops[0] = Result Type ID
4153 // Ops[1] = Operand 0
4154 // Ops[2] = Operand 1
4155 //
4156 Ops.clear();
4157
SJW806a5d82020-07-15 12:51:38 -05004158 Ops << CompositeTy << ShiftID << getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004159
SJWf93f5f32020-05-05 07:27:56 -05004160 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004161 break;
4162 }
4163
4164 // Ops[0] = Result Type ID
4165 // Ops[1] = Composite ID
4166 // Ops[2] ... Ops[n] = Indexes (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004167 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004168
SJW01901d92020-05-21 08:58:31 -05004169 Ops << I.getType() << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004170
4171 spv::Op Opcode = spv::OpCompositeExtract;
4172 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
SJW01901d92020-05-21 08:58:31 -05004173 Ops << static_cast<uint32_t>(CI->getZExtValue());
David Neto22f144c2017-06-12 14:26:21 -04004174 } else {
SJW01901d92020-05-21 08:58:31 -05004175 Ops << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004176 Opcode = spv::OpVectorExtractDynamic;
4177 }
4178
SJWf93f5f32020-05-05 07:27:56 -05004179 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004180 break;
4181 }
4182 case Instruction::InsertElement: {
4183 // Handle <4 x i8> type manually.
4184 Type *CompositeTy = I.getOperand(0)->getType();
4185 if (is4xi8vec(CompositeTy)) {
SJW806a5d82020-07-15 12:51:38 -05004186 SPIRVID CstFFID = getSPIRVInt32Constant(0xFF);
David Neto22f144c2017-06-12 14:26:21 -04004187
SJW01901d92020-05-21 08:58:31 -05004188 SPIRVID ShiftAmountID = 0;
David Neto22f144c2017-06-12 14:26:21 -04004189 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4190 // Handle constant index.
SJW806a5d82020-07-15 12:51:38 -05004191 uint32_t Idx = static_cast<uint32_t>(CI->getZExtValue());
4192 ShiftAmountID = getSPIRVInt32Constant(Idx * 8);
David Neto22f144c2017-06-12 14:26:21 -04004193 } else {
4194 // Handle variable index.
SJWf93f5f32020-05-05 07:27:56 -05004195 SPIRVOperandVec TmpOps;
David Neto22f144c2017-06-12 14:26:21 -04004196
SJW806a5d82020-07-15 12:51:38 -05004197 TmpOps << Type::getInt32Ty(Context) << I.getOperand(2)
4198 << getSPIRVInt32Constant(8);
David Neto22f144c2017-06-12 14:26:21 -04004199
SJWf93f5f32020-05-05 07:27:56 -05004200 ShiftAmountID = addSPIRVInst(spv::OpIMul, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004201 }
4202
4203 //
4204 // Generate mask operations.
4205 //
4206
4207 // ShiftLeft mask according to index of insertelement.
SJWf93f5f32020-05-05 07:27:56 -05004208 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004209
SJW01901d92020-05-21 08:58:31 -05004210 Ops << CompositeTy << CstFFID << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004211
SJW01901d92020-05-21 08:58:31 -05004212 SPIRVID MaskID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004213
4214 // Inverse mask.
4215 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004216 Ops << CompositeTy << MaskID;
David Neto22f144c2017-06-12 14:26:21 -04004217
SJW01901d92020-05-21 08:58:31 -05004218 SPIRVID InvMaskID = addSPIRVInst(spv::OpNot, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004219
4220 // Apply mask.
4221 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004222 Ops << CompositeTy << I.getOperand(0) << InvMaskID;
David Neto22f144c2017-06-12 14:26:21 -04004223
SJW01901d92020-05-21 08:58:31 -05004224 SPIRVID OrgValID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004225
4226 // Create correct value according to index of insertelement.
4227 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004228 Ops << CompositeTy << I.getOperand(1) << ShiftAmountID;
David Neto22f144c2017-06-12 14:26:21 -04004229
SJW01901d92020-05-21 08:58:31 -05004230 SPIRVID InsertValID = addSPIRVInst(spv::OpShiftLeftLogical, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004231
4232 // Insert value to original value.
4233 Ops.clear();
SJW01901d92020-05-21 08:58:31 -05004234 Ops << CompositeTy << OrgValID << InsertValID;
David Neto22f144c2017-06-12 14:26:21 -04004235
SJWf93f5f32020-05-05 07:27:56 -05004236 RID = addSPIRVInst(spv::OpBitwiseOr, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004237 break;
4238 }
4239
SJWf93f5f32020-05-05 07:27:56 -05004240 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004241
James Priced26efea2018-06-09 23:28:32 +01004242 // Ops[0] = Result Type ID
SJW01901d92020-05-21 08:58:31 -05004243 Ops << I.getType();
David Neto22f144c2017-06-12 14:26:21 -04004244
4245 spv::Op Opcode = spv::OpCompositeInsert;
4246 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004247 const auto value = CI->getZExtValue();
4248 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004249 // Ops[1] = Object ID
4250 // Ops[2] = Composite ID
4251 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004252 Ops << I.getOperand(1) << I.getOperand(0) << static_cast<uint32_t>(value);
David Neto22f144c2017-06-12 14:26:21 -04004253 } else {
James Priced26efea2018-06-09 23:28:32 +01004254 // Ops[1] = Composite ID
4255 // Ops[2] = Object ID
4256 // Ops[3] ... Ops[n] = Indexes (Literal Number)
SJW01901d92020-05-21 08:58:31 -05004257 Ops << I.getOperand(0) << I.getOperand(1) << I.getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04004258 Opcode = spv::OpVectorInsertDynamic;
4259 }
4260
SJWf93f5f32020-05-05 07:27:56 -05004261 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004262 break;
4263 }
4264 case Instruction::ShuffleVector: {
4265 // Ops[0] = Result Type ID
4266 // Ops[1] = Vector 1 ID
4267 // Ops[2] = Vector 2 ID
4268 // Ops[3] ... Ops[n] = Components (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004269 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004270
SJW01901d92020-05-21 08:58:31 -05004271 Ops << I.getType() << I.getOperand(0) << I.getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004272
alan-bakerc9666712020-04-01 16:31:21 -04004273 auto shuffle = cast<ShuffleVectorInst>(&I);
4274 SmallVector<int, 4> mask;
4275 shuffle->getShuffleMask(mask);
4276 for (auto i : mask) {
4277 if (i == UndefMaskElem) {
4278 if (clspv::Option::HackUndef())
4279 // Use 0 instead of undef.
SJW01901d92020-05-21 08:58:31 -05004280 Ops << 0;
alan-bakerc9666712020-04-01 16:31:21 -04004281 else
4282 // Undef for shuffle in SPIR-V.
SJW01901d92020-05-21 08:58:31 -05004283 Ops << 0xffffffff;
David Neto22f144c2017-06-12 14:26:21 -04004284 } else {
SJW01901d92020-05-21 08:58:31 -05004285 Ops << i;
David Neto22f144c2017-06-12 14:26:21 -04004286 }
4287 }
4288
SJWf93f5f32020-05-05 07:27:56 -05004289 RID = addSPIRVInst(spv::OpVectorShuffle, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004290 break;
4291 }
4292 case Instruction::ICmp:
4293 case Instruction::FCmp: {
4294 CmpInst *CmpI = cast<CmpInst>(&I);
4295
David Netod4ca2e62017-07-06 18:47:35 -04004296 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004297 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004298 if (isa<PointerType>(ArgTy)) {
4299 CmpI->print(errs());
alan-baker21574d32020-01-29 16:00:31 -05004300 std::string name = I.getParent()->getParent()->getName().str();
David Netod4ca2e62017-07-06 18:47:35 -04004301 errs()
4302 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4303 << "in function " << name << "\n";
4304 llvm_unreachable("Pointer equality check is invalid");
4305 break;
4306 }
4307
David Neto257c3892018-04-11 13:19:45 -04004308 // Ops[0] = Result Type ID
4309 // Ops[1] = Operand 1 ID
4310 // Ops[2] = Operand 2 ID
SJWf93f5f32020-05-05 07:27:56 -05004311 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004312
SJW01901d92020-05-21 08:58:31 -05004313 Ops << CmpI->getType() << CmpI->getOperand(0) << CmpI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04004314
4315 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
SJWf93f5f32020-05-05 07:27:56 -05004316 RID = addSPIRVInst(Opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004317 break;
4318 }
4319 case Instruction::Br: {
SJW88ed5fe2020-05-11 12:40:57 -05004320 // Branch instruction is deferred because it needs label's ID.
4321 BasicBlock *BrBB = I.getParent();
4322 if (ContinueBlocks.count(BrBB) || MergeBlocks.count(BrBB)) {
4323 // Placeholder for Merge operation
4324 RID = addSPIRVPlaceholder(&I);
4325 }
4326 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004327 break;
4328 }
4329 case Instruction::Switch: {
4330 I.print(errs());
4331 llvm_unreachable("Unsupported instruction???");
4332 break;
4333 }
4334 case Instruction::IndirectBr: {
4335 I.print(errs());
4336 llvm_unreachable("Unsupported instruction???");
4337 break;
4338 }
4339 case Instruction::PHI: {
SJW88ed5fe2020-05-11 12:40:57 -05004340 // PHI instruction is deferred because it needs label's ID.
4341 RID = addSPIRVPlaceholder(&I);
David Neto22f144c2017-06-12 14:26:21 -04004342 break;
4343 }
4344 case Instruction::Alloca: {
4345 //
4346 // Generate OpVariable.
4347 //
4348 // Ops[0] : Result Type ID
4349 // Ops[1] : Storage Class
SJWf93f5f32020-05-05 07:27:56 -05004350 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004351
SJW01901d92020-05-21 08:58:31 -05004352 Ops << I.getType() << spv::StorageClassFunction;
David Neto22f144c2017-06-12 14:26:21 -04004353
SJWf93f5f32020-05-05 07:27:56 -05004354 RID = addSPIRVInst(spv::OpVariable, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004355 break;
4356 }
4357 case Instruction::Load: {
4358 LoadInst *LD = cast<LoadInst>(&I);
4359 //
4360 // Generate OpLoad.
4361 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004362
alan-baker5b86ed72019-02-15 08:26:50 -05004363 if (LD->getType()->isPointerTy()) {
4364 // Loading a pointer requires variable pointers.
4365 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4366 }
David Neto22f144c2017-06-12 14:26:21 -04004367
SJW01901d92020-05-21 08:58:31 -05004368 SPIRVID PointerID = getSPIRVValue(LD->getPointerOperand());
David Netoa60b00b2017-09-15 16:34:09 -04004369 // This is a hack to work around what looks like a driver bug.
4370 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004371 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4372 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004373 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004374 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004375 // Generate a bitwise-and of the original value with itself.
4376 // We should have been able to get away with just an OpCopyObject,
4377 // but we need something more complex to get past certain driver bugs.
4378 // This is ridiculous, but necessary.
4379 // TODO(dneto): Revisit this once drivers fix their bugs.
4380
SJWf93f5f32020-05-05 07:27:56 -05004381 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004382 Ops << LD->getType() << WorkgroupSizeValueID << WorkgroupSizeValueID;
David Neto0a2f98d2017-09-15 19:38:40 -04004383
SJWf93f5f32020-05-05 07:27:56 -05004384 RID = addSPIRVInst(spv::OpBitwiseAnd, Ops);
David Netoa60b00b2017-09-15 16:34:09 -04004385 break;
4386 }
4387
4388 // This is the normal path. Generate a load.
4389
David Neto22f144c2017-06-12 14:26:21 -04004390 // Ops[0] = Result Type ID
4391 // Ops[1] = Pointer ID
4392 // Ops[2] ... Ops[n] = Optional Memory Access
4393 //
4394 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004395
SJWf93f5f32020-05-05 07:27:56 -05004396 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004397 Ops << LD->getType() << LD->getPointerOperand();
David Neto22f144c2017-06-12 14:26:21 -04004398
SJWf93f5f32020-05-05 07:27:56 -05004399 RID = addSPIRVInst(spv::OpLoad, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004400 break;
4401 }
4402 case Instruction::Store: {
4403 StoreInst *ST = cast<StoreInst>(&I);
4404 //
4405 // Generate OpStore.
4406 //
4407
alan-baker5b86ed72019-02-15 08:26:50 -05004408 if (ST->getValueOperand()->getType()->isPointerTy()) {
4409 // Storing a pointer requires variable pointers.
4410 setVariablePointersCapabilities(
4411 ST->getValueOperand()->getType()->getPointerAddressSpace());
4412 }
4413
David Neto22f144c2017-06-12 14:26:21 -04004414 // Ops[0] = Pointer ID
4415 // Ops[1] = Object ID
4416 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4417 //
4418 // TODO: Do we need to implement Optional Memory Access???
SJWf93f5f32020-05-05 07:27:56 -05004419 SPIRVOperandVec Ops;
SJW01901d92020-05-21 08:58:31 -05004420 Ops << ST->getPointerOperand() << ST->getValueOperand();
David Neto22f144c2017-06-12 14:26:21 -04004421
SJWf93f5f32020-05-05 07:27:56 -05004422 RID = addSPIRVInst(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004423 break;
4424 }
4425 case Instruction::AtomicCmpXchg: {
4426 I.print(errs());
4427 llvm_unreachable("Unsupported instruction???");
4428 break;
4429 }
4430 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004431 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4432
4433 spv::Op opcode;
4434
4435 switch (AtomicRMW->getOperation()) {
4436 default:
4437 I.print(errs());
4438 llvm_unreachable("Unsupported instruction???");
4439 case llvm::AtomicRMWInst::Add:
4440 opcode = spv::OpAtomicIAdd;
4441 break;
4442 case llvm::AtomicRMWInst::Sub:
4443 opcode = spv::OpAtomicISub;
4444 break;
4445 case llvm::AtomicRMWInst::Xchg:
4446 opcode = spv::OpAtomicExchange;
4447 break;
4448 case llvm::AtomicRMWInst::Min:
4449 opcode = spv::OpAtomicSMin;
4450 break;
4451 case llvm::AtomicRMWInst::Max:
4452 opcode = spv::OpAtomicSMax;
4453 break;
4454 case llvm::AtomicRMWInst::UMin:
4455 opcode = spv::OpAtomicUMin;
4456 break;
4457 case llvm::AtomicRMWInst::UMax:
4458 opcode = spv::OpAtomicUMax;
4459 break;
4460 case llvm::AtomicRMWInst::And:
4461 opcode = spv::OpAtomicAnd;
4462 break;
4463 case llvm::AtomicRMWInst::Or:
4464 opcode = spv::OpAtomicOr;
4465 break;
4466 case llvm::AtomicRMWInst::Xor:
4467 opcode = spv::OpAtomicXor;
4468 break;
4469 }
4470
4471 //
4472 // Generate OpAtomic*.
4473 //
SJWf93f5f32020-05-05 07:27:56 -05004474 SPIRVOperandVec Ops;
Neil Henning39672102017-09-29 14:33:13 +01004475
SJW01901d92020-05-21 08:58:31 -05004476 Ops << I.getType() << AtomicRMW->getPointerOperand();
Neil Henning39672102017-09-29 14:33:13 +01004477
SJW806a5d82020-07-15 12:51:38 -05004478 const auto ConstantScopeDevice = getSPIRVInt32Constant(spv::ScopeDevice);
SJW01901d92020-05-21 08:58:31 -05004479 Ops << ConstantScopeDevice;
Neil Henning39672102017-09-29 14:33:13 +01004480
SJW806a5d82020-07-15 12:51:38 -05004481 const auto ConstantMemorySemantics =
4482 getSPIRVInt32Constant(spv::MemorySemanticsUniformMemoryMask |
4483 spv::MemorySemanticsSequentiallyConsistentMask);
SJW01901d92020-05-21 08:58:31 -05004484 Ops << ConstantMemorySemantics << AtomicRMW->getValOperand();
Neil Henning39672102017-09-29 14:33:13 +01004485
SJWf93f5f32020-05-05 07:27:56 -05004486 RID = addSPIRVInst(opcode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004487 break;
4488 }
4489 case Instruction::Fence: {
4490 I.print(errs());
4491 llvm_unreachable("Unsupported instruction???");
4492 break;
4493 }
4494 case Instruction::Call: {
4495 CallInst *Call = dyn_cast<CallInst>(&I);
SJW806a5d82020-07-15 12:51:38 -05004496 RID = GenerateInstructionFromCall(Call);
David Neto22f144c2017-06-12 14:26:21 -04004497 break;
4498 }
4499 case Instruction::Ret: {
4500 unsigned NumOps = I.getNumOperands();
4501 if (NumOps == 0) {
4502 //
4503 // Generate OpReturn.
4504 //
SJWf93f5f32020-05-05 07:27:56 -05004505 RID = addSPIRVInst(spv::OpReturn);
David Neto22f144c2017-06-12 14:26:21 -04004506 } else {
4507 //
4508 // Generate OpReturnValue.
4509 //
4510
4511 // Ops[0] = Return Value ID
SJWf93f5f32020-05-05 07:27:56 -05004512 SPIRVOperandVec Ops;
David Neto257c3892018-04-11 13:19:45 -04004513
SJW01901d92020-05-21 08:58:31 -05004514 Ops << I.getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04004515
SJWf93f5f32020-05-05 07:27:56 -05004516 RID = addSPIRVInst(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004517 break;
4518 }
4519 break;
4520 }
4521 }
SJWf93f5f32020-05-05 07:27:56 -05004522
4523 // Register Instruction to ValueMap.
SJW01901d92020-05-21 08:58:31 -05004524 if (RID.isValid()) {
SJWf93f5f32020-05-05 07:27:56 -05004525 VMap[&I] = RID;
4526 }
David Neto22f144c2017-06-12 14:26:21 -04004527}
4528
4529void SPIRVProducerPass::GenerateFuncEpilogue() {
David Neto22f144c2017-06-12 14:26:21 -04004530 //
4531 // Generate OpFunctionEnd
4532 //
SJWf93f5f32020-05-05 07:27:56 -05004533 addSPIRVInst(spv::OpFunctionEnd);
David Neto22f144c2017-06-12 14:26:21 -04004534}
4535
4536bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004537 // Don't specialize <4 x i8> if i8 is generally supported.
4538 if (clspv::Option::Int8Support())
4539 return false;
4540
David Neto22f144c2017-06-12 14:26:21 -04004541 LLVMContext &Context = Ty->getContext();
James Pricecf53df42020-04-20 14:41:24 -04004542 if (auto VecTy = dyn_cast<VectorType>(Ty)) {
4543 if (VecTy->getElementType() == Type::getInt8Ty(Context) &&
alan-baker5a8c3be2020-09-09 13:44:26 -04004544 VecTy->getElementCount().getKnownMinValue() == 4) {
David Neto22f144c2017-06-12 14:26:21 -04004545 return true;
4546 }
4547 }
4548
4549 return false;
4550}
4551
4552void SPIRVProducerPass::HandleDeferredInstruction() {
David Neto22f144c2017-06-12 14:26:21 -04004553 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4554
SJW88ed5fe2020-05-11 12:40:57 -05004555 for (size_t i = 0; i < DeferredInsts.size(); ++i) {
4556 Value *Inst = DeferredInsts[i].first;
4557 SPIRVInstruction *Placeholder = DeferredInsts[i].second;
4558 SPIRVOperandVec Operands;
4559
4560 auto nextDeferred = [&i, &Inst, &DeferredInsts, &Placeholder]() {
4561 ++i;
4562 assert(DeferredInsts.size() > i);
4563 assert(Inst == DeferredInsts[i].first);
4564 Placeholder = DeferredInsts[i].second;
4565 };
David Neto22f144c2017-06-12 14:26:21 -04004566
4567 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
alan-baker06cad652019-12-03 17:56:47 -05004568 // Check whether this branch needs to be preceeded by merge instruction.
David Neto22f144c2017-06-12 14:26:21 -04004569 BasicBlock *BrBB = Br->getParent();
alan-baker06cad652019-12-03 17:56:47 -05004570 if (ContinueBlocks.count(BrBB)) {
David Neto22f144c2017-06-12 14:26:21 -04004571 //
4572 // Generate OpLoopMerge.
4573 //
4574 // Ops[0] = Merge Block ID
4575 // Ops[1] = Continue Target ID
4576 // Ops[2] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004577 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004578
SJW01901d92020-05-21 08:58:31 -05004579 Ops << MergeBlocks[BrBB] << ContinueBlocks[BrBB]
4580 << spv::LoopControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004581
SJW88ed5fe2020-05-11 12:40:57 -05004582 replaceSPIRVInst(Placeholder, spv::OpLoopMerge, Ops);
4583
4584 nextDeferred();
4585
alan-baker06cad652019-12-03 17:56:47 -05004586 } else if (MergeBlocks.count(BrBB)) {
4587 //
4588 // Generate OpSelectionMerge.
4589 //
4590 // Ops[0] = Merge Block ID
4591 // Ops[1] = Selection Control
SJWf93f5f32020-05-05 07:27:56 -05004592 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004593
alan-baker06cad652019-12-03 17:56:47 -05004594 auto MergeBB = MergeBlocks[BrBB];
SJW01901d92020-05-21 08:58:31 -05004595 Ops << MergeBB << spv::SelectionControlMaskNone;
David Neto22f144c2017-06-12 14:26:21 -04004596
SJW88ed5fe2020-05-11 12:40:57 -05004597 replaceSPIRVInst(Placeholder, spv::OpSelectionMerge, Ops);
4598
4599 nextDeferred();
David Neto22f144c2017-06-12 14:26:21 -04004600 }
4601
4602 if (Br->isConditional()) {
4603 //
4604 // Generate OpBranchConditional.
4605 //
4606 // Ops[0] = Condition ID
4607 // Ops[1] = True Label ID
4608 // Ops[2] = False Label ID
4609 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004610 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004611
SJW01901d92020-05-21 08:58:31 -05004612 Ops << Br->getCondition() << Br->getSuccessor(0) << Br->getSuccessor(1);
David Neto22f144c2017-06-12 14:26:21 -04004613
SJW88ed5fe2020-05-11 12:40:57 -05004614 replaceSPIRVInst(Placeholder, spv::OpBranchConditional, Ops);
4615
David Neto22f144c2017-06-12 14:26:21 -04004616 } else {
4617 //
4618 // Generate OpBranch.
4619 //
4620 // Ops[0] = Target Label ID
SJWf93f5f32020-05-05 07:27:56 -05004621 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004622
SJW01901d92020-05-21 08:58:31 -05004623 Ops << Br->getSuccessor(0);
David Neto22f144c2017-06-12 14:26:21 -04004624
SJW88ed5fe2020-05-11 12:40:57 -05004625 replaceSPIRVInst(Placeholder, spv::OpBranch, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004626 }
4627 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5ed87542020-03-23 11:05:22 -04004628 if (PHI->getType()->isPointerTy() && !IsSamplerType(PHI->getType()) &&
4629 !IsImageType(PHI->getType())) {
alan-baker5b86ed72019-02-15 08:26:50 -05004630 // OpPhi on pointers requires variable pointers.
4631 setVariablePointersCapabilities(
4632 PHI->getType()->getPointerAddressSpace());
4633 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
SJW01901d92020-05-21 08:58:31 -05004634 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004635 }
4636 }
4637
David Neto22f144c2017-06-12 14:26:21 -04004638 //
4639 // Generate OpPhi.
4640 //
4641 // Ops[0] = Result Type ID
4642 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
SJWf93f5f32020-05-05 07:27:56 -05004643 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004644
SJW01901d92020-05-21 08:58:31 -05004645 Ops << PHI->getType();
David Neto22f144c2017-06-12 14:26:21 -04004646
SJW88ed5fe2020-05-11 12:40:57 -05004647 for (unsigned j = 0; j < PHI->getNumIncomingValues(); j++) {
SJW01901d92020-05-21 08:58:31 -05004648 Ops << PHI->getIncomingValue(j) << PHI->getIncomingBlock(j);
David Neto22f144c2017-06-12 14:26:21 -04004649 }
4650
SJW88ed5fe2020-05-11 12:40:57 -05004651 replaceSPIRVInst(Placeholder, spv::OpPhi, Ops);
4652
David Neto22f144c2017-06-12 14:26:21 -04004653 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4654 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004655 auto callee_name = Callee->getName();
David Neto22f144c2017-06-12 14:26:21 -04004656
SJW61531372020-06-09 07:31:08 -05004657 if (Builtins::Lookup(Callee) == Builtins::kClspvCompositeConstruct) {
David Netoab03f432017-11-03 17:00:44 -04004658 // Generate an OpCompositeConstruct
SJWf93f5f32020-05-05 07:27:56 -05004659 SPIRVOperandVec Ops;
David Netoab03f432017-11-03 17:00:44 -04004660
4661 // The result type.
SJW01901d92020-05-21 08:58:31 -05004662 Ops << Call->getType();
David Netoab03f432017-11-03 17:00:44 -04004663
4664 for (Use &use : Call->arg_operands()) {
SJW01901d92020-05-21 08:58:31 -05004665 Ops << use.get();
David Netoab03f432017-11-03 17:00:44 -04004666 }
4667
SJW88ed5fe2020-05-11 12:40:57 -05004668 replaceSPIRVInst(Placeholder, spv::OpCompositeConstruct, Ops);
David Netoab03f432017-11-03 17:00:44 -04004669
David Neto22f144c2017-06-12 14:26:21 -04004670 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004671 if (Call->getType()->isPointerTy()) {
4672 // Functions returning pointers require variable pointers.
4673 setVariablePointersCapabilities(
4674 Call->getType()->getPointerAddressSpace());
4675 }
4676
David Neto22f144c2017-06-12 14:26:21 -04004677 //
4678 // Generate OpFunctionCall.
4679 //
4680
4681 // Ops[0] = Result Type ID
4682 // Ops[1] = Callee Function ID
4683 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
SJWf93f5f32020-05-05 07:27:56 -05004684 SPIRVOperandVec Ops;
David Neto22f144c2017-06-12 14:26:21 -04004685
SJW01901d92020-05-21 08:58:31 -05004686 Ops << Call->getType();
David Neto22f144c2017-06-12 14:26:21 -04004687
SJW01901d92020-05-21 08:58:31 -05004688 SPIRVID CalleeID = getSPIRVValue(Callee);
SJW806a5d82020-07-15 12:51:38 -05004689 if (!CalleeID.isValid()) {
David Neto43568eb2017-10-13 18:25:25 -04004690 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004691 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004692 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4693 // causes an infinite loop. Instead, go ahead and generate
4694 // the bad function call. A validator will catch the 0-Id.
4695 // llvm_unreachable("Can't translate function call");
4696 }
David Neto22f144c2017-06-12 14:26:21 -04004697
SJW01901d92020-05-21 08:58:31 -05004698 Ops << CalleeID;
David Neto22f144c2017-06-12 14:26:21 -04004699
David Neto22f144c2017-06-12 14:26:21 -04004700 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
SJW88ed5fe2020-05-11 12:40:57 -05004701 for (unsigned j = 0; j < CalleeFTy->getNumParams(); j++) {
4702 auto *operand = Call->getOperand(j);
alan-bakerd4d50652019-12-03 17:17:15 -05004703 auto *operand_type = operand->getType();
4704 // Images and samplers can be passed as function parameters without
4705 // variable pointers.
4706 if (operand_type->isPointerTy() && !IsImageType(operand_type) &&
4707 !IsSamplerType(operand_type)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004708 auto sc =
4709 GetStorageClass(operand->getType()->getPointerAddressSpace());
4710 if (sc == spv::StorageClassStorageBuffer) {
4711 // Passing SSBO by reference requires variable pointers storage
4712 // buffer.
SJW01901d92020-05-21 08:58:31 -05004713 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05004714 } else if (sc == spv::StorageClassWorkgroup) {
4715 // Workgroup references require variable pointers if they are not
4716 // memory object declarations.
4717 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4718 // Workgroup accessor represents a variable reference.
SJW61531372020-06-09 07:31:08 -05004719 if (Builtins::Lookup(operand_call->getCalledFunction()) !=
4720 Builtins::kClspvLocal)
SJW01901d92020-05-21 08:58:31 -05004721 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004722 } else {
4723 // Arguments are function parameters.
4724 if (!isa<Argument>(operand))
SJW01901d92020-05-21 08:58:31 -05004725 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05004726 }
4727 }
4728 }
SJW01901d92020-05-21 08:58:31 -05004729 Ops << operand;
David Neto22f144c2017-06-12 14:26:21 -04004730 }
4731
SJW88ed5fe2020-05-11 12:40:57 -05004732 replaceSPIRVInst(Placeholder, spv::OpFunctionCall, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004733 }
4734 }
4735 }
4736}
4737
SJW77b87ad2020-04-21 14:37:52 -05004738void SPIRVProducerPass::HandleDeferredDecorations() {
4739 const auto &DL = module->getDataLayout();
alan-baker5a8c3be2020-09-09 13:44:26 -04004740 if (getTypesNeedingArrayStride().empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04004741 return;
David Netoc6f3ab22018-04-06 18:02:31 -04004742 }
David Neto1a1a0582017-07-07 12:01:44 -04004743
David Netoc6f3ab22018-04-06 18:02:31 -04004744 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
4745 // instructions we generated earlier.
alan-bakerc3fd07f2020-10-22 09:48:49 -04004746 DenseSet<uint32_t> seen;
David Neto85082642018-03-24 06:55:20 -07004747 for (auto *type : getTypesNeedingArrayStride()) {
alan-bakerc3fd07f2020-10-22 09:48:49 -04004748 auto id = getSPIRVType(type);
4749 if (!seen.insert(id.get()).second)
4750 continue;
4751
David Neto85082642018-03-24 06:55:20 -07004752 Type *elemTy = nullptr;
4753 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
4754 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004755 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
alan-baker8eb435a2020-04-08 00:42:06 -04004756 elemTy = arrayTy->getElementType();
4757 } else if (auto *vecTy = dyn_cast<VectorType>(type)) {
4758 elemTy = vecTy->getElementType();
David Neto85082642018-03-24 06:55:20 -07004759 } else {
4760 errs() << "Unhandled strided type " << *type << "\n";
4761 llvm_unreachable("Unhandled strided type");
4762 }
David Neto1a1a0582017-07-07 12:01:44 -04004763
4764 // Ops[0] = Target ID
4765 // Ops[1] = Decoration (ArrayStride)
4766 // Ops[2] = Stride number (Literal Number)
SJWf93f5f32020-05-05 07:27:56 -05004767 SPIRVOperandVec Ops;
David Neto1a1a0582017-07-07 12:01:44 -04004768
David Neto85082642018-03-24 06:55:20 -07004769 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04004770 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04004771
alan-bakerc3fd07f2020-10-22 09:48:49 -04004772 Ops << id << spv::DecorationArrayStride << stride;
David Neto1a1a0582017-07-07 12:01:44 -04004773
SJWf93f5f32020-05-05 07:27:56 -05004774 addSPIRVInst<kAnnotations>(spv::OpDecorate, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04004775 }
David Neto1a1a0582017-07-07 12:01:44 -04004776}
4777
SJW61531372020-06-09 07:31:08 -05004778glsl::ExtInst
4779SPIRVProducerPass::getExtInstEnum(const Builtins::FunctionInfo &func_info) {
SJW61531372020-06-09 07:31:08 -05004780 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004781 case Builtins::kClamp: {
SJW61531372020-06-09 07:31:08 -05004782 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004783 if (param_type.type_id == Type::FloatTyID) {
4784 return glsl::ExtInst::ExtInstFClamp;
4785 }
4786 return param_type.is_signed ? glsl::ExtInst::ExtInstSClamp
4787 : glsl::ExtInst::ExtInstUClamp;
4788 }
4789 case Builtins::kMax: {
SJW61531372020-06-09 07:31:08 -05004790 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004791 if (param_type.type_id == Type::FloatTyID) {
4792 return glsl::ExtInst::ExtInstFMax;
4793 }
4794 return param_type.is_signed ? glsl::ExtInst::ExtInstSMax
4795 : glsl::ExtInst::ExtInstUMax;
4796 }
4797 case Builtins::kMin: {
SJW61531372020-06-09 07:31:08 -05004798 auto param_type = func_info.getParameter(0);
SJW2c317da2020-03-23 07:39:13 -05004799 if (param_type.type_id == Type::FloatTyID) {
4800 return glsl::ExtInst::ExtInstFMin;
4801 }
4802 return param_type.is_signed ? glsl::ExtInst::ExtInstSMin
4803 : glsl::ExtInst::ExtInstUMin;
4804 }
4805 case Builtins::kAbs:
4806 return glsl::ExtInst::ExtInstSAbs;
4807 case Builtins::kFmax:
Marco Antognini55d51862020-07-21 17:50:07 +01004808 return glsl::ExtInst::ExtInstNMax;
SJW2c317da2020-03-23 07:39:13 -05004809 case Builtins::kFmin:
Marco Antognini55d51862020-07-21 17:50:07 +01004810 return glsl::ExtInst::ExtInstNMin;
SJW2c317da2020-03-23 07:39:13 -05004811 case Builtins::kDegrees:
4812 return glsl::ExtInst::ExtInstDegrees;
4813 case Builtins::kRadians:
4814 return glsl::ExtInst::ExtInstRadians;
4815 case Builtins::kMix:
4816 return glsl::ExtInst::ExtInstFMix;
4817 case Builtins::kAcos:
4818 case Builtins::kAcospi:
4819 return glsl::ExtInst::ExtInstAcos;
4820 case Builtins::kAcosh:
4821 return glsl::ExtInst::ExtInstAcosh;
4822 case Builtins::kAsin:
4823 case Builtins::kAsinpi:
4824 return glsl::ExtInst::ExtInstAsin;
4825 case Builtins::kAsinh:
4826 return glsl::ExtInst::ExtInstAsinh;
4827 case Builtins::kAtan:
4828 case Builtins::kAtanpi:
4829 return glsl::ExtInst::ExtInstAtan;
4830 case Builtins::kAtanh:
4831 return glsl::ExtInst::ExtInstAtanh;
4832 case Builtins::kAtan2:
4833 case Builtins::kAtan2pi:
4834 return glsl::ExtInst::ExtInstAtan2;
4835 case Builtins::kCeil:
4836 return glsl::ExtInst::ExtInstCeil;
4837 case Builtins::kSin:
4838 case Builtins::kHalfSin:
4839 case Builtins::kNativeSin:
4840 return glsl::ExtInst::ExtInstSin;
4841 case Builtins::kSinh:
4842 return glsl::ExtInst::ExtInstSinh;
4843 case Builtins::kCos:
4844 case Builtins::kHalfCos:
4845 case Builtins::kNativeCos:
4846 return glsl::ExtInst::ExtInstCos;
4847 case Builtins::kCosh:
4848 return glsl::ExtInst::ExtInstCosh;
4849 case Builtins::kTan:
4850 case Builtins::kHalfTan:
4851 case Builtins::kNativeTan:
4852 return glsl::ExtInst::ExtInstTan;
4853 case Builtins::kTanh:
4854 return glsl::ExtInst::ExtInstTanh;
4855 case Builtins::kExp:
4856 case Builtins::kHalfExp:
4857 case Builtins::kNativeExp:
4858 return glsl::ExtInst::ExtInstExp;
4859 case Builtins::kExp2:
4860 case Builtins::kHalfExp2:
4861 case Builtins::kNativeExp2:
4862 return glsl::ExtInst::ExtInstExp2;
4863 case Builtins::kLog:
4864 case Builtins::kHalfLog:
4865 case Builtins::kNativeLog:
4866 return glsl::ExtInst::ExtInstLog;
4867 case Builtins::kLog2:
4868 case Builtins::kHalfLog2:
4869 case Builtins::kNativeLog2:
4870 return glsl::ExtInst::ExtInstLog2;
4871 case Builtins::kFabs:
4872 return glsl::ExtInst::ExtInstFAbs;
4873 case Builtins::kFma:
4874 return glsl::ExtInst::ExtInstFma;
4875 case Builtins::kFloor:
4876 return glsl::ExtInst::ExtInstFloor;
4877 case Builtins::kLdexp:
4878 return glsl::ExtInst::ExtInstLdexp;
4879 case Builtins::kPow:
4880 case Builtins::kPowr:
4881 case Builtins::kHalfPowr:
4882 case Builtins::kNativePowr:
4883 return glsl::ExtInst::ExtInstPow;
James Price38553362020-09-03 18:30:40 -04004884 case Builtins::kRint:
4885 return glsl::ExtInst::ExtInstRoundEven;
SJW2c317da2020-03-23 07:39:13 -05004886 case Builtins::kRound:
4887 return glsl::ExtInst::ExtInstRound;
4888 case Builtins::kSqrt:
4889 case Builtins::kHalfSqrt:
4890 case Builtins::kNativeSqrt:
4891 return glsl::ExtInst::ExtInstSqrt;
4892 case Builtins::kRsqrt:
4893 case Builtins::kHalfRsqrt:
4894 case Builtins::kNativeRsqrt:
4895 return glsl::ExtInst::ExtInstInverseSqrt;
4896 case Builtins::kTrunc:
4897 return glsl::ExtInst::ExtInstTrunc;
4898 case Builtins::kFrexp:
4899 return glsl::ExtInst::ExtInstFrexp;
SJW61531372020-06-09 07:31:08 -05004900 case Builtins::kClspvFract:
SJW2c317da2020-03-23 07:39:13 -05004901 case Builtins::kFract:
4902 return glsl::ExtInst::ExtInstFract;
4903 case Builtins::kSign:
4904 return glsl::ExtInst::ExtInstFSign;
4905 case Builtins::kLength:
4906 case Builtins::kFastLength:
4907 return glsl::ExtInst::ExtInstLength;
4908 case Builtins::kDistance:
4909 case Builtins::kFastDistance:
4910 return glsl::ExtInst::ExtInstDistance;
4911 case Builtins::kStep:
4912 return glsl::ExtInst::ExtInstStep;
4913 case Builtins::kSmoothstep:
4914 return glsl::ExtInst::ExtInstSmoothStep;
4915 case Builtins::kCross:
4916 return glsl::ExtInst::ExtInstCross;
4917 case Builtins::kNormalize:
4918 case Builtins::kFastNormalize:
4919 return glsl::ExtInst::ExtInstNormalize;
SJW61531372020-06-09 07:31:08 -05004920 case Builtins::kSpirvPack:
4921 return glsl::ExtInst::ExtInstPackHalf2x16;
4922 case Builtins::kSpirvUnpack:
4923 return glsl::ExtInst::ExtInstUnpackHalf2x16;
SJW2c317da2020-03-23 07:39:13 -05004924 default:
4925 break;
4926 }
4927
SJW61531372020-06-09 07:31:08 -05004928 if (func_info.getName().find("llvm.fmuladd.") == 0) {
4929 return glsl::ExtInst::ExtInstFma;
4930 }
4931 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004932}
4933
SJW61531372020-06-09 07:31:08 -05004934glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(
4935 const Builtins::FunctionInfo &func_info) {
4936 switch (func_info.getType()) {
SJW2c317da2020-03-23 07:39:13 -05004937 case Builtins::kClz:
4938 return glsl::ExtInst::ExtInstFindUMsb;
4939 case Builtins::kAcospi:
4940 return glsl::ExtInst::ExtInstAcos;
4941 case Builtins::kAsinpi:
4942 return glsl::ExtInst::ExtInstAsin;
4943 case Builtins::kAtanpi:
4944 return glsl::ExtInst::ExtInstAtan;
4945 case Builtins::kAtan2pi:
4946 return glsl::ExtInst::ExtInstAtan2;
4947 default:
4948 break;
4949 }
4950 return kGlslExtInstBad;
David Neto3fbb4072017-10-16 11:28:14 -04004951}
4952
SJW61531372020-06-09 07:31:08 -05004953glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(
4954 const Builtins::FunctionInfo &func_info) {
4955 auto direct = getExtInstEnum(func_info);
David Neto3fbb4072017-10-16 11:28:14 -04004956 if (direct != kGlslExtInstBad)
4957 return direct;
SJW61531372020-06-09 07:31:08 -05004958 return getIndirectExtInstEnum(func_info);
David Neto22f144c2017-06-12 14:26:21 -04004959}
4960
David Neto22f144c2017-06-12 14:26:21 -04004961void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04004962 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04004963}
4964
SJW88ed5fe2020-05-11 12:40:57 -05004965void SPIRVProducerPass::WriteResultID(const SPIRVInstruction &Inst) {
SJW01901d92020-05-21 08:58:31 -05004966 WriteOneWord(Inst.getResultID().get());
David Neto22f144c2017-06-12 14:26:21 -04004967}
4968
SJW88ed5fe2020-05-11 12:40:57 -05004969void SPIRVProducerPass::WriteWordCountAndOpcode(const SPIRVInstruction &Inst) {
David Neto22f144c2017-06-12 14:26:21 -04004970 // High 16 bit : Word Count
4971 // Low 16 bit : Opcode
SJW88ed5fe2020-05-11 12:40:57 -05004972 uint32_t Word = Inst.getOpcode();
4973 const uint32_t count = Inst.getWordCount();
David Netoee2660d2018-06-28 16:31:29 -04004974 if (count > 65535) {
4975 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
4976 llvm_unreachable("Word count too high");
4977 }
SJW88ed5fe2020-05-11 12:40:57 -05004978 Word |= Inst.getWordCount() << 16;
David Neto22f144c2017-06-12 14:26:21 -04004979 WriteOneWord(Word);
4980}
4981
SJW88ed5fe2020-05-11 12:40:57 -05004982void SPIRVProducerPass::WriteOperand(const SPIRVOperand &Op) {
4983 SPIRVOperandType OpTy = Op.getType();
David Neto22f144c2017-06-12 14:26:21 -04004984 switch (OpTy) {
4985 default: {
4986 llvm_unreachable("Unsupported SPIRV Operand Type???");
4987 break;
4988 }
4989 case SPIRVOperandType::NUMBERID: {
SJW88ed5fe2020-05-11 12:40:57 -05004990 WriteOneWord(Op.getNumID());
David Neto22f144c2017-06-12 14:26:21 -04004991 break;
4992 }
4993 case SPIRVOperandType::LITERAL_STRING: {
SJW88ed5fe2020-05-11 12:40:57 -05004994 std::string Str = Op.getLiteralStr();
David Neto22f144c2017-06-12 14:26:21 -04004995 const char *Data = Str.c_str();
4996 size_t WordSize = Str.size() / 4;
4997 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
4998 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
4999 }
5000
5001 uint32_t Remainder = Str.size() % 4;
5002 uint32_t LastWord = 0;
5003 if (Remainder) {
5004 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5005 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5006 }
5007 }
5008
5009 WriteOneWord(LastWord);
5010 break;
5011 }
SJW88ed5fe2020-05-11 12:40:57 -05005012 case SPIRVOperandType::LITERAL_WORD: {
5013 WriteOneWord(Op.getLiteralNum()[0]);
5014 break;
5015 }
5016 case SPIRVOperandType::LITERAL_DWORD: {
5017 WriteOneWord(Op.getLiteralNum()[0]);
5018 WriteOneWord(Op.getLiteralNum()[1]);
David Neto22f144c2017-06-12 14:26:21 -04005019 break;
5020 }
5021 }
5022}
5023
5024void SPIRVProducerPass::WriteSPIRVBinary() {
SJW69939d52020-04-16 07:29:07 -05005025 for (int i = 0; i < kSectionCount; ++i) {
5026 WriteSPIRVBinary(SPIRVSections[i]);
5027 }
5028}
5029
5030void SPIRVProducerPass::WriteSPIRVBinary(SPIRVInstructionList &SPIRVInstList) {
SJW88ed5fe2020-05-11 12:40:57 -05005031 for (const auto &Inst : SPIRVInstList) {
5032 const auto &Ops = Inst.getOperands();
5033 spv::Op Opcode = static_cast<spv::Op>(Inst.getOpcode());
David Neto22f144c2017-06-12 14:26:21 -04005034
5035 switch (Opcode) {
5036 default: {
David Neto5c22a252018-03-15 16:07:41 -04005037 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005038 llvm_unreachable("Unsupported SPIRV instruction");
5039 break;
5040 }
Marco Antognini68e5c512020-09-09 16:08:57 +01005041 case spv::OpUnreachable:
David Neto22f144c2017-06-12 14:26:21 -04005042 case spv::OpCapability:
5043 case spv::OpExtension:
5044 case spv::OpMemoryModel:
5045 case spv::OpEntryPoint:
5046 case spv::OpExecutionMode:
5047 case spv::OpSource:
5048 case spv::OpDecorate:
5049 case spv::OpMemberDecorate:
5050 case spv::OpBranch:
5051 case spv::OpBranchConditional:
5052 case spv::OpSelectionMerge:
5053 case spv::OpLoopMerge:
5054 case spv::OpStore:
5055 case spv::OpImageWrite:
5056 case spv::OpReturnValue:
5057 case spv::OpControlBarrier:
5058 case spv::OpMemoryBarrier:
5059 case spv::OpReturn:
5060 case spv::OpFunctionEnd:
5061 case spv::OpCopyMemory: {
5062 WriteWordCountAndOpcode(Inst);
5063 for (uint32_t i = 0; i < Ops.size(); i++) {
5064 WriteOperand(Ops[i]);
5065 }
5066 break;
5067 }
5068 case spv::OpTypeBool:
5069 case spv::OpTypeVoid:
5070 case spv::OpTypeSampler:
5071 case spv::OpLabel:
5072 case spv::OpExtInstImport:
5073 case spv::OpTypePointer:
5074 case spv::OpTypeRuntimeArray:
5075 case spv::OpTypeStruct:
5076 case spv::OpTypeImage:
5077 case spv::OpTypeSampledImage:
5078 case spv::OpTypeInt:
5079 case spv::OpTypeFloat:
5080 case spv::OpTypeArray:
5081 case spv::OpTypeVector:
alan-baker86ce19c2020-08-05 13:09:19 -04005082 case spv::OpTypeFunction:
5083 case spv::OpString: {
David Neto22f144c2017-06-12 14:26:21 -04005084 WriteWordCountAndOpcode(Inst);
5085 WriteResultID(Inst);
5086 for (uint32_t i = 0; i < Ops.size(); i++) {
5087 WriteOperand(Ops[i]);
5088 }
5089 break;
5090 }
5091 case spv::OpFunction:
5092 case spv::OpFunctionParameter:
5093 case spv::OpAccessChain:
5094 case spv::OpPtrAccessChain:
5095 case spv::OpInBoundsAccessChain:
5096 case spv::OpUConvert:
5097 case spv::OpSConvert:
5098 case spv::OpConvertFToU:
5099 case spv::OpConvertFToS:
5100 case spv::OpConvertUToF:
5101 case spv::OpConvertSToF:
5102 case spv::OpFConvert:
5103 case spv::OpConvertPtrToU:
5104 case spv::OpConvertUToPtr:
5105 case spv::OpBitcast:
alan-bakerc9c55ae2019-12-02 16:01:27 -05005106 case spv::OpFNegate:
David Neto22f144c2017-06-12 14:26:21 -04005107 case spv::OpIAdd:
alan-bakera52b7312020-10-26 08:58:51 -04005108 case spv::OpIAddCarry:
David Neto22f144c2017-06-12 14:26:21 -04005109 case spv::OpFAdd:
5110 case spv::OpISub:
5111 case spv::OpFSub:
5112 case spv::OpIMul:
5113 case spv::OpFMul:
5114 case spv::OpUDiv:
5115 case spv::OpSDiv:
5116 case spv::OpFDiv:
5117 case spv::OpUMod:
5118 case spv::OpSRem:
5119 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005120 case spv::OpUMulExtended:
5121 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005122 case spv::OpBitwiseOr:
5123 case spv::OpBitwiseXor:
5124 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005125 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005126 case spv::OpShiftLeftLogical:
5127 case spv::OpShiftRightLogical:
5128 case spv::OpShiftRightArithmetic:
5129 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005130 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005131 case spv::OpCompositeExtract:
5132 case spv::OpVectorExtractDynamic:
5133 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005134 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005135 case spv::OpVectorInsertDynamic:
5136 case spv::OpVectorShuffle:
5137 case spv::OpIEqual:
5138 case spv::OpINotEqual:
5139 case spv::OpUGreaterThan:
5140 case spv::OpUGreaterThanEqual:
5141 case spv::OpULessThan:
5142 case spv::OpULessThanEqual:
5143 case spv::OpSGreaterThan:
5144 case spv::OpSGreaterThanEqual:
5145 case spv::OpSLessThan:
5146 case spv::OpSLessThanEqual:
5147 case spv::OpFOrdEqual:
5148 case spv::OpFOrdGreaterThan:
5149 case spv::OpFOrdGreaterThanEqual:
5150 case spv::OpFOrdLessThan:
5151 case spv::OpFOrdLessThanEqual:
5152 case spv::OpFOrdNotEqual:
5153 case spv::OpFUnordEqual:
5154 case spv::OpFUnordGreaterThan:
5155 case spv::OpFUnordGreaterThanEqual:
5156 case spv::OpFUnordLessThan:
5157 case spv::OpFUnordLessThanEqual:
5158 case spv::OpFUnordNotEqual:
5159 case spv::OpExtInst:
5160 case spv::OpIsInf:
5161 case spv::OpIsNan:
5162 case spv::OpAny:
5163 case spv::OpAll:
5164 case spv::OpUndef:
5165 case spv::OpConstantNull:
5166 case spv::OpLogicalOr:
5167 case spv::OpLogicalAnd:
5168 case spv::OpLogicalNot:
5169 case spv::OpLogicalNotEqual:
5170 case spv::OpConstantComposite:
5171 case spv::OpSpecConstantComposite:
5172 case spv::OpConstantTrue:
5173 case spv::OpConstantFalse:
5174 case spv::OpConstant:
5175 case spv::OpSpecConstant:
5176 case spv::OpVariable:
5177 case spv::OpFunctionCall:
5178 case spv::OpSampledImage:
alan-baker75090e42020-02-20 11:21:04 -05005179 case spv::OpImageFetch:
alan-bakerf6bc8252020-09-23 14:58:55 -04005180 case spv::OpImageRead:
David Neto22f144c2017-06-12 14:26:21 -04005181 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005182 case spv::OpImageQuerySize:
alan-bakerce179f12019-12-06 19:02:22 -05005183 case spv::OpImageQuerySizeLod:
David Neto22f144c2017-06-12 14:26:21 -04005184 case spv::OpSelect:
5185 case spv::OpPhi:
5186 case spv::OpLoad:
5187 case spv::OpAtomicIAdd:
5188 case spv::OpAtomicISub:
5189 case spv::OpAtomicExchange:
5190 case spv::OpAtomicIIncrement:
5191 case spv::OpAtomicIDecrement:
5192 case spv::OpAtomicCompareExchange:
5193 case spv::OpAtomicUMin:
5194 case spv::OpAtomicSMin:
5195 case spv::OpAtomicUMax:
5196 case spv::OpAtomicSMax:
5197 case spv::OpAtomicAnd:
5198 case spv::OpAtomicOr:
5199 case spv::OpAtomicXor:
SJW806a5d82020-07-15 12:51:38 -05005200 case spv::OpDot:
5201 case spv::OpGroupNonUniformAll:
5202 case spv::OpGroupNonUniformAny:
5203 case spv::OpGroupNonUniformBroadcast:
5204 case spv::OpGroupNonUniformIAdd:
5205 case spv::OpGroupNonUniformFAdd:
5206 case spv::OpGroupNonUniformSMin:
5207 case spv::OpGroupNonUniformUMin:
5208 case spv::OpGroupNonUniformFMin:
5209 case spv::OpGroupNonUniformSMax:
5210 case spv::OpGroupNonUniformUMax:
5211 case spv::OpGroupNonUniformFMax: {
David Neto22f144c2017-06-12 14:26:21 -04005212 WriteWordCountAndOpcode(Inst);
5213 WriteOperand(Ops[0]);
5214 WriteResultID(Inst);
5215 for (uint32_t i = 1; i < Ops.size(); i++) {
5216 WriteOperand(Ops[i]);
5217 }
5218 break;
5219 }
5220 }
5221 }
5222}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005223
alan-bakerb6b09dc2018-11-08 16:59:28 -05005224bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005225 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005226 case Type::HalfTyID:
5227 case Type::FloatTyID:
5228 case Type::DoubleTyID:
5229 case Type::IntegerTyID:
James Price59a1c752020-04-23 23:06:16 -04005230 case Type::FixedVectorTyID:
alan-bakerb6b09dc2018-11-08 16:59:28 -05005231 return true;
5232 case Type::PointerTyID: {
5233 const PointerType *pointer_type = cast<PointerType>(type);
5234 if (pointer_type->getPointerAddressSpace() !=
5235 AddressSpace::UniformConstant) {
5236 auto pointee_type = pointer_type->getPointerElementType();
5237 if (pointee_type->isStructTy() &&
5238 cast<StructType>(pointee_type)->isOpaque()) {
5239 // Images and samplers are not nullable.
5240 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005241 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005242 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005243 return true;
5244 }
5245 case Type::ArrayTyID:
alan-baker8eb435a2020-04-08 00:42:06 -04005246 return IsTypeNullable(type->getArrayElementType());
alan-bakerb6b09dc2018-11-08 16:59:28 -05005247 case Type::StructTyID: {
5248 const StructType *struct_type = cast<StructType>(type);
5249 // Images and samplers are not nullable.
5250 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005251 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005252 for (const auto element : struct_type->elements()) {
5253 if (!IsTypeNullable(element))
5254 return false;
5255 }
5256 return true;
5257 }
5258 default:
5259 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005260 }
5261}
Alan Bakerfcda9482018-10-02 17:09:59 -04005262
SJW77b87ad2020-04-21 14:37:52 -05005263void SPIRVProducerPass::PopulateUBOTypeMaps() {
Alan Bakerfcda9482018-10-02 17:09:59 -04005264 if (auto *offsets_md =
SJW77b87ad2020-04-21 14:37:52 -05005265 module->getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005266 // Metdata is stored as key-value pair operands. The first element of each
5267 // operand is the type and the second is a vector of offsets.
5268 for (const auto *operand : offsets_md->operands()) {
5269 const auto *pair = cast<MDTuple>(operand);
5270 auto *type =
5271 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5272 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5273 std::vector<uint32_t> offsets;
5274 for (const Metadata *offset_md : offset_vector->operands()) {
5275 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005276 offsets.push_back(static_cast<uint32_t>(
5277 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005278 }
5279 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5280 }
5281 }
5282
5283 if (auto *sizes_md =
SJW77b87ad2020-04-21 14:37:52 -05005284 module->getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
Alan Bakerfcda9482018-10-02 17:09:59 -04005285 // Metadata is stored as key-value pair operands. The first element of each
5286 // operand is the type and the second is a triple of sizes: type size in
5287 // bits, store size and alloc size.
5288 for (const auto *operand : sizes_md->operands()) {
5289 const auto *pair = cast<MDTuple>(operand);
5290 auto *type =
5291 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5292 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5293 uint64_t type_size_in_bits =
5294 cast<ConstantInt>(
5295 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5296 ->getZExtValue();
5297 uint64_t type_store_size =
5298 cast<ConstantInt>(
5299 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5300 ->getZExtValue();
5301 uint64_t type_alloc_size =
5302 cast<ConstantInt>(
5303 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5304 ->getZExtValue();
5305 RemappedUBOTypeSizes.insert(std::make_pair(
5306 type, std::make_tuple(type_size_in_bits, type_store_size,
5307 type_alloc_size)));
5308 }
5309 }
5310}
5311
5312uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5313 const DataLayout &DL) {
5314 auto iter = RemappedUBOTypeSizes.find(type);
5315 if (iter != RemappedUBOTypeSizes.end()) {
5316 return std::get<0>(iter->second);
5317 }
5318
5319 return DL.getTypeSizeInBits(type);
5320}
5321
5322uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5323 auto iter = RemappedUBOTypeSizes.find(type);
5324 if (iter != RemappedUBOTypeSizes.end()) {
5325 return std::get<1>(iter->second);
5326 }
5327
5328 return DL.getTypeStoreSize(type);
5329}
5330
5331uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5332 auto iter = RemappedUBOTypeSizes.find(type);
5333 if (iter != RemappedUBOTypeSizes.end()) {
5334 return std::get<2>(iter->second);
5335 }
5336
5337 return DL.getTypeAllocSize(type);
5338}
alan-baker5b86ed72019-02-15 08:26:50 -05005339
Kévin Petitbbbda972020-03-03 19:16:31 +00005340uint32_t SPIRVProducerPass::GetExplicitLayoutStructMemberOffset(
5341 StructType *type, unsigned member, const DataLayout &DL) {
5342 const auto StructLayout = DL.getStructLayout(type);
5343 // Search for the correct offsets if this type was remapped.
5344 std::vector<uint32_t> *offsets = nullptr;
5345 auto iter = RemappedUBOTypeOffsets.find(type);
5346 if (iter != RemappedUBOTypeOffsets.end()) {
5347 offsets = &iter->second;
5348 }
5349 auto ByteOffset =
5350 static_cast<uint32_t>(StructLayout->getElementOffset(member));
5351 if (offsets) {
5352 ByteOffset = (*offsets)[member];
5353 }
5354
5355 return ByteOffset;
5356}
5357
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005358void SPIRVProducerPass::setVariablePointersCapabilities(
5359 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005360 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
SJW01901d92020-05-21 08:58:31 -05005361 setVariablePointersStorageBuffer();
alan-baker5b86ed72019-02-15 08:26:50 -05005362 } else {
SJW01901d92020-05-21 08:58:31 -05005363 setVariablePointers();
alan-baker5b86ed72019-02-15 08:26:50 -05005364 }
5365}
5366
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005367Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005368 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5369 return GetBasePointer(gep->getPointerOperand());
5370 }
5371
5372 // Conservatively return |v|.
5373 return v;
5374}
5375
5376bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5377 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5378 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
alan-baker7506abb2020-09-10 15:02:55 -04005379 const auto &lhs_func_info =
5380 Builtins::Lookup(lhs_call->getCalledFunction());
5381 const auto &rhs_func_info =
5382 Builtins::Lookup(rhs_call->getCalledFunction());
SJW61531372020-06-09 07:31:08 -05005383 if (lhs_func_info.getType() == Builtins::kClspvResource &&
5384 rhs_func_info.getType() == Builtins::kClspvResource) {
alan-baker5b86ed72019-02-15 08:26:50 -05005385 // For resource accessors, match descriptor set and binding.
5386 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5387 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5388 return true;
SJW61531372020-06-09 07:31:08 -05005389 } else if (lhs_func_info.getType() == Builtins::kClspvLocal &&
5390 rhs_func_info.getType() == Builtins::kClspvLocal) {
alan-baker5b86ed72019-02-15 08:26:50 -05005391 // For workgroup resources, match spec id.
5392 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5393 return true;
5394 }
5395 }
5396 }
5397
5398 return false;
5399}
5400
5401bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5402 assert(inst->getType()->isPointerTy());
5403 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5404 spv::StorageClassStorageBuffer);
5405 const bool hack_undef = clspv::Option::HackUndef();
5406 if (auto *select = dyn_cast<SelectInst>(inst)) {
5407 auto *true_base = GetBasePointer(select->getTrueValue());
5408 auto *false_base = GetBasePointer(select->getFalseValue());
5409
5410 if (true_base == false_base)
5411 return true;
5412
5413 // If either the true or false operand is a null, then we satisfy the same
5414 // object constraint.
5415 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5416 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5417 return true;
5418 }
5419
5420 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5421 if (false_cst->isNullValue() ||
5422 (hack_undef && isa<UndefValue>(false_base)))
5423 return true;
5424 }
5425
5426 if (sameResource(true_base, false_base))
5427 return true;
5428 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5429 Value *value = nullptr;
5430 bool ok = true;
5431 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5432 auto *base = GetBasePointer(phi->getIncomingValue(i));
5433 // Null values satisfy the constraint of selecting of selecting from the
5434 // same object.
5435 if (!value) {
5436 if (auto *cst = dyn_cast<Constant>(base)) {
5437 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5438 value = base;
5439 } else {
5440 value = base;
5441 }
5442 } else if (base != value) {
5443 if (auto *base_cst = dyn_cast<Constant>(base)) {
5444 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5445 continue;
5446 }
5447
5448 if (sameResource(value, base))
5449 continue;
5450
5451 // Values don't represent the same base.
5452 ok = false;
5453 }
5454 }
5455
5456 return ok;
5457 }
5458
5459 // Conservatively return false.
5460 return false;
5461}
alan-bakere9308012019-03-15 10:25:13 -04005462
5463bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5464 if (!Arg.getType()->isPointerTy() ||
5465 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5466 // Only SSBOs need to be annotated as coherent.
5467 return false;
5468 }
5469
5470 DenseSet<Value *> visited;
5471 std::vector<Value *> stack;
5472 for (auto *U : Arg.getParent()->users()) {
5473 if (auto *call = dyn_cast<CallInst>(U)) {
5474 stack.push_back(call->getOperand(Arg.getArgNo()));
5475 }
5476 }
5477
5478 while (!stack.empty()) {
5479 Value *v = stack.back();
5480 stack.pop_back();
5481
5482 if (!visited.insert(v).second)
5483 continue;
5484
5485 auto *resource_call = dyn_cast<CallInst>(v);
5486 if (resource_call &&
SJW61531372020-06-09 07:31:08 -05005487 Builtins::Lookup(resource_call->getCalledFunction()).getType() ==
5488 Builtins::kClspvResource) {
alan-bakere9308012019-03-15 10:25:13 -04005489 // If this is a resource accessor function, check if the coherent operand
5490 // is set.
5491 const auto coherent =
5492 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5493 ->getZExtValue());
5494 if (coherent == 1)
5495 return true;
5496 } else if (auto *arg = dyn_cast<Argument>(v)) {
5497 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005498 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005499 if (auto *call = dyn_cast<CallInst>(U)) {
5500 stack.push_back(call->getOperand(arg->getArgNo()));
5501 }
5502 }
5503 } else if (auto *user = dyn_cast<User>(v)) {
5504 // If this is a user, traverse all operands that could lead to resource
5505 // variables.
5506 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5507 Value *operand = user->getOperand(i);
5508 if (operand->getType()->isPointerTy() &&
5509 operand->getType()->getPointerAddressSpace() ==
5510 clspv::AddressSpace::Global) {
5511 stack.push_back(operand);
5512 }
5513 }
5514 }
5515 }
5516
5517 // No coherent resource variables encountered.
5518 return false;
5519}
alan-baker06cad652019-12-03 17:56:47 -05005520
SJW77b87ad2020-04-21 14:37:52 -05005521void SPIRVProducerPass::PopulateStructuredCFGMaps() {
alan-baker06cad652019-12-03 17:56:47 -05005522 // First, track loop merges and continues.
5523 DenseSet<BasicBlock *> LoopMergesAndContinues;
SJW77b87ad2020-04-21 14:37:52 -05005524 for (auto &F : *module) {
alan-baker06cad652019-12-03 17:56:47 -05005525 if (F.isDeclaration())
5526 continue;
5527
5528 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
5529 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
5530 std::deque<BasicBlock *> order;
5531 DenseSet<BasicBlock *> visited;
5532 clspv::ComputeStructuredOrder(&*F.begin(), &DT, LI, &order, &visited);
5533
5534 for (auto BB : order) {
5535 auto terminator = BB->getTerminator();
5536 auto branch = dyn_cast<BranchInst>(terminator);
5537 if (LI.isLoopHeader(BB)) {
5538 auto L = LI.getLoopFor(BB);
5539 BasicBlock *ContinueBB = nullptr;
5540 BasicBlock *MergeBB = nullptr;
5541
5542 MergeBB = L->getExitBlock();
5543 if (!MergeBB) {
5544 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5545 // has regions with single entry/exit. As a result, loop should not
5546 // have multiple exits.
5547 llvm_unreachable("Loop has multiple exits???");
5548 }
5549
5550 if (L->isLoopLatch(BB)) {
5551 ContinueBB = BB;
5552 } else {
5553 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5554 // block.
5555 BasicBlock *Header = L->getHeader();
5556 BasicBlock *Latch = L->getLoopLatch();
5557 for (auto *loop_block : L->blocks()) {
5558 if (loop_block == Header) {
5559 continue;
5560 }
5561
5562 // Check whether block dominates block with back-edge.
5563 // The loop latch is the single block with a back-edge. If it was
5564 // possible, StructurizeCFG made the loop conform to this
5565 // requirement, otherwise |Latch| is a nullptr.
5566 if (DT.dominates(loop_block, Latch)) {
5567 ContinueBB = loop_block;
5568 }
5569 }
5570
5571 if (!ContinueBB) {
5572 llvm_unreachable("Wrong continue block from loop");
5573 }
5574 }
5575
5576 // Record the continue and merge blocks.
5577 MergeBlocks[BB] = MergeBB;
5578 ContinueBlocks[BB] = ContinueBB;
5579 LoopMergesAndContinues.insert(MergeBB);
5580 LoopMergesAndContinues.insert(ContinueBB);
5581 } else if (branch && branch->isConditional()) {
5582 auto L = LI.getLoopFor(BB);
5583 bool HasBackedge = false;
5584 while (L && !HasBackedge) {
5585 if (L->isLoopLatch(BB)) {
5586 HasBackedge = true;
5587 }
5588 L = L->getParentLoop();
5589 }
5590
5591 if (!HasBackedge) {
5592 // Only need a merge if the branch doesn't include a loop break or
5593 // continue.
5594 auto true_bb = branch->getSuccessor(0);
5595 auto false_bb = branch->getSuccessor(1);
5596 if (!LoopMergesAndContinues.count(true_bb) &&
5597 !LoopMergesAndContinues.count(false_bb)) {
5598 // StructurizeCFG pass already manipulated CFG. Just use false block
5599 // of branch instruction as merge block.
5600 MergeBlocks[BB] = false_bb;
5601 }
5602 }
5603 }
5604 }
5605 }
5606}
alan-baker86ce19c2020-08-05 13:09:19 -04005607
5608SPIRVID SPIRVProducerPass::getReflectionImport() {
5609 if (!ReflectionID.isValid()) {
5610 addSPIRVInst<kExtensions>(spv::OpExtension, "SPV_KHR_non_semantic_info");
5611 ReflectionID = addSPIRVInst<kImports>(spv::OpExtInstImport,
5612 "NonSemantic.ClspvReflection.1");
5613 }
5614 return ReflectionID;
5615}
5616
5617void SPIRVProducerPass::GenerateReflection() {
5618 GenerateKernelReflection();
5619 GeneratePushConstantReflection();
5620 GenerateSpecConstantReflection();
5621}
5622
5623void SPIRVProducerPass::GeneratePushConstantReflection() {
5624 if (auto GV = module->getGlobalVariable(clspv::PushConstantsVariableName())) {
5625 auto const &DL = module->getDataLayout();
5626 auto MD = GV->getMetadata(clspv::PushConstantsMetadataName());
5627 auto STy = cast<StructType>(GV->getValueType());
5628
5629 for (unsigned i = 0; i < STy->getNumElements(); i++) {
5630 auto pc = static_cast<clspv::PushConstant>(
5631 mdconst::extract<ConstantInt>(MD->getOperand(i))->getZExtValue());
5632 if (pc == PushConstant::KernelArgument)
5633 continue;
5634
5635 auto memberType = STy->getElementType(i);
5636 auto offset = GetExplicitLayoutStructMemberOffset(STy, i, DL);
5637 unsigned previousOffset = 0;
5638 if (i > 0) {
5639 previousOffset = GetExplicitLayoutStructMemberOffset(STy, i - 1, DL);
5640 }
5641 auto size = static_cast<uint32_t>(GetTypeSizeInBits(memberType, DL)) / 8;
5642 assert(isValidExplicitLayout(*module, STy, i,
5643 spv::StorageClassPushConstant, offset,
5644 previousOffset));
5645
5646 reflection::ExtInst pc_inst = reflection::ExtInstMax;
5647 switch (pc) {
5648 case PushConstant::GlobalOffset:
5649 pc_inst = reflection::ExtInstPushConstantGlobalOffset;
5650 break;
5651 case PushConstant::EnqueuedLocalSize:
5652 pc_inst = reflection::ExtInstPushConstantEnqueuedLocalSize;
5653 break;
5654 case PushConstant::GlobalSize:
5655 pc_inst = reflection::ExtInstPushConstantGlobalSize;
5656 break;
5657 case PushConstant::RegionOffset:
5658 pc_inst = reflection::ExtInstPushConstantRegionOffset;
5659 break;
5660 case PushConstant::NumWorkgroups:
5661 pc_inst = reflection::ExtInstPushConstantNumWorkgroups;
5662 break;
5663 case PushConstant::RegionGroupOffset:
5664 pc_inst = reflection::ExtInstPushConstantRegionGroupOffset;
5665 break;
5666 default:
5667 llvm_unreachable("Unhandled push constant");
5668 break;
5669 }
5670
5671 auto import_id = getReflectionImport();
5672 SPIRVOperandVec Ops;
5673 Ops << getSPIRVType(Type::getVoidTy(module->getContext())) << import_id
5674 << pc_inst << getSPIRVInt32Constant(offset)
5675 << getSPIRVInt32Constant(size);
5676 addSPIRVInst(spv::OpExtInst, Ops);
5677 }
5678 }
5679}
5680
5681void SPIRVProducerPass::GenerateSpecConstantReflection() {
5682 const uint32_t kMax = std::numeric_limits<uint32_t>::max();
5683 uint32_t wgsize_id[3] = {kMax, kMax, kMax};
5684 uint32_t global_offset_id[3] = {kMax, kMax, kMax};
5685 uint32_t work_dim_id = kMax;
5686 for (auto pair : clspv::GetSpecConstants(module)) {
5687 auto kind = pair.first;
5688 auto id = pair.second;
5689
5690 // Local memory size is only used for kernel arguments.
5691 if (kind == SpecConstant::kLocalMemorySize)
5692 continue;
5693
5694 switch (kind) {
5695 case SpecConstant::kWorkgroupSizeX:
5696 wgsize_id[0] = id;
5697 break;
5698 case SpecConstant::kWorkgroupSizeY:
5699 wgsize_id[1] = id;
5700 break;
5701 case SpecConstant::kWorkgroupSizeZ:
5702 wgsize_id[2] = id;
5703 break;
5704 case SpecConstant::kGlobalOffsetX:
5705 global_offset_id[0] = id;
5706 break;
5707 case SpecConstant::kGlobalOffsetY:
5708 global_offset_id[1] = id;
5709 break;
5710 case SpecConstant::kGlobalOffsetZ:
5711 global_offset_id[2] = id;
5712 break;
5713 case SpecConstant::kWorkDim:
5714 work_dim_id = id;
5715 break;
5716 default:
5717 llvm_unreachable("Unhandled spec constant");
5718 }
5719 }
5720
5721 auto import_id = getReflectionImport();
5722 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5723 SPIRVOperandVec Ops;
5724 if (wgsize_id[0] != kMax) {
5725 assert(wgsize_id[1] != kMax);
5726 assert(wgsize_id[2] != kMax);
5727 Ops.clear();
5728 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkgroupSize
5729 << getSPIRVInt32Constant(wgsize_id[0])
5730 << getSPIRVInt32Constant(wgsize_id[1])
5731 << getSPIRVInt32Constant(wgsize_id[2]);
5732 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5733 }
5734 if (global_offset_id[0] != kMax) {
5735 assert(global_offset_id[1] != kMax);
5736 assert(global_offset_id[2] != kMax);
5737 Ops.clear();
5738 Ops << void_id << import_id << reflection::ExtInstSpecConstantGlobalOffset
5739 << getSPIRVInt32Constant(global_offset_id[0])
5740 << getSPIRVInt32Constant(global_offset_id[1])
5741 << getSPIRVInt32Constant(global_offset_id[2]);
5742 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5743 }
5744 if (work_dim_id != kMax) {
5745 Ops.clear();
5746 Ops << void_id << import_id << reflection::ExtInstSpecConstantWorkDim
5747 << getSPIRVInt32Constant(work_dim_id);
5748 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5749 }
5750}
5751
5752void SPIRVProducerPass::GenerateKernelReflection() {
5753 const auto &DL = module->getDataLayout();
5754 auto import_id = getReflectionImport();
5755 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5756
5757 for (auto &F : *module) {
5758 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
5759 continue;
5760 }
5761
5762 // OpString for the kernel name.
5763 auto kernel_name =
5764 addSPIRVInst<kDebug>(spv::OpString, F.getName().str().c_str());
5765
5766 // Kernel declaration
5767 // Ops[0] = void type
5768 // Ops[1] = reflection ext import
5769 // Ops[2] = function id
5770 // Ops[3] = kernel name
5771 SPIRVOperandVec Ops;
5772 Ops << void_id << import_id << reflection::ExtInstKernel << ValueMap[&F]
5773 << kernel_name;
5774 auto kernel_decl = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5775
5776 // Generate the required workgroup size property if it was specified.
5777 if (const MDNode *MD = F.getMetadata("reqd_work_group_size")) {
5778 uint32_t CurXDimCst = static_cast<uint32_t>(
5779 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
5780 uint32_t CurYDimCst = static_cast<uint32_t>(
5781 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
5782 uint32_t CurZDimCst = static_cast<uint32_t>(
5783 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
5784
5785 Ops.clear();
5786 Ops << void_id << import_id
5787 << reflection::ExtInstPropertyRequiredWorkgroupSize << kernel_decl
5788 << getSPIRVInt32Constant(CurXDimCst)
5789 << getSPIRVInt32Constant(CurYDimCst)
5790 << getSPIRVInt32Constant(CurZDimCst);
5791 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5792 }
5793
5794 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
5795 auto *func_ty = F.getFunctionType();
5796
5797 // If we've clustered POD arguments, then argument details are in metadata.
5798 // If an argument maps to a resource variable, then get descriptor set and
5799 // binding from the resource variable. Other info comes from the metadata.
5800 const auto *arg_map = F.getMetadata(clspv::KernelArgMapMetadataName());
5801 auto local_spec_id_md =
5802 module->getNamedMetadata(clspv::LocalSpecIdMetadataName());
5803 if (arg_map) {
5804 for (const auto &arg : arg_map->operands()) {
5805 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
5806 assert(arg_node->getNumOperands() == 6);
5807 const auto name =
5808 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
5809 const auto old_index =
5810 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
5811 // Remapped argument index
5812 const int new_index = static_cast<int>(
5813 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getSExtValue());
5814 const auto offset =
5815 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
5816 const auto size =
5817 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
5818 const auto argKind = clspv::GetArgKindFromName(
5819 dyn_cast<MDString>(arg_node->getOperand(5))->getString().str());
5820
5821 // If this is a local memory argument, find the right spec id for this
5822 // argument.
5823 int64_t spec_id = -1;
5824 if (argKind == clspv::ArgKind::Local) {
5825 for (auto spec_id_arg : local_spec_id_md->operands()) {
5826 if ((&F == dyn_cast<Function>(
5827 dyn_cast<ValueAsMetadata>(spec_id_arg->getOperand(0))
5828 ->getValue())) &&
5829 (static_cast<uint64_t>(new_index) ==
5830 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(1))
5831 ->getZExtValue())) {
5832 spec_id =
5833 mdconst::extract<ConstantInt>(spec_id_arg->getOperand(2))
5834 ->getSExtValue();
5835 break;
5836 }
5837 }
5838 }
5839
5840 // Generate the specific argument instruction.
5841 const uint32_t ordinal = static_cast<uint32_t>(old_index);
5842 const uint32_t arg_offset = static_cast<uint32_t>(offset);
5843 const uint32_t arg_size = static_cast<uint32_t>(size);
5844 uint32_t elem_size = 0;
5845 uint32_t descriptor_set = 0;
5846 uint32_t binding = 0;
5847 if (spec_id > 0) {
5848 elem_size = static_cast<uint32_t>(
5849 GetTypeAllocSize(func_ty->getParamType(unsigned(new_index))
5850 ->getPointerElementType(),
5851 DL));
5852 } else if (new_index >= 0) {
5853 auto *info = resource_var_at_index[new_index];
5854 assert(info);
5855 descriptor_set = info->descriptor_set;
5856 binding = info->binding;
5857 }
5858 AddArgumentReflection(kernel_decl, name.str(), argKind, ordinal,
5859 descriptor_set, binding, arg_offset, arg_size,
5860 static_cast<uint32_t>(spec_id), elem_size);
5861 }
5862 } else {
5863 // There is no argument map.
5864 // Take descriptor info from the resource variable calls.
5865 // Take argument name and size from the arguments list.
5866
5867 SmallVector<Argument *, 4> arguments;
5868 for (auto &arg : F.args()) {
5869 arguments.push_back(&arg);
5870 }
5871
5872 unsigned arg_index = 0;
5873 for (auto *info : resource_var_at_index) {
5874 if (info) {
5875 auto arg = arguments[arg_index];
5876 unsigned arg_size = 0;
5877 if (info->arg_kind == clspv::ArgKind::Pod ||
5878 info->arg_kind == clspv::ArgKind::PodUBO ||
5879 info->arg_kind == clspv::ArgKind::PodPushConstant) {
5880 arg_size =
5881 static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
5882 }
5883
5884 // Local pointer arguments are unused in this case.
5885 // offset, spec_id and elem_size always 0.
5886 AddArgumentReflection(kernel_decl, arg->getName().str(),
5887 info->arg_kind, arg_index, info->descriptor_set,
5888 info->binding, 0, arg_size, 0, 0);
5889 }
5890 arg_index++;
5891 }
5892 // Generate mappings for pointer-to-local arguments.
5893 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
5894 Argument *arg = arguments[arg_index];
5895 auto where = LocalArgSpecIds.find(arg);
5896 if (where != LocalArgSpecIds.end()) {
5897 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
5898
5899 // descriptor_set, binding, offset and size are always 0.
5900 AddArgumentReflection(kernel_decl, arg->getName().str(),
5901 ArgKind::Local, arg_index, 0, 0, 0, 0,
5902 static_cast<uint32_t>(local_arg_info.spec_id),
5903 static_cast<uint32_t>(GetTypeAllocSize(
5904 local_arg_info.elem_type, DL)));
5905 }
5906 }
5907 }
5908 }
5909}
5910
5911void SPIRVProducerPass::AddArgumentReflection(
5912 SPIRVID kernel_decl, const std::string &name, clspv::ArgKind arg_kind,
5913 uint32_t ordinal, uint32_t descriptor_set, uint32_t binding,
5914 uint32_t offset, uint32_t size, uint32_t spec_id, uint32_t elem_size) {
5915 // Generate ArgumentInfo for this argument.
5916 // TODO: generate remaining optional operands.
5917 auto import_id = getReflectionImport();
5918 auto arg_name = addSPIRVInst<kDebug>(spv::OpString, name.c_str());
5919 auto void_id = getSPIRVType(Type::getVoidTy(module->getContext()));
5920 SPIRVOperandVec Ops;
5921 Ops << void_id << import_id << reflection::ExtInstArgumentInfo << arg_name;
5922 auto arg_info = addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5923
5924 Ops.clear();
5925 Ops << void_id << import_id;
5926 reflection::ExtInst ext_inst = reflection::ExtInstMax;
5927 // Determine the extended instruction.
5928 switch (arg_kind) {
5929 case clspv::ArgKind::Buffer:
5930 ext_inst = reflection::ExtInstArgumentStorageBuffer;
5931 break;
5932 case clspv::ArgKind::BufferUBO:
5933 ext_inst = reflection::ExtInstArgumentUniform;
5934 break;
5935 case clspv::ArgKind::Local:
5936 ext_inst = reflection::ExtInstArgumentWorkgroup;
5937 break;
5938 case clspv::ArgKind::Pod:
5939 ext_inst = reflection::ExtInstArgumentPodStorageBuffer;
5940 break;
5941 case clspv::ArgKind::PodUBO:
5942 ext_inst = reflection::ExtInstArgumentPodUniform;
5943 break;
5944 case clspv::ArgKind::PodPushConstant:
5945 ext_inst = reflection::ExtInstArgumentPodPushConstant;
5946 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005947 case clspv::ArgKind::SampledImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005948 ext_inst = reflection::ExtInstArgumentSampledImage;
5949 break;
alan-bakerf6bc8252020-09-23 14:58:55 -04005950 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005951 ext_inst = reflection::ExtInstArgumentStorageImage;
5952 break;
5953 case clspv::ArgKind::Sampler:
5954 ext_inst = reflection::ExtInstArgumentSampler;
5955 break;
5956 default:
5957 llvm_unreachable("Unhandled argument reflection");
5958 break;
5959 }
5960 Ops << ext_inst << kernel_decl << getSPIRVInt32Constant(ordinal);
5961
5962 // Add descriptor set and binding for applicable arguments.
5963 switch (arg_kind) {
5964 case clspv::ArgKind::Buffer:
5965 case clspv::ArgKind::BufferUBO:
5966 case clspv::ArgKind::Pod:
5967 case clspv::ArgKind::PodUBO:
alan-bakerf6bc8252020-09-23 14:58:55 -04005968 case clspv::ArgKind::SampledImage:
5969 case clspv::ArgKind::StorageImage:
alan-baker86ce19c2020-08-05 13:09:19 -04005970 case clspv::ArgKind::Sampler:
5971 Ops << getSPIRVInt32Constant(descriptor_set)
5972 << getSPIRVInt32Constant(binding);
5973 break;
5974 default:
5975 break;
5976 }
5977
5978 // Add remaining operands for arguments.
5979 switch (arg_kind) {
5980 case clspv::ArgKind::Local:
5981 Ops << getSPIRVInt32Constant(spec_id) << getSPIRVInt32Constant(elem_size);
5982 break;
5983 case clspv::ArgKind::Pod:
5984 case clspv::ArgKind::PodUBO:
5985 case clspv::ArgKind::PodPushConstant:
5986 Ops << getSPIRVInt32Constant(offset) << getSPIRVInt32Constant(size);
5987 break;
5988 default:
5989 break;
5990 }
5991 Ops << arg_info;
5992 addSPIRVInst<kReflection>(spv::OpExtInst, Ops);
5993}