blob: c0e00b8d1a52703b7f177b7a3f07ebc46a55b292 [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"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040047#include "clspv/Option.h"
48#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070049#include "clspv/spirv_c_strings.hpp"
50#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040051
David Neto4feb7a42017-10-06 17:29:42 -040052#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070053#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040054#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040055#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040056
David Neto22f144c2017-06-12 14:26:21 -040057#if defined(_MSC_VER)
58#pragma warning(pop)
59#endif
60
61using namespace llvm;
62using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040063using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040064
65namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040066
David Neto862b7d82018-06-14 18:48:37 -040067cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
68 cl::desc("Show resource variable creation"));
69
70// These hacks exist to help transition code generation algorithms
71// without making huge noise in detailed test output.
72const bool Hack_generate_runtime_array_stride_early = true;
73
David Neto3fbb4072017-10-16 11:28:14 -040074// The value of 1/pi. This value is from MSDN
75// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
76const double kOneOverPi = 0.318309886183790671538;
77const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
78
alan-bakerb6b09dc2018-11-08 16:59:28 -050079const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040080
David Neto22f144c2017-06-12 14:26:21 -040081enum SPIRVOperandType {
82 NUMBERID,
83 LITERAL_INTEGER,
84 LITERAL_STRING,
85 LITERAL_FLOAT
86};
87
88struct SPIRVOperand {
89 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
90 : Type(Ty), LiteralNum(1, Num) {}
91 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
92 : Type(Ty), LiteralStr(Str) {}
93 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
94 : Type(Ty), LiteralStr(Str) {}
95 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
96 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
97
98 SPIRVOperandType getType() { return Type; };
99 uint32_t getNumID() { return LiteralNum[0]; };
100 std::string getLiteralStr() { return LiteralStr; };
101 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
102
David Neto87846742018-04-11 17:36:22 -0400103 uint32_t GetNumWords() const {
104 switch (Type) {
105 case NUMBERID:
106 return 1;
107 case LITERAL_INTEGER:
108 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400109 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400110 case LITERAL_STRING:
111 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400112 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400113 }
114 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
115 }
116
David Neto22f144c2017-06-12 14:26:21 -0400117private:
118 SPIRVOperandType Type;
119 std::string LiteralStr;
120 SmallVector<uint32_t, 4> LiteralNum;
121};
122
David Netoc6f3ab22018-04-06 18:02:31 -0400123class SPIRVOperandList {
124public:
125 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500126 SPIRVOperandList(const SPIRVOperandList &other) = delete;
127 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400128 contents_ = std::move(other.contents_);
129 other.contents_.clear();
130 }
131 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
132 : contents_(init.begin(), init.end()) {}
133 operator ArrayRef<SPIRVOperand *>() { return contents_; }
134 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500135 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400136 size_t size() const { return contents_.size(); }
137 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
138
David Neto87846742018-04-11 17:36:22 -0400139 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
140 return contents_;
141 }
142
David Netoc6f3ab22018-04-06 18:02:31 -0400143private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500144 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400145};
146
147SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
148 list.push_back(elem);
149 return list;
150}
151
alan-bakerb6b09dc2018-11-08 16:59:28 -0500152SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400153 return new SPIRVOperand(LITERAL_INTEGER, num);
154}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500155SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400156 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
157}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500158SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400159 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
160}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500161SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
162SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400163 return new SPIRVOperand(LITERAL_STRING, str);
164}
David Netoc6f3ab22018-04-06 18:02:31 -0400165
David Neto22f144c2017-06-12 14:26:21 -0400166struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400167 // Create an instruction with an opcode and no result ID, and with the given
168 // operands. This computes its own word count.
169 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
170 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
171 Operands(Ops.begin(), Ops.end()) {
172 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400173 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400174 }
175 }
176 // Create an instruction with an opcode and a no-zero result ID, and
177 // with the given operands. This computes its own word count.
178 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400179 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400180 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
181 Operands(Ops.begin(), Ops.end()) {
182 if (ResID == 0) {
183 llvm_unreachable("Result ID of 0 was provided");
184 }
185 for (auto *operand : Ops) {
186 WordCount += operand->GetNumWords();
187 }
188 }
David Neto22f144c2017-06-12 14:26:21 -0400189
David Netoee2660d2018-06-28 16:31:29 -0400190 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400191 uint16_t getOpcode() const { return Opcode; }
192 uint32_t getResultID() const { return ResultID; }
193 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
194
195private:
David Netoee2660d2018-06-28 16:31:29 -0400196 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400197 uint16_t Opcode;
198 uint32_t ResultID;
199 SmallVector<SPIRVOperand *, 4> Operands;
200};
201
202struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400203 typedef DenseMap<Type *, uint32_t> TypeMapType;
204 typedef UniqueVector<Type *> TypeList;
205 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400206 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400207 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
208 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400209 // A vector of tuples, each of which is:
210 // - the LLVM instruction that we will later generate SPIR-V code for
211 // - where the SPIR-V instruction should be inserted
212 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400213 typedef std::vector<
214 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
215 DeferredInstVecType;
216 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
217 GlobalConstFuncMapType;
218
David Neto44795152017-07-13 15:45:28 -0400219 explicit SPIRVProducerPass(
220 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
221 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
222 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400223 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400224 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400225 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400226 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400227 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500228 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0), max_local_spec_id_(0),
229 constant_i32_zero_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400230
231 void getAnalysisUsage(AnalysisUsage &AU) const override {
232 AU.addRequired<DominatorTreeWrapperPass>();
233 AU.addRequired<LoopInfoWrapperPass>();
234 }
235
236 virtual bool runOnModule(Module &module) override;
237
238 // output the SPIR-V header block
239 void outputHeader();
240
241 // patch the SPIR-V header block
242 void patchHeader();
243
244 uint32_t lookupType(Type *Ty) {
245 if (Ty->isPointerTy() &&
246 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
247 auto PointeeTy = Ty->getPointerElementType();
248 if (PointeeTy->isStructTy() &&
249 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
250 Ty = PointeeTy;
251 }
252 }
253
David Neto862b7d82018-06-14 18:48:37 -0400254 auto where = TypeMap.find(Ty);
255 if (where == TypeMap.end()) {
256 if (Ty) {
257 errs() << "Unhandled type " << *Ty << "\n";
258 } else {
259 errs() << "Unhandled type (null)\n";
260 }
David Netoe439d702018-03-23 13:14:08 -0700261 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400262 }
263
David Neto862b7d82018-06-14 18:48:37 -0400264 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
267 TypeList &getTypeList() { return Types; };
268 ValueList &getConstantList() { return Constants; };
269 ValueMapType &getValueMap() { return ValueMap; }
270 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
271 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400272 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
273 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
274 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
275 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
276 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500277 bool hasVariablePointers() {
278 return true; /* We use StorageBuffer everywhere */
279 };
David Neto22f144c2017-06-12 14:26:21 -0400280 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500281 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
282 return samplerMap;
283 }
David Neto22f144c2017-06-12 14:26:21 -0400284 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
285 return GlobalConstFuncTypeMap;
286 }
287 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
288 return GlobalConstArgumentSet;
289 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400291
David Netoc6f3ab22018-04-06 18:02:31 -0400292 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500293 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
294 // *not* be converted to a storage buffer, replace each such global variable
295 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400296 void FindGlobalConstVars(Module &M, const DataLayout &DL);
297 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
298 // ModuleOrderedResourceVars.
299 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400300 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400301 bool FindExtInst(Module &M);
302 void FindTypePerGlobalVar(GlobalVariable &GV);
303 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400304 void FindTypesForSamplerMap(Module &M);
305 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500306 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
307 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400308 void FindType(Type *Ty);
309 void FindConstantPerGlobalVar(GlobalVariable &GV);
310 void FindConstantPerFunc(Function &F);
311 void FindConstant(Value *V);
312 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400313 // Generates instructions for SPIR-V types corresponding to the LLVM types
314 // saved in the |Types| member. A type follows its subtypes. IDs are
315 // allocated sequentially starting with the current value of nextID, and
316 // with a type following its subtypes. Also updates nextID to just beyond
317 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500318 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400319 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400320 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400321 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400322 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Generate descriptor map entries for resource variables associated with
324 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500325 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400326 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400327 // Generate OpVariables for %clspv.resource.var.* calls.
328 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400329 void GenerateFuncPrologue(Function &F);
330 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400331 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400332 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
333 spv::Op GetSPIRVCastOpcode(Instruction &I);
334 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
335 void GenerateInstruction(Instruction &I);
336 void GenerateFuncEpilogue();
337 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500338 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400339 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400340 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
341 // have been created.
342 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400343 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400344 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400345 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400346 // Returns the GLSL extended instruction enum that the given function
347 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400348 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400349 // Returns the GLSL extended instruction enum indirectly used by the given
350 // function. That is, to implement the given function, we use an extended
351 // instruction plus one more instruction. If none, then returns the 0 value,
352 // i.e. GLSLstd4580Bad.
353 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
354 // Returns the single GLSL extended instruction used directly or
355 // indirectly by the given function call.
356 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400357 void PrintResID(SPIRVInstruction *Inst);
358 void PrintOpcode(SPIRVInstruction *Inst);
359 void PrintOperand(SPIRVOperand *Op);
360 void PrintCapability(SPIRVOperand *Op);
361 void PrintExtInst(SPIRVOperand *Op);
362 void PrintAddrModel(SPIRVOperand *Op);
363 void PrintMemModel(SPIRVOperand *Op);
364 void PrintExecModel(SPIRVOperand *Op);
365 void PrintExecMode(SPIRVOperand *Op);
366 void PrintSourceLanguage(SPIRVOperand *Op);
367 void PrintFuncCtrl(SPIRVOperand *Op);
368 void PrintStorageClass(SPIRVOperand *Op);
369 void PrintDecoration(SPIRVOperand *Op);
370 void PrintBuiltIn(SPIRVOperand *Op);
371 void PrintSelectionControl(SPIRVOperand *Op);
372 void PrintLoopControl(SPIRVOperand *Op);
373 void PrintDimensionality(SPIRVOperand *Op);
374 void PrintImageFormat(SPIRVOperand *Op);
375 void PrintMemoryAccess(SPIRVOperand *Op);
376 void PrintImageOperandsType(SPIRVOperand *Op);
377 void WriteSPIRVAssembly();
378 void WriteOneWord(uint32_t Word);
379 void WriteResultID(SPIRVInstruction *Inst);
380 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
381 void WriteOperand(SPIRVOperand *Op);
382 void WriteSPIRVBinary();
383
Alan Baker9bf93fb2018-08-28 16:59:26 -0400384 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500385 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400386
Alan Bakerfcda9482018-10-02 17:09:59 -0400387 // Populate UBO remapped type maps.
388 void PopulateUBOTypeMaps(Module &module);
389
390 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
391 // uses the internal map, otherwise it falls back on the data layout.
392 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
393 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
394 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
395
David Neto22f144c2017-06-12 14:26:21 -0400396private:
397 static char ID;
David Neto44795152017-07-13 15:45:28 -0400398 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400399 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400400
401 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
402 // convert to other formats on demand?
403
404 // When emitting a C initialization list, the WriteSPIRVBinary method
405 // will actually write its words to this vector via binaryTempOut.
406 SmallVector<char, 100> binaryTempUnderlyingVector;
407 raw_svector_ostream binaryTempOut;
408
409 // Binary output writes to this stream, which might be |out| or
410 // |binaryTempOut|. It's the latter when we really want to write a C
411 // initializer list.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500412 raw_pwrite_stream *binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400413 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400414 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400415 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400416 uint64_t patchBoundOffset;
417 uint32_t nextID;
418
David Neto19a1bad2017-08-25 15:01:41 -0400419 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400420 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400421 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400422 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400423 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400424 TypeList Types;
425 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400426 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400427 ValueMapType ValueMap;
428 ValueMapType AllocatedValueMap;
429 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400430
David Neto22f144c2017-06-12 14:26:21 -0400431 EntryPointVecType EntryPointVec;
432 DeferredInstVecType DeferredInstVec;
433 ValueList EntryPointInterfacesVec;
434 uint32_t OpExtInstImportID;
435 std::vector<uint32_t> BuiltinDimensionVec;
436 bool HasVariablePointers;
437 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500438 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700439
440 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700441 // will map F's type to (G, index of the parameter), where in a first phase
442 // G is F's type. During FindTypePerFunc, G will be changed to F's type
443 // but replacing the pointer-to-constant parameter with
444 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700445 // TODO(dneto): This doesn't seem general enough? A function might have
446 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400447 GlobalConstFuncMapType GlobalConstFuncTypeMap;
448 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400449 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700450 // or array types, and which point into transparent memory (StorageBuffer
451 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400452 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700453 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400454
455 // This is truly ugly, but works around what look like driver bugs.
456 // For get_local_size, an earlier part of the flow has created a module-scope
457 // variable in Private address space to hold the value for the workgroup
458 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
459 // When this is present, save the IDs of the initializer value and variable
460 // in these two variables. We only ever do a vector load from it, and
461 // when we see one of those, substitute just the value of the intializer.
462 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700463 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400464 uint32_t WorkgroupSizeValueID;
465 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400466
David Neto862b7d82018-06-14 18:48:37 -0400467 // Bookkeeping for mapping kernel arguments to resource variables.
468 struct ResourceVarInfo {
469 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
470 Function *fn, clspv::ArgKind arg_kind_arg)
471 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
472 var_fn(fn), arg_kind(arg_kind_arg),
473 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
474 const int index; // Index into ResourceVarInfoList
475 const unsigned descriptor_set;
476 const unsigned binding;
477 Function *const var_fn; // The @clspv.resource.var.* function.
478 const clspv::ArgKind arg_kind;
479 const unsigned addr_space; // The LLVM address space
480 // The SPIR-V ID of the OpVariable. Not populated at construction time.
481 uint32_t var_id = 0;
482 };
483 // A list of resource var info. Each one correponds to a module-scope
484 // resource variable we will have to create. Resource var indices are
485 // indices into this vector.
486 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
487 // This is a vector of pointers of all the resource vars, but ordered by
488 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500489 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400490 // Map a function to the ordered list of resource variables it uses, one for
491 // each argument. If an argument does not use a resource variable, it
492 // will have a null pointer entry.
493 using FunctionToResourceVarsMapType =
494 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
495 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
496
497 // What LLVM types map to SPIR-V types needing layout? These are the
498 // arrays and structures supporting storage buffers and uniform buffers.
499 TypeList TypesNeedingLayout;
500 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
501 UniqueVector<StructType *> StructTypesNeedingBlock;
502 // For a call that represents a load from an opaque type (samplers, images),
503 // map it to the variable id it should load from.
504 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700505
Alan Baker202c8c72018-08-13 13:47:44 -0400506 // One larger than the maximum used SpecId for pointer-to-local arguments.
507 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400508 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500509 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400510 LocalArgList LocalArgs;
511 // Information about a pointer-to-local argument.
512 struct LocalArgInfo {
513 // The SPIR-V ID of the array variable.
514 uint32_t variable_id;
515 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500516 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400517 // The ID of the array type.
518 uint32_t array_size_id;
519 // The ID of the array type.
520 uint32_t array_type_id;
521 // The ID of the pointer to the array type.
522 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400523 // The specialization constant ID of the array size.
524 int spec_id;
525 };
Alan Baker202c8c72018-08-13 13:47:44 -0400526 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500527 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400528 // A mapping from SpecId to its LocalArgInfo.
529 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400530 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500531 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400532 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500533 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
534 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400535
536 // The ID of 32-bit integer zero constant. This is only valid after
537 // GenerateSPIRVConstants has run.
538 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400539};
540
541char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400542
alan-bakerb6b09dc2018-11-08 16:59:28 -0500543} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400544
545namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400546ModulePass *
547createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
548 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
549 bool outputAsm, bool outputCInitList) {
550 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
551 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400552}
David Netoc2c368d2017-06-30 16:50:17 -0400553} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400554
555bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400556 binaryOut = outputCInitList ? &binaryTempOut : &out;
557
David Neto257c3892018-04-11 13:19:45 -0400558 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
559
Alan Bakerfcda9482018-10-02 17:09:59 -0400560 PopulateUBOTypeMaps(module);
561
David Neto22f144c2017-06-12 14:26:21 -0400562 // SPIR-V always begins with its header information
563 outputHeader();
564
David Netoc6f3ab22018-04-06 18:02:31 -0400565 const DataLayout &DL = module.getDataLayout();
566
David Neto22f144c2017-06-12 14:26:21 -0400567 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400568 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400569
David Neto22f144c2017-06-12 14:26:21 -0400570 // Collect information on global variables too.
571 for (GlobalVariable &GV : module.globals()) {
572 // If the GV is one of our special __spirv_* variables, remove the
573 // initializer as it was only placed there to force LLVM to not throw the
574 // value away.
575 if (GV.getName().startswith("__spirv_")) {
576 GV.setInitializer(nullptr);
577 }
578
579 // Collect types' information from global variable.
580 FindTypePerGlobalVar(GV);
581
582 // Collect constant information from global variable.
583 FindConstantPerGlobalVar(GV);
584
585 // If the variable is an input, entry points need to know about it.
586 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400587 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400588 }
589 }
590
591 // If there are extended instructions, generate OpExtInstImport.
592 if (FindExtInst(module)) {
593 GenerateExtInstImport();
594 }
595
596 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400597 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400598
599 // Generate SPIRV constants.
600 GenerateSPIRVConstants();
601
602 // If we have a sampler map, we might have literal samplers to generate.
603 if (0 < getSamplerMap().size()) {
604 GenerateSamplers(module);
605 }
606
607 // Generate SPIRV variables.
608 for (GlobalVariable &GV : module.globals()) {
609 GenerateGlobalVar(GV);
610 }
David Neto862b7d82018-06-14 18:48:37 -0400611 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400612 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400613
614 // Generate SPIRV instructions for each function.
615 for (Function &F : module) {
616 if (F.isDeclaration()) {
617 continue;
618 }
619
David Neto862b7d82018-06-14 18:48:37 -0400620 GenerateDescriptorMapInfo(DL, F);
621
David Neto22f144c2017-06-12 14:26:21 -0400622 // Generate Function Prologue.
623 GenerateFuncPrologue(F);
624
625 // Generate SPIRV instructions for function body.
626 GenerateFuncBody(F);
627
628 // Generate Function Epilogue.
629 GenerateFuncEpilogue();
630 }
631
632 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400633 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400634
635 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400636 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400637
638 if (outputAsm) {
639 WriteSPIRVAssembly();
640 } else {
641 WriteSPIRVBinary();
642 }
643
644 // We need to patch the SPIR-V header to set bound correctly.
645 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400646
647 if (outputCInitList) {
648 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400649 std::ostringstream os;
650
David Neto57fb0b92017-08-04 15:35:09 -0400651 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400652 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400653 os << ",\n";
654 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400655 first = false;
656 };
657
658 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400659 const std::string str(binaryTempOut.str());
660 for (unsigned i = 0; i < str.size(); i += 4) {
661 const uint32_t a = static_cast<unsigned char>(str[i]);
662 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
663 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
664 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
665 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400666 }
667 os << "}\n";
668 out << os.str();
669 }
670
David Neto22f144c2017-06-12 14:26:21 -0400671 return false;
672}
673
674void SPIRVProducerPass::outputHeader() {
675 if (outputAsm) {
676 // for ASM output the header goes into 5 comments at the beginning of the
677 // file
678 out << "; SPIR-V\n";
679
680 // the major version number is in the 2nd highest byte
681 const uint32_t major = (spv::Version >> 16) & 0xFF;
682
683 // the minor version number is in the 2nd lowest byte
684 const uint32_t minor = (spv::Version >> 8) & 0xFF;
685 out << "; Version: " << major << "." << minor << "\n";
686
687 // use Codeplay's vendor ID
688 out << "; Generator: Codeplay; 0\n";
689
690 out << "; Bound: ";
691
692 // we record where we need to come back to and patch in the bound value
693 patchBoundOffset = out.tell();
694
695 // output one space per digit for the max size of a 32 bit unsigned integer
696 // (which is the maximum ID we could possibly be using)
697 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
698 out << " ";
699 }
700
701 out << "\n";
702
703 out << "; Schema: 0\n";
704 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400705 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500706 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400707 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500708 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400709
710 // use Codeplay's vendor ID
711 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400712 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400713
714 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400715 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400716
717 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400718 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400719
720 // output the schema (reserved for use and must be 0)
721 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400722 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400723 }
724}
725
726void SPIRVProducerPass::patchHeader() {
727 if (outputAsm) {
728 // get the string representation of the max bound used (nextID will be the
729 // max ID used)
730 auto asString = std::to_string(nextID);
731 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
732 } else {
733 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400734 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
735 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400736 }
737}
738
David Netoc6f3ab22018-04-06 18:02:31 -0400739void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400740 // This function generates LLVM IR for function such as global variable for
741 // argument, constant and pointer type for argument access. These information
742 // is artificial one because we need Vulkan SPIR-V output. This function is
743 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400744 LLVMContext &Context = M.getContext();
745
David Neto862b7d82018-06-14 18:48:37 -0400746 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400747
David Neto862b7d82018-06-14 18:48:37 -0400748 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400749
750 bool HasWorkGroupBuiltin = false;
751 for (GlobalVariable &GV : M.globals()) {
752 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
753 if (spv::BuiltInWorkgroupSize == BuiltinType) {
754 HasWorkGroupBuiltin = true;
755 }
756 }
757
David Neto862b7d82018-06-14 18:48:37 -0400758 FindTypesForSamplerMap(M);
759 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400760 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400761
David Neto862b7d82018-06-14 18:48:37 -0400762 // TODO(dneto): Delete the next 3 vars.
763
764 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400765 // Map kernel functions to their ordinal number in the compilation unit.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500766 UniqueVector<Function *> KernelOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400767
768 // Map the global variables created for kernel args to their creation
769 // order.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500770 UniqueVector<GlobalVariable *> KernelArgVarOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400771
David Neto862b7d82018-06-14 18:48:37 -0400772 // For each kernel argument type, record the kernel arg global resource
773 // variables generated for that type, the function in which that variable
774 // was most recently used, and the binding number it took. For
775 // reproducibility, we track things by ordinal number (rather than pointer),
776 // and we use a std::set rather than DenseSet since std::set maintains an
777 // ordering. Each tuple is the ordinals of the kernel function, the binding
778 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400779 //
780 // This table lets us reuse module-scope StorageBuffer variables between
781 // different kernels.
782 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
783 GVarsForType;
784
David Neto862b7d82018-06-14 18:48:37 -0400785 // These function calls need a <2 x i32> as an intermediate result but not
786 // the final result.
787 std::unordered_set<std::string> NeedsIVec2{
788 "_Z15get_image_width14ocl_image2d_ro",
789 "_Z15get_image_width14ocl_image2d_wo",
790 "_Z16get_image_height14ocl_image2d_ro",
791 "_Z16get_image_height14ocl_image2d_wo",
792 };
793
David Neto22f144c2017-06-12 14:26:21 -0400794 for (Function &F : M) {
795 // Handle kernel function first.
796 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
797 continue;
798 }
David Neto26aaf622017-10-23 18:11:53 -0400799 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400800
801 for (BasicBlock &BB : F) {
802 for (Instruction &I : BB) {
803 if (I.getOpcode() == Instruction::ZExt ||
804 I.getOpcode() == Instruction::SExt ||
805 I.getOpcode() == Instruction::UIToFP) {
806 // If there is zext with i1 type, it will be changed to OpSelect. The
807 // OpSelect needs constant 0 and 1 so the constants are added here.
808
809 auto OpTy = I.getOperand(0)->getType();
810
Kévin Petit24272b62018-10-18 19:16:12 +0000811 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400812 if (I.getOpcode() == Instruction::ZExt) {
813 APInt One(32, 1);
814 FindConstant(Constant::getNullValue(I.getType()));
815 FindConstant(Constant::getIntegerValue(I.getType(), One));
816 } else if (I.getOpcode() == Instruction::SExt) {
817 APInt MinusOne(32, UINT64_MAX, true);
818 FindConstant(Constant::getNullValue(I.getType()));
819 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
820 } else {
821 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
822 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
823 }
824 }
825 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400826 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400827
828 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400829 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400830 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400831 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400832 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
833 TypeMapType &OpImageTypeMap = getImageTypeMap();
834 Type *ImageTy =
835 Call->getArgOperand(0)->getType()->getPointerElementType();
836 OpImageTypeMap[ImageTy] = 0;
837
838 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
839 }
David Neto5c22a252018-03-15 16:07:41 -0400840
David Neto862b7d82018-06-14 18:48:37 -0400841 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400842 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
843 }
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845 }
846 }
847
David Neto22f144c2017-06-12 14:26:21 -0400848 if (const MDNode *MD =
849 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
850 // We generate constants if the WorkgroupSize builtin is being used.
851 if (HasWorkGroupBuiltin) {
852 // Collect constant information for work group size.
853 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
854 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
855 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
856 }
857 }
858
David Neto22f144c2017-06-12 14:26:21 -0400859 // Collect types' information from function.
860 FindTypePerFunc(F);
861
862 // Collect constant information from function.
863 FindConstantPerFunc(F);
864 }
865
866 for (Function &F : M) {
867 // Handle non-kernel functions.
868 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
869 continue;
870 }
871
872 for (BasicBlock &BB : F) {
873 for (Instruction &I : BB) {
874 if (I.getOpcode() == Instruction::ZExt ||
875 I.getOpcode() == Instruction::SExt ||
876 I.getOpcode() == Instruction::UIToFP) {
877 // If there is zext with i1 type, it will be changed to OpSelect. The
878 // OpSelect needs constant 0 and 1 so the constants are added here.
879
880 auto OpTy = I.getOperand(0)->getType();
881
Kévin Petit24272b62018-10-18 19:16:12 +0000882 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400883 if (I.getOpcode() == Instruction::ZExt) {
884 APInt One(32, 1);
885 FindConstant(Constant::getNullValue(I.getType()));
886 FindConstant(Constant::getIntegerValue(I.getType(), One));
887 } else if (I.getOpcode() == Instruction::SExt) {
888 APInt MinusOne(32, UINT64_MAX, true);
889 FindConstant(Constant::getNullValue(I.getType()));
890 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
891 } else {
892 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
893 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
894 }
895 }
896 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
897 Function *Callee = Call->getCalledFunction();
898
899 // Handle image type specially.
900 if (Callee->getName().equals(
901 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
902 Callee->getName().equals(
903 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
904 TypeMapType &OpImageTypeMap = getImageTypeMap();
905 Type *ImageTy =
906 Call->getArgOperand(0)->getType()->getPointerElementType();
907 OpImageTypeMap[ImageTy] = 0;
908
909 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
910 }
911 }
912 }
913 }
914
915 if (M.getTypeByName("opencl.image2d_ro_t") ||
916 M.getTypeByName("opencl.image2d_wo_t") ||
917 M.getTypeByName("opencl.image3d_ro_t") ||
918 M.getTypeByName("opencl.image3d_wo_t")) {
919 // Assume Image type's sampled type is float type.
920 FindType(Type::getFloatTy(Context));
921 }
922
923 // Collect types' information from function.
924 FindTypePerFunc(F);
925
926 // Collect constant information from function.
927 FindConstantPerFunc(F);
928 }
929}
930
David Neto862b7d82018-06-14 18:48:37 -0400931void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
932 SmallVector<GlobalVariable *, 8> GVList;
933 SmallVector<GlobalVariable *, 8> DeadGVList;
934 for (GlobalVariable &GV : M.globals()) {
935 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
936 if (GV.use_empty()) {
937 DeadGVList.push_back(&GV);
938 } else {
939 GVList.push_back(&GV);
940 }
941 }
942 }
943
944 // Remove dead global __constant variables.
945 for (auto GV : DeadGVList) {
946 GV->eraseFromParent();
947 }
948 DeadGVList.clear();
949
950 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
951 // For now, we only support a single storage buffer.
952 if (GVList.size() > 0) {
953 assert(GVList.size() == 1);
954 const auto *GV = GVList[0];
955 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400956 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400957 const size_t kConstantMaxSize = 65536;
958 if (constants_byte_size > kConstantMaxSize) {
959 outs() << "Max __constant capacity of " << kConstantMaxSize
960 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
961 llvm_unreachable("Max __constant capacity exceeded");
962 }
963 }
964 } else {
965 // Change global constant variable's address space to ModuleScopePrivate.
966 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
967 for (auto GV : GVList) {
968 // Create new gv with ModuleScopePrivate address space.
969 Type *NewGVTy = GV->getType()->getPointerElementType();
970 GlobalVariable *NewGV = new GlobalVariable(
971 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
972 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
973 NewGV->takeName(GV);
974
975 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
976 SmallVector<User *, 8> CandidateUsers;
977
978 auto record_called_function_type_as_user =
979 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
980 // Find argument index.
981 unsigned index = 0;
982 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
983 if (gv == call->getOperand(i)) {
984 // TODO(dneto): Should we break here?
985 index = i;
986 }
987 }
988
989 // Record function type with global constant.
990 GlobalConstFuncTyMap[call->getFunctionType()] =
991 std::make_pair(call->getFunctionType(), index);
992 };
993
994 for (User *GVU : GVUsers) {
995 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
996 record_called_function_type_as_user(GV, Call);
997 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
998 // Check GEP users.
999 for (User *GEPU : GEP->users()) {
1000 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1001 record_called_function_type_as_user(GEP, GEPCall);
1002 }
1003 }
1004 }
1005
1006 CandidateUsers.push_back(GVU);
1007 }
1008
1009 for (User *U : CandidateUsers) {
1010 // Update users of gv with new gv.
1011 U->replaceUsesOfWith(GV, NewGV);
1012 }
1013
1014 // Delete original gv.
1015 GV->eraseFromParent();
1016 }
1017 }
1018}
1019
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001020void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001021 ResourceVarInfoList.clear();
1022 FunctionToResourceVarsMap.clear();
1023 ModuleOrderedResourceVars.reset();
1024 // Normally, there is one resource variable per clspv.resource.var.*
1025 // function, since that is unique'd by arg type and index. By design,
1026 // we can share these resource variables across kernels because all
1027 // kernels use the same descriptor set.
1028 //
1029 // But if the user requested distinct descriptor sets per kernel, then
1030 // the descriptor allocator has made different (set,binding) pairs for
1031 // the same (type,arg_index) pair. Since we can decorate a resource
1032 // variable with only exactly one DescriptorSet and Binding, we are
1033 // forced in this case to make distinct resource variables whenever
1034 // the same clspv.reource.var.X function is seen with disintct
1035 // (set,binding) values.
1036 const bool always_distinct_sets =
1037 clspv::Option::DistinctKernelDescriptorSets();
1038 for (Function &F : M) {
1039 // Rely on the fact the resource var functions have a stable ordering
1040 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001041 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001042 // Find all calls to this function with distinct set and binding pairs.
1043 // Save them in ResourceVarInfoList.
1044
1045 // Determine uniqueness of the (set,binding) pairs only withing this
1046 // one resource-var builtin function.
1047 using SetAndBinding = std::pair<unsigned, unsigned>;
1048 // Maps set and binding to the resource var info.
1049 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1050 bool first_use = true;
1051 for (auto &U : F.uses()) {
1052 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1053 const auto set = unsigned(
1054 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1055 const auto binding = unsigned(
1056 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1057 const auto arg_kind = clspv::ArgKind(
1058 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1059 const auto arg_index = unsigned(
1060 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1061
1062 // Find or make the resource var info for this combination.
1063 ResourceVarInfo *rv = nullptr;
1064 if (always_distinct_sets) {
1065 // Make a new resource var any time we see a different
1066 // (set,binding) pair.
1067 SetAndBinding key{set, binding};
1068 auto where = set_and_binding_map.find(key);
1069 if (where == set_and_binding_map.end()) {
1070 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1071 binding, &F, arg_kind);
1072 ResourceVarInfoList.emplace_back(rv);
1073 set_and_binding_map[key] = rv;
1074 } else {
1075 rv = where->second;
1076 }
1077 } else {
1078 // The default is to make exactly one resource for each
1079 // clspv.resource.var.* function.
1080 if (first_use) {
1081 first_use = false;
1082 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1083 binding, &F, arg_kind);
1084 ResourceVarInfoList.emplace_back(rv);
1085 } else {
1086 rv = ResourceVarInfoList.back().get();
1087 }
1088 }
1089
1090 // Now populate FunctionToResourceVarsMap.
1091 auto &mapping =
1092 FunctionToResourceVarsMap[call->getParent()->getParent()];
1093 while (mapping.size() <= arg_index) {
1094 mapping.push_back(nullptr);
1095 }
1096 mapping[arg_index] = rv;
1097 }
1098 }
1099 }
1100 }
1101
1102 // Populate ModuleOrderedResourceVars.
1103 for (Function &F : M) {
1104 auto where = FunctionToResourceVarsMap.find(&F);
1105 if (where != FunctionToResourceVarsMap.end()) {
1106 for (auto &rv : where->second) {
1107 if (rv != nullptr) {
1108 ModuleOrderedResourceVars.insert(rv);
1109 }
1110 }
1111 }
1112 }
1113 if (ShowResourceVars) {
1114 for (auto *info : ModuleOrderedResourceVars) {
1115 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1116 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1117 << "\n";
1118 }
1119 }
1120}
1121
David Neto22f144c2017-06-12 14:26:21 -04001122bool SPIRVProducerPass::FindExtInst(Module &M) {
1123 LLVMContext &Context = M.getContext();
1124 bool HasExtInst = false;
1125
1126 for (Function &F : M) {
1127 for (BasicBlock &BB : F) {
1128 for (Instruction &I : BB) {
1129 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1130 Function *Callee = Call->getCalledFunction();
1131 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001132 auto callee_name = Callee->getName();
1133 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1134 const glsl::ExtInst IndirectEInst =
1135 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001136
David Neto3fbb4072017-10-16 11:28:14 -04001137 HasExtInst |=
1138 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1139
1140 if (IndirectEInst) {
1141 // Register extra constants if needed.
1142
1143 // Registers a type and constant for computing the result of the
1144 // given instruction. If the result of the instruction is a vector,
1145 // then make a splat vector constant with the same number of
1146 // elements.
1147 auto register_constant = [this, &I](Constant *constant) {
1148 FindType(constant->getType());
1149 FindConstant(constant);
1150 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1151 // Register the splat vector of the value with the same
1152 // width as the result of the instruction.
1153 auto *vec_constant = ConstantVector::getSplat(
1154 static_cast<unsigned>(vectorTy->getNumElements()),
1155 constant);
1156 FindConstant(vec_constant);
1157 FindType(vec_constant->getType());
1158 }
1159 };
1160 switch (IndirectEInst) {
1161 case glsl::ExtInstFindUMsb:
1162 // clz needs OpExtInst and OpISub with constant 31, or splat
1163 // vector of 31. Add it to the constant list here.
1164 register_constant(
1165 ConstantInt::get(Type::getInt32Ty(Context), 31));
1166 break;
1167 case glsl::ExtInstAcos:
1168 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001169 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001170 case glsl::ExtInstAtan2:
1171 // We need 1/pi for acospi, asinpi, atan2pi.
1172 register_constant(
1173 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1174 break;
1175 default:
1176 assert(false && "internally inconsistent");
1177 }
David Neto22f144c2017-06-12 14:26:21 -04001178 }
1179 }
1180 }
1181 }
1182 }
1183
1184 return HasExtInst;
1185}
1186
1187void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1188 // Investigate global variable's type.
1189 FindType(GV.getType());
1190}
1191
1192void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1193 // Investigate function's type.
1194 FunctionType *FTy = F.getFunctionType();
1195
1196 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1197 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001198 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001199 if (GlobalConstFuncTyMap.count(FTy)) {
1200 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1201 SmallVector<Type *, 4> NewFuncParamTys;
1202 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1203 Type *ParamTy = FTy->getParamType(i);
1204 if (i == GVCstArgIdx) {
1205 Type *EleTy = ParamTy->getPointerElementType();
1206 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1207 }
1208
1209 NewFuncParamTys.push_back(ParamTy);
1210 }
1211
1212 FunctionType *NewFTy =
1213 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1214 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1215 FTy = NewFTy;
1216 }
1217
1218 FindType(FTy);
1219 } else {
1220 // As kernel functions do not have parameters, create new function type and
1221 // add it to type map.
1222 SmallVector<Type *, 4> NewFuncParamTys;
1223 FunctionType *NewFTy =
1224 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1225 FindType(NewFTy);
1226 }
1227
1228 // Investigate instructions' type in function body.
1229 for (BasicBlock &BB : F) {
1230 for (Instruction &I : BB) {
1231 if (isa<ShuffleVectorInst>(I)) {
1232 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1233 // Ignore type for mask of shuffle vector instruction.
1234 if (i == 2) {
1235 continue;
1236 }
1237
1238 Value *Op = I.getOperand(i);
1239 if (!isa<MetadataAsValue>(Op)) {
1240 FindType(Op->getType());
1241 }
1242 }
1243
1244 FindType(I.getType());
1245 continue;
1246 }
1247
David Neto862b7d82018-06-14 18:48:37 -04001248 CallInst *Call = dyn_cast<CallInst>(&I);
1249
1250 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001251 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001252 // This is a fake call representing access to a resource variable.
1253 // We handle that elsewhere.
1254 continue;
1255 }
1256
Alan Baker202c8c72018-08-13 13:47:44 -04001257 if (Call && Call->getCalledFunction()->getName().startswith(
1258 clspv::WorkgroupAccessorFunction())) {
1259 // This is a fake call representing access to a workgroup variable.
1260 // We handle that elsewhere.
1261 continue;
1262 }
1263
David Neto22f144c2017-06-12 14:26:21 -04001264 // Work through the operands of the instruction.
1265 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1266 Value *const Op = I.getOperand(i);
1267 // If any of the operands is a constant, find the type!
1268 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1269 FindType(Op->getType());
1270 }
1271 }
1272
1273 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001274 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001275 // Avoid to check call instruction's type.
1276 break;
1277 }
Alan Baker202c8c72018-08-13 13:47:44 -04001278 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1279 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1280 clspv::WorkgroupAccessorFunction())) {
1281 // This is a fake call representing access to a workgroup variable.
1282 // We handle that elsewhere.
1283 continue;
1284 }
1285 }
David Neto22f144c2017-06-12 14:26:21 -04001286 if (!isa<MetadataAsValue>(&Op)) {
1287 FindType(Op->getType());
1288 continue;
1289 }
1290 }
1291
David Neto22f144c2017-06-12 14:26:21 -04001292 // We don't want to track the type of this call as we are going to replace
1293 // it.
David Neto862b7d82018-06-14 18:48:37 -04001294 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001295 Call->getCalledFunction()->getName())) {
1296 continue;
1297 }
1298
1299 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1300 // If gep's base operand has ModuleScopePrivate address space, make gep
1301 // return ModuleScopePrivate address space.
1302 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1303 // Add pointer type with private address space for global constant to
1304 // type list.
1305 Type *EleTy = I.getType()->getPointerElementType();
1306 Type *NewPTy =
1307 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1308
1309 FindType(NewPTy);
1310 continue;
1311 }
1312 }
1313
1314 FindType(I.getType());
1315 }
1316 }
1317}
1318
David Neto862b7d82018-06-14 18:48:37 -04001319void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1320 // If we are using a sampler map, find the type of the sampler.
1321 if (M.getFunction("clspv.sampler.var.literal") ||
1322 0 < getSamplerMap().size()) {
1323 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1324 if (!SamplerStructTy) {
1325 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1326 }
1327
1328 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1329
1330 FindType(SamplerTy);
1331 }
1332}
1333
1334void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1335 // Record types so they are generated.
1336 TypesNeedingLayout.reset();
1337 StructTypesNeedingBlock.reset();
1338
1339 // To match older clspv codegen, generate the float type first if required
1340 // for images.
1341 for (const auto *info : ModuleOrderedResourceVars) {
1342 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1343 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1344 // We need "float" for the sampled component type.
1345 FindType(Type::getFloatTy(M.getContext()));
1346 // We only need to find it once.
1347 break;
1348 }
1349 }
1350
1351 for (const auto *info : ModuleOrderedResourceVars) {
1352 Type *type = info->var_fn->getReturnType();
1353
1354 switch (info->arg_kind) {
1355 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001356 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001357 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1358 StructTypesNeedingBlock.insert(sty);
1359 } else {
1360 errs() << *type << "\n";
1361 llvm_unreachable("Buffer arguments must map to structures!");
1362 }
1363 break;
1364 case clspv::ArgKind::Pod:
1365 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1366 StructTypesNeedingBlock.insert(sty);
1367 } else {
1368 errs() << *type << "\n";
1369 llvm_unreachable("POD arguments must map to structures!");
1370 }
1371 break;
1372 case clspv::ArgKind::ReadOnlyImage:
1373 case clspv::ArgKind::WriteOnlyImage:
1374 case clspv::ArgKind::Sampler:
1375 // Sampler and image types map to the pointee type but
1376 // in the uniform constant address space.
1377 type = PointerType::get(type->getPointerElementType(),
1378 clspv::AddressSpace::UniformConstant);
1379 break;
1380 default:
1381 break;
1382 }
1383
1384 // The converted type is the type of the OpVariable we will generate.
1385 // If the pointee type is an array of size zero, FindType will convert it
1386 // to a runtime array.
1387 FindType(type);
1388 }
1389
1390 // Traverse the arrays and structures underneath each Block, and
1391 // mark them as needing layout.
1392 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1393 StructTypesNeedingBlock.end());
1394 while (!work_list.empty()) {
1395 Type *type = work_list.back();
1396 work_list.pop_back();
1397 TypesNeedingLayout.insert(type);
1398 switch (type->getTypeID()) {
1399 case Type::ArrayTyID:
1400 work_list.push_back(type->getArrayElementType());
1401 if (!Hack_generate_runtime_array_stride_early) {
1402 // Remember this array type for deferred decoration.
1403 TypesNeedingArrayStride.insert(type);
1404 }
1405 break;
1406 case Type::StructTyID:
1407 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1408 work_list.push_back(elem_ty);
1409 }
1410 default:
1411 // This type and its contained types don't get layout.
1412 break;
1413 }
1414 }
1415}
1416
Alan Baker202c8c72018-08-13 13:47:44 -04001417void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1418 // The SpecId assignment for pointer-to-local arguments is recorded in
1419 // module-level metadata. Translate that information into local argument
1420 // information.
1421 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001422 if (!nmd)
1423 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001424 for (auto operand : nmd->operands()) {
1425 MDTuple *tuple = cast<MDTuple>(operand);
1426 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1427 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001428 ConstantAsMetadata *arg_index_md =
1429 cast<ConstantAsMetadata>(tuple->getOperand(1));
1430 int arg_index = static_cast<int>(
1431 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1432 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001433
1434 ConstantAsMetadata *spec_id_md =
1435 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001436 int spec_id = static_cast<int>(
1437 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001438
1439 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1440 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001441 if (LocalSpecIdInfoMap.count(spec_id))
1442 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001443
1444 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1445 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1446 nextID + 1, nextID + 2,
1447 nextID + 3, spec_id};
1448 LocalSpecIdInfoMap[spec_id] = info;
1449 nextID += 4;
1450
1451 // Ensure the types necessary for this argument get generated.
1452 Type *IdxTy = Type::getInt32Ty(M.getContext());
1453 FindConstant(ConstantInt::get(IdxTy, 0));
1454 FindType(IdxTy);
1455 FindType(arg->getType());
1456 }
1457}
1458
David Neto22f144c2017-06-12 14:26:21 -04001459void SPIRVProducerPass::FindType(Type *Ty) {
1460 TypeList &TyList = getTypeList();
1461
1462 if (0 != TyList.idFor(Ty)) {
1463 return;
1464 }
1465
1466 if (Ty->isPointerTy()) {
1467 auto AddrSpace = Ty->getPointerAddressSpace();
1468 if ((AddressSpace::Constant == AddrSpace) ||
1469 (AddressSpace::Global == AddrSpace)) {
1470 auto PointeeTy = Ty->getPointerElementType();
1471
1472 if (PointeeTy->isStructTy() &&
1473 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1474 FindType(PointeeTy);
1475 auto ActualPointerTy =
1476 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1477 FindType(ActualPointerTy);
1478 return;
1479 }
1480 }
1481 }
1482
David Neto862b7d82018-06-14 18:48:37 -04001483 // By convention, LLVM array type with 0 elements will map to
1484 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1485 // has a constant number of elements. We need to support type of the
1486 // constant.
1487 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1488 if (arrayTy->getNumElements() > 0) {
1489 LLVMContext &Context = Ty->getContext();
1490 FindType(Type::getInt32Ty(Context));
1491 }
David Neto22f144c2017-06-12 14:26:21 -04001492 }
1493
1494 for (Type *SubTy : Ty->subtypes()) {
1495 FindType(SubTy);
1496 }
1497
1498 TyList.insert(Ty);
1499}
1500
1501void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1502 // If the global variable has a (non undef) initializer.
1503 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001504 // Generate the constant if it's not the initializer to a module scope
1505 // constant that we will expect in a storage buffer.
1506 const bool module_scope_constant_external_init =
1507 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1508 clspv::Option::ModuleConstantsInStorageBuffer();
1509 if (!module_scope_constant_external_init) {
1510 FindConstant(GV.getInitializer());
1511 }
David Neto22f144c2017-06-12 14:26:21 -04001512 }
1513}
1514
1515void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1516 // Investigate constants in function body.
1517 for (BasicBlock &BB : F) {
1518 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001519 if (auto *call = dyn_cast<CallInst>(&I)) {
1520 auto name = call->getCalledFunction()->getName();
1521 if (name == "clspv.sampler.var.literal") {
1522 // We've handled these constants elsewhere, so skip it.
1523 continue;
1524 }
Alan Baker202c8c72018-08-13 13:47:44 -04001525 if (name.startswith(clspv::ResourceAccessorFunction())) {
1526 continue;
1527 }
1528 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001529 continue;
1530 }
David Neto22f144c2017-06-12 14:26:21 -04001531 }
1532
1533 if (isa<AllocaInst>(I)) {
1534 // Alloca instruction has constant for the number of element. Ignore it.
1535 continue;
1536 } else if (isa<ShuffleVectorInst>(I)) {
1537 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1538 // Ignore constant for mask of shuffle vector instruction.
1539 if (i == 2) {
1540 continue;
1541 }
1542
1543 if (isa<Constant>(I.getOperand(i)) &&
1544 !isa<GlobalValue>(I.getOperand(i))) {
1545 FindConstant(I.getOperand(i));
1546 }
1547 }
1548
1549 continue;
1550 } else if (isa<InsertElementInst>(I)) {
1551 // Handle InsertElement with <4 x i8> specially.
1552 Type *CompositeTy = I.getOperand(0)->getType();
1553 if (is4xi8vec(CompositeTy)) {
1554 LLVMContext &Context = CompositeTy->getContext();
1555 if (isa<Constant>(I.getOperand(0))) {
1556 FindConstant(I.getOperand(0));
1557 }
1558
1559 if (isa<Constant>(I.getOperand(1))) {
1560 FindConstant(I.getOperand(1));
1561 }
1562
1563 // Add mask constant 0xFF.
1564 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1565 FindConstant(CstFF);
1566
1567 // Add shift amount constant.
1568 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1569 uint64_t Idx = CI->getZExtValue();
1570 Constant *CstShiftAmount =
1571 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1572 FindConstant(CstShiftAmount);
1573 }
1574
1575 continue;
1576 }
1577
1578 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1579 // Ignore constant for index of InsertElement instruction.
1580 if (i == 2) {
1581 continue;
1582 }
1583
1584 if (isa<Constant>(I.getOperand(i)) &&
1585 !isa<GlobalValue>(I.getOperand(i))) {
1586 FindConstant(I.getOperand(i));
1587 }
1588 }
1589
1590 continue;
1591 } else if (isa<ExtractElementInst>(I)) {
1592 // Handle ExtractElement with <4 x i8> specially.
1593 Type *CompositeTy = I.getOperand(0)->getType();
1594 if (is4xi8vec(CompositeTy)) {
1595 LLVMContext &Context = CompositeTy->getContext();
1596 if (isa<Constant>(I.getOperand(0))) {
1597 FindConstant(I.getOperand(0));
1598 }
1599
1600 // Add mask constant 0xFF.
1601 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1602 FindConstant(CstFF);
1603
1604 // Add shift amount constant.
1605 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1606 uint64_t Idx = CI->getZExtValue();
1607 Constant *CstShiftAmount =
1608 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1609 FindConstant(CstShiftAmount);
1610 } else {
1611 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1612 FindConstant(Cst8);
1613 }
1614
1615 continue;
1616 }
1617
1618 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1619 // Ignore constant for index of ExtractElement instruction.
1620 if (i == 1) {
1621 continue;
1622 }
1623
1624 if (isa<Constant>(I.getOperand(i)) &&
1625 !isa<GlobalValue>(I.getOperand(i))) {
1626 FindConstant(I.getOperand(i));
1627 }
1628 }
1629
1630 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001631 } else if ((Instruction::Xor == I.getOpcode()) &&
1632 I.getType()->isIntegerTy(1)) {
1633 // We special case for Xor where the type is i1 and one of the arguments
1634 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1635 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001636 bool foundConstantTrue = false;
1637 for (Use &Op : I.operands()) {
1638 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1639 auto CI = cast<ConstantInt>(Op);
1640
1641 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001642 // If we already found the true constant, we might (probably only
1643 // on -O0) have an OpLogicalNot which is taking a constant
1644 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001645 FindConstant(Op);
1646 } else {
1647 foundConstantTrue = true;
1648 }
1649 }
1650 }
1651
1652 continue;
David Netod2de94a2017-08-28 17:27:47 -04001653 } else if (isa<TruncInst>(I)) {
1654 // For truncation to i8 we mask against 255.
1655 Type *ToTy = I.getType();
1656 if (8u == ToTy->getPrimitiveSizeInBits()) {
1657 LLVMContext &Context = ToTy->getContext();
1658 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1659 FindConstant(Cst255);
1660 }
1661 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001662 } else if (isa<AtomicRMWInst>(I)) {
1663 LLVMContext &Context = I.getContext();
1664
1665 FindConstant(
1666 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1667 FindConstant(ConstantInt::get(
1668 Type::getInt32Ty(Context),
1669 spv::MemorySemanticsUniformMemoryMask |
1670 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001671 }
1672
1673 for (Use &Op : I.operands()) {
1674 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1675 FindConstant(Op);
1676 }
1677 }
1678 }
1679 }
1680}
1681
1682void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001683 ValueList &CstList = getConstantList();
1684
David Netofb9a7972017-08-25 17:08:24 -04001685 // If V is already tracked, ignore it.
1686 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001687 return;
1688 }
1689
David Neto862b7d82018-06-14 18:48:37 -04001690 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1691 return;
1692 }
1693
David Neto22f144c2017-06-12 14:26:21 -04001694 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001695 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001696
1697 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001698 if (is4xi8vec(CstTy)) {
1699 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001700 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001701 }
1702 }
1703
1704 if (Cst->getNumOperands()) {
1705 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1706 ++I) {
1707 FindConstant(*I);
1708 }
1709
David Netofb9a7972017-08-25 17:08:24 -04001710 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001711 return;
1712 } else if (const ConstantDataSequential *CDS =
1713 dyn_cast<ConstantDataSequential>(Cst)) {
1714 // Add constants for each element to constant list.
1715 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1716 Constant *EleCst = CDS->getElementAsConstant(i);
1717 FindConstant(EleCst);
1718 }
1719 }
1720
1721 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001722 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001723 }
1724}
1725
1726spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1727 switch (AddrSpace) {
1728 default:
1729 llvm_unreachable("Unsupported OpenCL address space");
1730 case AddressSpace::Private:
1731 return spv::StorageClassFunction;
1732 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001733 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001734 case AddressSpace::Constant:
1735 return clspv::Option::ConstantArgsInUniformBuffer()
1736 ? spv::StorageClassUniform
1737 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001738 case AddressSpace::Input:
1739 return spv::StorageClassInput;
1740 case AddressSpace::Local:
1741 return spv::StorageClassWorkgroup;
1742 case AddressSpace::UniformConstant:
1743 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001744 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001745 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001746 case AddressSpace::ModuleScopePrivate:
1747 return spv::StorageClassPrivate;
1748 }
1749}
1750
David Neto862b7d82018-06-14 18:48:37 -04001751spv::StorageClass
1752SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1753 switch (arg_kind) {
1754 case clspv::ArgKind::Buffer:
1755 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001756 case clspv::ArgKind::BufferUBO:
1757 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001758 case clspv::ArgKind::Pod:
1759 return clspv::Option::PodArgsInUniformBuffer()
1760 ? spv::StorageClassUniform
1761 : spv::StorageClassStorageBuffer;
1762 case clspv::ArgKind::Local:
1763 return spv::StorageClassWorkgroup;
1764 case clspv::ArgKind::ReadOnlyImage:
1765 case clspv::ArgKind::WriteOnlyImage:
1766 case clspv::ArgKind::Sampler:
1767 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001768 default:
1769 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001770 }
1771}
1772
David Neto22f144c2017-06-12 14:26:21 -04001773spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1774 return StringSwitch<spv::BuiltIn>(Name)
1775 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1776 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1777 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1778 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1779 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1780 .Default(spv::BuiltInMax);
1781}
1782
1783void SPIRVProducerPass::GenerateExtInstImport() {
1784 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1785 uint32_t &ExtInstImportID = getOpExtInstImportID();
1786
1787 //
1788 // Generate OpExtInstImport.
1789 //
1790 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001791 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001792 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1793 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001794}
1795
alan-bakerb6b09dc2018-11-08 16:59:28 -05001796void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1797 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001798 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1799 ValueMapType &VMap = getValueMap();
1800 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001801 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001802
1803 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1804 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1805 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1806
1807 for (Type *Ty : getTypeList()) {
1808 // Update TypeMap with nextID for reference later.
1809 TypeMap[Ty] = nextID;
1810
1811 switch (Ty->getTypeID()) {
1812 default: {
1813 Ty->print(errs());
1814 llvm_unreachable("Unsupported type???");
1815 break;
1816 }
1817 case Type::MetadataTyID:
1818 case Type::LabelTyID: {
1819 // Ignore these types.
1820 break;
1821 }
1822 case Type::PointerTyID: {
1823 PointerType *PTy = cast<PointerType>(Ty);
1824 unsigned AddrSpace = PTy->getAddressSpace();
1825
1826 // For the purposes of our Vulkan SPIR-V type system, constant and global
1827 // are conflated.
1828 bool UseExistingOpTypePointer = false;
1829 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001830 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1831 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001832 // Check to see if we already created this type (for instance, if we
1833 // had a constant <type>* and a global <type>*, the type would be
1834 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001835 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1836 if (0 < TypeMap.count(GlobalTy)) {
1837 TypeMap[PTy] = TypeMap[GlobalTy];
1838 UseExistingOpTypePointer = true;
1839 break;
1840 }
David Neto22f144c2017-06-12 14:26:21 -04001841 }
1842 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001843 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1844 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001845
alan-bakerb6b09dc2018-11-08 16:59:28 -05001846 // Check to see if we already created this type (for instance, if we
1847 // had a constant <type>* and a global <type>*, the type would be
1848 // created by one of these types, and shared by both).
1849 auto ConstantTy =
1850 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001851 if (0 < TypeMap.count(ConstantTy)) {
1852 TypeMap[PTy] = TypeMap[ConstantTy];
1853 UseExistingOpTypePointer = true;
1854 }
David Neto22f144c2017-06-12 14:26:21 -04001855 }
1856 }
1857
David Neto862b7d82018-06-14 18:48:37 -04001858 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001859
David Neto862b7d82018-06-14 18:48:37 -04001860 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001861 //
1862 // Generate OpTypePointer.
1863 //
1864
1865 // OpTypePointer
1866 // Ops[0] = Storage Class
1867 // Ops[1] = Element Type ID
1868 SPIRVOperandList Ops;
1869
David Neto257c3892018-04-11 13:19:45 -04001870 Ops << MkNum(GetStorageClass(AddrSpace))
1871 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001872
David Neto87846742018-04-11 17:36:22 -04001873 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001874 SPIRVInstList.push_back(Inst);
1875 }
David Neto22f144c2017-06-12 14:26:21 -04001876 break;
1877 }
1878 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001879 StructType *STy = cast<StructType>(Ty);
1880
1881 // Handle sampler type.
1882 if (STy->isOpaque()) {
1883 if (STy->getName().equals("opencl.sampler_t")) {
1884 //
1885 // Generate OpTypeSampler
1886 //
1887 // Empty Ops.
1888 SPIRVOperandList Ops;
1889
David Neto87846742018-04-11 17:36:22 -04001890 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001891 SPIRVInstList.push_back(Inst);
1892 break;
1893 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1894 STy->getName().equals("opencl.image2d_wo_t") ||
1895 STy->getName().equals("opencl.image3d_ro_t") ||
1896 STy->getName().equals("opencl.image3d_wo_t")) {
1897 //
1898 // Generate OpTypeImage
1899 //
1900 // Ops[0] = Sampled Type ID
1901 // Ops[1] = Dim ID
1902 // Ops[2] = Depth (Literal Number)
1903 // Ops[3] = Arrayed (Literal Number)
1904 // Ops[4] = MS (Literal Number)
1905 // Ops[5] = Sampled (Literal Number)
1906 // Ops[6] = Image Format ID
1907 //
1908 SPIRVOperandList Ops;
1909
1910 // TODO: Changed Sampled Type according to situations.
1911 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001912 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001913
1914 spv::Dim DimID = spv::Dim2D;
1915 if (STy->getName().equals("opencl.image3d_ro_t") ||
1916 STy->getName().equals("opencl.image3d_wo_t")) {
1917 DimID = spv::Dim3D;
1918 }
David Neto257c3892018-04-11 13:19:45 -04001919 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001920
1921 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001922 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001923
1924 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001925 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001926
1927 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001928 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001929
1930 // TODO: Set up Sampled.
1931 //
1932 // From Spec
1933 //
1934 // 0 indicates this is only known at run time, not at compile time
1935 // 1 indicates will be used with sampler
1936 // 2 indicates will be used without a sampler (a storage image)
1937 uint32_t Sampled = 1;
1938 if (STy->getName().equals("opencl.image2d_wo_t") ||
1939 STy->getName().equals("opencl.image3d_wo_t")) {
1940 Sampled = 2;
1941 }
David Neto257c3892018-04-11 13:19:45 -04001942 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001943
1944 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001945 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001946
David Neto87846742018-04-11 17:36:22 -04001947 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001948 SPIRVInstList.push_back(Inst);
1949 break;
1950 }
1951 }
1952
1953 //
1954 // Generate OpTypeStruct
1955 //
1956 // Ops[0] ... Ops[n] = Member IDs
1957 SPIRVOperandList Ops;
1958
1959 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001960 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001961 }
1962
David Neto22f144c2017-06-12 14:26:21 -04001963 uint32_t STyID = nextID;
1964
alan-bakerb6b09dc2018-11-08 16:59:28 -05001965 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001966 SPIRVInstList.push_back(Inst);
1967
1968 // Generate OpMemberDecorate.
1969 auto DecoInsertPoint =
1970 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1971 [](SPIRVInstruction *Inst) -> bool {
1972 return Inst->getOpcode() != spv::OpDecorate &&
1973 Inst->getOpcode() != spv::OpMemberDecorate &&
1974 Inst->getOpcode() != spv::OpExtInstImport;
1975 });
1976
David Netoc463b372017-08-10 15:32:21 -04001977 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001978 // Search for the correct offsets if this type was remapped.
1979 std::vector<uint32_t> *offsets = nullptr;
1980 auto iter = RemappedUBOTypeOffsets.find(STy);
1981 if (iter != RemappedUBOTypeOffsets.end()) {
1982 offsets = &iter->second;
1983 }
David Netoc463b372017-08-10 15:32:21 -04001984
David Neto862b7d82018-06-14 18:48:37 -04001985 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001986 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1987 MemberIdx++) {
1988 // Ops[0] = Structure Type ID
1989 // Ops[1] = Member Index(Literal Number)
1990 // Ops[2] = Decoration (Offset)
1991 // Ops[3] = Byte Offset (Literal Number)
1992 Ops.clear();
1993
David Neto257c3892018-04-11 13:19:45 -04001994 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001995
alan-bakerb6b09dc2018-11-08 16:59:28 -05001996 auto ByteOffset =
1997 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001998 if (offsets) {
1999 ByteOffset = (*offsets)[MemberIdx];
2000 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002001 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002002 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002003 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002004
David Neto87846742018-04-11 17:36:22 -04002005 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002006 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002007 }
2008
2009 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002010 if (StructTypesNeedingBlock.idFor(STy)) {
2011 Ops.clear();
2012 // Use Block decorations with StorageBuffer storage class.
2013 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002014
David Neto862b7d82018-06-14 18:48:37 -04002015 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2016 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002017 }
2018 break;
2019 }
2020 case Type::IntegerTyID: {
2021 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2022
2023 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002024 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002025 SPIRVInstList.push_back(Inst);
2026 } else {
2027 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002028 // No matter what LLVM type is requested first, always alias the
2029 // second one's SPIR-V type to be the same as the one we generated
2030 // first.
Neil Henning39672102017-09-29 14:33:13 +01002031 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002032 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002033 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002034 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002035 } else if (BitWidth == 32) {
2036 aliasToWidth = 8;
2037 }
2038 if (aliasToWidth) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002039 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
David Neto391aeb12017-08-26 15:51:58 -04002040 auto where = TypeMap.find(otherType);
2041 if (where == TypeMap.end()) {
2042 // Go ahead and make it, but also map the other type to it.
2043 TypeMap[otherType] = nextID;
2044 } else {
2045 // Alias this SPIR-V type the existing type.
2046 TypeMap[Ty] = where->second;
2047 break;
2048 }
David Neto22f144c2017-06-12 14:26:21 -04002049 }
2050
David Neto257c3892018-04-11 13:19:45 -04002051 SPIRVOperandList Ops;
2052 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002053
2054 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002055 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002056 }
2057 break;
2058 }
2059 case Type::HalfTyID:
2060 case Type::FloatTyID:
2061 case Type::DoubleTyID: {
2062 SPIRVOperand *WidthOp = new SPIRVOperand(
2063 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2064
2065 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002066 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002067 break;
2068 }
2069 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002070 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002071 const uint64_t Length = ArrTy->getArrayNumElements();
2072 if (Length == 0) {
2073 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002074
David Neto862b7d82018-06-14 18:48:37 -04002075 // Only generate the type once.
2076 // TODO(dneto): Can it ever be generated more than once?
2077 // Doesn't LLVM type uniqueness guarantee we'll only see this
2078 // once?
2079 Type *EleTy = ArrTy->getArrayElementType();
2080 if (OpRuntimeTyMap.count(EleTy) == 0) {
2081 uint32_t OpTypeRuntimeArrayID = nextID;
2082 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002083
David Neto862b7d82018-06-14 18:48:37 -04002084 //
2085 // Generate OpTypeRuntimeArray.
2086 //
David Neto22f144c2017-06-12 14:26:21 -04002087
David Neto862b7d82018-06-14 18:48:37 -04002088 // OpTypeRuntimeArray
2089 // Ops[0] = Element Type ID
2090 SPIRVOperandList Ops;
2091 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002092
David Neto862b7d82018-06-14 18:48:37 -04002093 SPIRVInstList.push_back(
2094 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002095
David Neto862b7d82018-06-14 18:48:37 -04002096 if (Hack_generate_runtime_array_stride_early) {
2097 // Generate OpDecorate.
2098 auto DecoInsertPoint = std::find_if(
2099 SPIRVInstList.begin(), SPIRVInstList.end(),
2100 [](SPIRVInstruction *Inst) -> bool {
2101 return Inst->getOpcode() != spv::OpDecorate &&
2102 Inst->getOpcode() != spv::OpMemberDecorate &&
2103 Inst->getOpcode() != spv::OpExtInstImport;
2104 });
David Neto22f144c2017-06-12 14:26:21 -04002105
David Neto862b7d82018-06-14 18:48:37 -04002106 // Ops[0] = Target ID
2107 // Ops[1] = Decoration (ArrayStride)
2108 // Ops[2] = Stride Number(Literal Number)
2109 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002110
David Neto862b7d82018-06-14 18:48:37 -04002111 Ops << MkId(OpTypeRuntimeArrayID)
2112 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002113 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002114
David Neto862b7d82018-06-14 18:48:37 -04002115 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2116 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2117 }
2118 }
David Neto22f144c2017-06-12 14:26:21 -04002119
David Neto862b7d82018-06-14 18:48:37 -04002120 } else {
David Neto22f144c2017-06-12 14:26:21 -04002121
David Neto862b7d82018-06-14 18:48:37 -04002122 //
2123 // Generate OpConstant and OpTypeArray.
2124 //
2125
2126 //
2127 // Generate OpConstant for array length.
2128 //
2129 // Ops[0] = Result Type ID
2130 // Ops[1] .. Ops[n] = Values LiteralNumber
2131 SPIRVOperandList Ops;
2132
2133 Type *LengthTy = Type::getInt32Ty(Context);
2134 uint32_t ResTyID = lookupType(LengthTy);
2135 Ops << MkId(ResTyID);
2136
2137 assert(Length < UINT32_MAX);
2138 Ops << MkNum(static_cast<uint32_t>(Length));
2139
2140 // Add constant for length to constant list.
2141 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2142 AllocatedVMap[CstLength] = nextID;
2143 VMap[CstLength] = nextID;
2144 uint32_t LengthID = nextID;
2145
2146 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2147 SPIRVInstList.push_back(CstInst);
2148
2149 // Remember to generate ArrayStride later
2150 getTypesNeedingArrayStride().insert(Ty);
2151
2152 //
2153 // Generate OpTypeArray.
2154 //
2155 // Ops[0] = Element Type ID
2156 // Ops[1] = Array Length Constant ID
2157 Ops.clear();
2158
2159 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2160 Ops << MkId(EleTyID) << MkId(LengthID);
2161
2162 // Update TypeMap with nextID.
2163 TypeMap[Ty] = nextID;
2164
2165 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2166 SPIRVInstList.push_back(ArrayInst);
2167 }
David Neto22f144c2017-06-12 14:26:21 -04002168 break;
2169 }
2170 case Type::VectorTyID: {
2171 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002172 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2173 if (Ty->getVectorNumElements() == 4) {
2174 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2175 break;
2176 } else {
2177 Ty->print(errs());
2178 llvm_unreachable("Support above i8 vector type");
2179 }
2180 }
2181
2182 // Ops[0] = Component Type ID
2183 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002184 SPIRVOperandList Ops;
2185 Ops << MkId(lookupType(Ty->getVectorElementType()))
2186 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002187
alan-bakerb6b09dc2018-11-08 16:59:28 -05002188 SPIRVInstruction *inst =
2189 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002190 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002191 break;
2192 }
2193 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002194 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002195 SPIRVInstList.push_back(Inst);
2196 break;
2197 }
2198 case Type::FunctionTyID: {
2199 // Generate SPIRV instruction for function type.
2200 FunctionType *FTy = cast<FunctionType>(Ty);
2201
2202 // Ops[0] = Return Type ID
2203 // Ops[1] ... Ops[n] = Parameter Type IDs
2204 SPIRVOperandList Ops;
2205
2206 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002207 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002208
2209 // Find SPIRV instructions for parameter types
2210 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2211 // Find SPIRV instruction for parameter type.
2212 auto ParamTy = FTy->getParamType(k);
2213 if (ParamTy->isPointerTy()) {
2214 auto PointeeTy = ParamTy->getPointerElementType();
2215 if (PointeeTy->isStructTy() &&
2216 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2217 ParamTy = PointeeTy;
2218 }
2219 }
2220
David Netoc6f3ab22018-04-06 18:02:31 -04002221 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002222 }
2223
David Neto87846742018-04-11 17:36:22 -04002224 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002225 SPIRVInstList.push_back(Inst);
2226 break;
2227 }
2228 }
2229 }
2230
2231 // Generate OpTypeSampledImage.
2232 TypeMapType &OpImageTypeMap = getImageTypeMap();
2233 for (auto &ImageType : OpImageTypeMap) {
2234 //
2235 // Generate OpTypeSampledImage.
2236 //
2237 // Ops[0] = Image Type ID
2238 //
2239 SPIRVOperandList Ops;
2240
2241 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002242 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002243
2244 // Update OpImageTypeMap.
2245 ImageType.second = nextID;
2246
David Neto87846742018-04-11 17:36:22 -04002247 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002248 SPIRVInstList.push_back(Inst);
2249 }
David Netoc6f3ab22018-04-06 18:02:31 -04002250
2251 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002252 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2253 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002254 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002255
2256 // Generate the spec constant.
2257 SPIRVOperandList Ops;
2258 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002259 SPIRVInstList.push_back(
2260 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002261
2262 // Generate the array type.
2263 Ops.clear();
2264 // The element type must have been created.
2265 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2266 assert(elem_ty_id);
2267 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2268
2269 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002270 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002271
2272 Ops.clear();
2273 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002274 SPIRVInstList.push_back(new SPIRVInstruction(
2275 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002276 }
David Neto22f144c2017-06-12 14:26:21 -04002277}
2278
2279void SPIRVProducerPass::GenerateSPIRVConstants() {
2280 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2281 ValueMapType &VMap = getValueMap();
2282 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2283 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002284 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002285
2286 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002287 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002288 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002289
2290 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002291 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002292 continue;
2293 }
2294
David Netofb9a7972017-08-25 17:08:24 -04002295 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002296 VMap[Cst] = nextID;
2297
2298 //
2299 // Generate OpConstant.
2300 //
2301
2302 // Ops[0] = Result Type ID
2303 // Ops[1] .. Ops[n] = Values LiteralNumber
2304 SPIRVOperandList Ops;
2305
David Neto257c3892018-04-11 13:19:45 -04002306 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002307
2308 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002309 spv::Op Opcode = spv::OpNop;
2310
2311 if (isa<UndefValue>(Cst)) {
2312 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002313 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002314 if (hack_undef && IsTypeNullable(Cst->getType())) {
2315 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002316 }
David Neto22f144c2017-06-12 14:26:21 -04002317 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2318 unsigned BitWidth = CI->getBitWidth();
2319 if (BitWidth == 1) {
2320 // If the bitwidth of constant is 1, generate OpConstantTrue or
2321 // OpConstantFalse.
2322 if (CI->getZExtValue()) {
2323 // Ops[0] = Result Type ID
2324 Opcode = spv::OpConstantTrue;
2325 } else {
2326 // Ops[0] = Result Type ID
2327 Opcode = spv::OpConstantFalse;
2328 }
David Neto22f144c2017-06-12 14:26:21 -04002329 } else {
2330 auto V = CI->getZExtValue();
2331 LiteralNum.push_back(V & 0xFFFFFFFF);
2332
2333 if (BitWidth > 32) {
2334 LiteralNum.push_back(V >> 32);
2335 }
2336
2337 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002338
David Neto257c3892018-04-11 13:19:45 -04002339 Ops << MkInteger(LiteralNum);
2340
2341 if (BitWidth == 32 && V == 0) {
2342 constant_i32_zero_id_ = nextID;
2343 }
David Neto22f144c2017-06-12 14:26:21 -04002344 }
2345 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2346 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2347 Type *CFPTy = CFP->getType();
2348 if (CFPTy->isFloatTy()) {
2349 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2350 } else {
2351 CFPTy->print(errs());
2352 llvm_unreachable("Implement this ConstantFP Type");
2353 }
2354
2355 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002356
David Neto257c3892018-04-11 13:19:45 -04002357 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002358 } else if (isa<ConstantDataSequential>(Cst) &&
2359 cast<ConstantDataSequential>(Cst)->isString()) {
2360 Cst->print(errs());
2361 llvm_unreachable("Implement this Constant");
2362
2363 } else if (const ConstantDataSequential *CDS =
2364 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002365 // Let's convert <4 x i8> constant to int constant specially.
2366 // This case occurs when all the values are specified as constant
2367 // ints.
2368 Type *CstTy = Cst->getType();
2369 if (is4xi8vec(CstTy)) {
2370 LLVMContext &Context = CstTy->getContext();
2371
2372 //
2373 // Generate OpConstant with OpTypeInt 32 0.
2374 //
Neil Henning39672102017-09-29 14:33:13 +01002375 uint32_t IntValue = 0;
2376 for (unsigned k = 0; k < 4; k++) {
2377 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002378 IntValue = (IntValue << 8) | (Val & 0xffu);
2379 }
2380
2381 Type *i32 = Type::getInt32Ty(Context);
2382 Constant *CstInt = ConstantInt::get(i32, IntValue);
2383 // If this constant is already registered on VMap, use it.
2384 if (VMap.count(CstInt)) {
2385 uint32_t CstID = VMap[CstInt];
2386 VMap[Cst] = CstID;
2387 continue;
2388 }
2389
David Neto257c3892018-04-11 13:19:45 -04002390 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002391
David Neto87846742018-04-11 17:36:22 -04002392 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002393 SPIRVInstList.push_back(CstInst);
2394
2395 continue;
2396 }
2397
2398 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002399 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2400 Constant *EleCst = CDS->getElementAsConstant(k);
2401 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002402 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002403 }
2404
2405 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002406 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2407 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002408 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002409 Type *CstTy = Cst->getType();
2410 if (is4xi8vec(CstTy)) {
2411 LLVMContext &Context = CstTy->getContext();
2412
2413 //
2414 // Generate OpConstant with OpTypeInt 32 0.
2415 //
Neil Henning39672102017-09-29 14:33:13 +01002416 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002417 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2418 I != E; ++I) {
2419 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002420 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002421 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2422 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002423 }
David Neto49351ac2017-08-26 17:32:20 -04002424 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002425 }
2426
David Neto49351ac2017-08-26 17:32:20 -04002427 Type *i32 = Type::getInt32Ty(Context);
2428 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002429 // If this constant is already registered on VMap, use it.
2430 if (VMap.count(CstInt)) {
2431 uint32_t CstID = VMap[CstInt];
2432 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002433 continue;
David Neto22f144c2017-06-12 14:26:21 -04002434 }
2435
David Neto257c3892018-04-11 13:19:45 -04002436 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002437
David Neto87846742018-04-11 17:36:22 -04002438 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002439 SPIRVInstList.push_back(CstInst);
2440
David Neto19a1bad2017-08-25 15:01:41 -04002441 continue;
David Neto22f144c2017-06-12 14:26:21 -04002442 }
2443
2444 // We use a constant composite in SPIR-V for our constant aggregate in
2445 // LLVM.
2446 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002447
2448 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2449 // Look up the ID of the element of this aggregate (which we will
2450 // previously have created a constant for).
2451 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2452
2453 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002454 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002455 }
2456 } else if (Cst->isNullValue()) {
2457 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002458 } else {
2459 Cst->print(errs());
2460 llvm_unreachable("Unsupported Constant???");
2461 }
2462
David Neto87846742018-04-11 17:36:22 -04002463 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002464 SPIRVInstList.push_back(CstInst);
2465 }
2466}
2467
2468void SPIRVProducerPass::GenerateSamplers(Module &M) {
2469 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002470
alan-bakerb6b09dc2018-11-08 16:59:28 -05002471 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002472 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002473 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002474 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2475 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002476
David Neto862b7d82018-06-14 18:48:37 -04002477 // We might have samplers in the sampler map that are not used
2478 // in the translation unit. We need to allocate variables
2479 // for them and bindings too.
2480 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002481
alan-bakerb6b09dc2018-11-08 16:59:28 -05002482 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2483 if (!var_fn)
2484 return;
David Neto862b7d82018-06-14 18:48:37 -04002485 for (auto user : var_fn->users()) {
2486 // Populate SamplerLiteralToDescriptorSetMap and
2487 // SamplerLiteralToBindingMap.
2488 //
2489 // Look for calls like
2490 // call %opencl.sampler_t addrspace(2)*
2491 // @clspv.sampler.var.literal(
2492 // i32 descriptor,
2493 // i32 binding,
2494 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002495 if (auto *call = dyn_cast<CallInst>(user)) {
2496 const size_t index_into_sampler_map = static_cast<size_t>(
2497 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002498 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002499 errs() << "Out of bounds index to sampler map: "
2500 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002501 llvm_unreachable("bad sampler init: out of bounds");
2502 }
2503
2504 auto sampler_value = sampler_map[index_into_sampler_map].first;
2505 const auto descriptor_set = static_cast<unsigned>(
2506 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2507 const auto binding = static_cast<unsigned>(
2508 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2509
2510 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2511 SamplerLiteralToBindingMap[sampler_value] = binding;
2512 used_bindings.insert(binding);
2513 }
2514 }
2515
2516 unsigned index = 0;
2517 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002518 // Generate OpVariable.
2519 //
2520 // GIDOps[0] : Result Type ID
2521 // GIDOps[1] : Storage Class
2522 SPIRVOperandList Ops;
2523
David Neto257c3892018-04-11 13:19:45 -04002524 Ops << MkId(lookupType(SamplerTy))
2525 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002526
David Neto862b7d82018-06-14 18:48:37 -04002527 auto sampler_var_id = nextID++;
2528 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002529 SPIRVInstList.push_back(Inst);
2530
David Neto862b7d82018-06-14 18:48:37 -04002531 SamplerMapIndexToIDMap[index] = sampler_var_id;
2532 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002533
2534 // Find Insert Point for OpDecorate.
2535 auto DecoInsertPoint =
2536 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2537 [](SPIRVInstruction *Inst) -> bool {
2538 return Inst->getOpcode() != spv::OpDecorate &&
2539 Inst->getOpcode() != spv::OpMemberDecorate &&
2540 Inst->getOpcode() != spv::OpExtInstImport;
2541 });
2542
2543 // Ops[0] = Target ID
2544 // Ops[1] = Decoration (DescriptorSet)
2545 // Ops[2] = LiteralNumber according to Decoration
2546 Ops.clear();
2547
David Neto862b7d82018-06-14 18:48:37 -04002548 unsigned descriptor_set;
2549 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002550 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2551 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002552 // This sampler is not actually used. Find the next one.
2553 for (binding = 0; used_bindings.count(binding); binding++)
2554 ;
2555 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2556 used_bindings.insert(binding);
2557 } else {
2558 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2559 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2560 }
2561
2562 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2563 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002564
David Neto44795152017-07-13 15:45:28 -04002565 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002566 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002567 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002568
David Neto87846742018-04-11 17:36:22 -04002569 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002570 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2571
2572 // Ops[0] = Target ID
2573 // Ops[1] = Decoration (Binding)
2574 // Ops[2] = LiteralNumber according to Decoration
2575 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002576 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2577 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002578
David Neto87846742018-04-11 17:36:22 -04002579 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002580 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002581
2582 index++;
David Neto22f144c2017-06-12 14:26:21 -04002583 }
David Neto862b7d82018-06-14 18:48:37 -04002584}
David Neto22f144c2017-06-12 14:26:21 -04002585
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002586void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002587 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2588 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002589
David Neto862b7d82018-06-14 18:48:37 -04002590 // Generate variables. Make one for each of resource var info object.
2591 for (auto *info : ModuleOrderedResourceVars) {
2592 Type *type = info->var_fn->getReturnType();
2593 // Remap the address space for opaque types.
2594 switch (info->arg_kind) {
2595 case clspv::ArgKind::Sampler:
2596 case clspv::ArgKind::ReadOnlyImage:
2597 case clspv::ArgKind::WriteOnlyImage:
2598 type = PointerType::get(type->getPointerElementType(),
2599 clspv::AddressSpace::UniformConstant);
2600 break;
2601 default:
2602 break;
2603 }
David Neto22f144c2017-06-12 14:26:21 -04002604
David Neto862b7d82018-06-14 18:48:37 -04002605 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002606
David Neto862b7d82018-06-14 18:48:37 -04002607 const auto type_id = lookupType(type);
2608 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2609 SPIRVOperandList Ops;
2610 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002611
David Neto862b7d82018-06-14 18:48:37 -04002612 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2613 SPIRVInstList.push_back(Inst);
2614
2615 // Map calls to the variable-builtin-function.
2616 for (auto &U : info->var_fn->uses()) {
2617 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2618 const auto set = unsigned(
2619 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2620 const auto binding = unsigned(
2621 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2622 if (set == info->descriptor_set && binding == info->binding) {
2623 switch (info->arg_kind) {
2624 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002625 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002626 case clspv::ArgKind::Pod:
2627 // The call maps to the variable directly.
2628 VMap[call] = info->var_id;
2629 break;
2630 case clspv::ArgKind::Sampler:
2631 case clspv::ArgKind::ReadOnlyImage:
2632 case clspv::ArgKind::WriteOnlyImage:
2633 // The call maps to a load we generate later.
2634 ResourceVarDeferredLoadCalls[call] = info->var_id;
2635 break;
2636 default:
2637 llvm_unreachable("Unhandled arg kind");
2638 }
2639 }
David Neto22f144c2017-06-12 14:26:21 -04002640 }
David Neto862b7d82018-06-14 18:48:37 -04002641 }
2642 }
David Neto22f144c2017-06-12 14:26:21 -04002643
David Neto862b7d82018-06-14 18:48:37 -04002644 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002645
David Neto862b7d82018-06-14 18:48:37 -04002646 // Find Insert Point for OpDecorate.
2647 auto DecoInsertPoint =
2648 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2649 [](SPIRVInstruction *Inst) -> bool {
2650 return Inst->getOpcode() != spv::OpDecorate &&
2651 Inst->getOpcode() != spv::OpMemberDecorate &&
2652 Inst->getOpcode() != spv::OpExtInstImport;
2653 });
2654
2655 SPIRVOperandList Ops;
2656 for (auto *info : ModuleOrderedResourceVars) {
2657 // Decorate with DescriptorSet and Binding.
2658 Ops.clear();
2659 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2660 << MkNum(info->descriptor_set);
2661 SPIRVInstList.insert(DecoInsertPoint,
2662 new SPIRVInstruction(spv::OpDecorate, Ops));
2663
2664 Ops.clear();
2665 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2666 << MkNum(info->binding);
2667 SPIRVInstList.insert(DecoInsertPoint,
2668 new SPIRVInstruction(spv::OpDecorate, Ops));
2669
2670 // Generate NonWritable and NonReadable
2671 switch (info->arg_kind) {
2672 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002673 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002674 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2675 clspv::AddressSpace::Constant) {
2676 Ops.clear();
2677 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2678 SPIRVInstList.insert(DecoInsertPoint,
2679 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002680 }
David Neto862b7d82018-06-14 18:48:37 -04002681 break;
2682 case clspv::ArgKind::ReadOnlyImage:
2683 Ops.clear();
2684 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2685 SPIRVInstList.insert(DecoInsertPoint,
2686 new SPIRVInstruction(spv::OpDecorate, Ops));
2687 break;
2688 case clspv::ArgKind::WriteOnlyImage:
2689 Ops.clear();
2690 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2691 SPIRVInstList.insert(DecoInsertPoint,
2692 new SPIRVInstruction(spv::OpDecorate, Ops));
2693 break;
2694 default:
2695 break;
David Neto22f144c2017-06-12 14:26:21 -04002696 }
2697 }
2698}
2699
2700void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002701 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002702 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2703 ValueMapType &VMap = getValueMap();
2704 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002705 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002706
2707 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2708 Type *Ty = GV.getType();
2709 PointerType *PTy = cast<PointerType>(Ty);
2710
2711 uint32_t InitializerID = 0;
2712
2713 // Workgroup size is handled differently (it goes into a constant)
2714 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2715 std::vector<bool> HasMDVec;
2716 uint32_t PrevXDimCst = 0xFFFFFFFF;
2717 uint32_t PrevYDimCst = 0xFFFFFFFF;
2718 uint32_t PrevZDimCst = 0xFFFFFFFF;
2719 for (Function &Func : *GV.getParent()) {
2720 if (Func.isDeclaration()) {
2721 continue;
2722 }
2723
2724 // We only need to check kernels.
2725 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2726 continue;
2727 }
2728
2729 if (const MDNode *MD =
2730 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2731 uint32_t CurXDimCst = static_cast<uint32_t>(
2732 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2733 uint32_t CurYDimCst = static_cast<uint32_t>(
2734 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2735 uint32_t CurZDimCst = static_cast<uint32_t>(
2736 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2737
2738 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2739 PrevZDimCst == 0xFFFFFFFF) {
2740 PrevXDimCst = CurXDimCst;
2741 PrevYDimCst = CurYDimCst;
2742 PrevZDimCst = CurZDimCst;
2743 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2744 CurZDimCst != PrevZDimCst) {
2745 llvm_unreachable(
2746 "reqd_work_group_size must be the same across all kernels");
2747 } else {
2748 continue;
2749 }
2750
2751 //
2752 // Generate OpConstantComposite.
2753 //
2754 // Ops[0] : Result Type ID
2755 // Ops[1] : Constant size for x dimension.
2756 // Ops[2] : Constant size for y dimension.
2757 // Ops[3] : Constant size for z dimension.
2758 SPIRVOperandList Ops;
2759
2760 uint32_t XDimCstID =
2761 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2762 uint32_t YDimCstID =
2763 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2764 uint32_t ZDimCstID =
2765 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2766
2767 InitializerID = nextID;
2768
David Neto257c3892018-04-11 13:19:45 -04002769 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2770 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002771
David Neto87846742018-04-11 17:36:22 -04002772 auto *Inst =
2773 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002774 SPIRVInstList.push_back(Inst);
2775
2776 HasMDVec.push_back(true);
2777 } else {
2778 HasMDVec.push_back(false);
2779 }
2780 }
2781
2782 // Check all kernels have same definitions for work_group_size.
2783 bool HasMD = false;
2784 if (!HasMDVec.empty()) {
2785 HasMD = HasMDVec[0];
2786 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2787 if (HasMD != HasMDVec[i]) {
2788 llvm_unreachable(
2789 "Kernels should have consistent work group size definition");
2790 }
2791 }
2792 }
2793
2794 // If all kernels do not have metadata for reqd_work_group_size, generate
2795 // OpSpecConstants for x/y/z dimension.
2796 if (!HasMD) {
2797 //
2798 // Generate OpSpecConstants for x/y/z dimension.
2799 //
2800 // Ops[0] : Result Type ID
2801 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2802 uint32_t XDimCstID = 0;
2803 uint32_t YDimCstID = 0;
2804 uint32_t ZDimCstID = 0;
2805
David Neto22f144c2017-06-12 14:26:21 -04002806 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002807 uint32_t result_type_id =
2808 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002809
David Neto257c3892018-04-11 13:19:45 -04002810 // X Dimension
2811 Ops << MkId(result_type_id) << MkNum(1);
2812 XDimCstID = nextID++;
2813 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002814 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002815
2816 // Y Dimension
2817 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002818 Ops << MkId(result_type_id) << MkNum(1);
2819 YDimCstID = nextID++;
2820 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002821 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002822
2823 // Z Dimension
2824 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002825 Ops << MkId(result_type_id) << MkNum(1);
2826 ZDimCstID = nextID++;
2827 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002828 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002829
David Neto257c3892018-04-11 13:19:45 -04002830 BuiltinDimVec.push_back(XDimCstID);
2831 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002832 BuiltinDimVec.push_back(ZDimCstID);
2833
David Neto22f144c2017-06-12 14:26:21 -04002834 //
2835 // Generate OpSpecConstantComposite.
2836 //
2837 // Ops[0] : Result Type ID
2838 // Ops[1] : Constant size for x dimension.
2839 // Ops[2] : Constant size for y dimension.
2840 // Ops[3] : Constant size for z dimension.
2841 InitializerID = nextID;
2842
2843 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002844 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2845 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002846
David Neto87846742018-04-11 17:36:22 -04002847 auto *Inst =
2848 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002849 SPIRVInstList.push_back(Inst);
2850 }
2851 }
2852
David Neto22f144c2017-06-12 14:26:21 -04002853 VMap[&GV] = nextID;
2854
2855 //
2856 // Generate OpVariable.
2857 //
2858 // GIDOps[0] : Result Type ID
2859 // GIDOps[1] : Storage Class
2860 SPIRVOperandList Ops;
2861
David Neto85082642018-03-24 06:55:20 -07002862 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002863 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002864
David Neto85082642018-03-24 06:55:20 -07002865 if (GV.hasInitializer()) {
2866 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002867 }
2868
David Neto85082642018-03-24 06:55:20 -07002869 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002870 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002871 clspv::Option::ModuleConstantsInStorageBuffer();
2872
2873 if (0 != InitializerID) {
2874 if (!module_scope_constant_external_init) {
2875 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002876 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002877 }
2878 }
2879 const uint32_t var_id = nextID++;
2880
David Neto87846742018-04-11 17:36:22 -04002881 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002882 SPIRVInstList.push_back(Inst);
2883
2884 // If we have a builtin.
2885 if (spv::BuiltInMax != BuiltinType) {
2886 // Find Insert Point for OpDecorate.
2887 auto DecoInsertPoint =
2888 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2889 [](SPIRVInstruction *Inst) -> bool {
2890 return Inst->getOpcode() != spv::OpDecorate &&
2891 Inst->getOpcode() != spv::OpMemberDecorate &&
2892 Inst->getOpcode() != spv::OpExtInstImport;
2893 });
2894 //
2895 // Generate OpDecorate.
2896 //
2897 // DOps[0] = Target ID
2898 // DOps[1] = Decoration (Builtin)
2899 // DOps[2] = BuiltIn ID
2900 uint32_t ResultID;
2901
2902 // WorkgroupSize is different, we decorate the constant composite that has
2903 // its value, rather than the variable that we use to access the value.
2904 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2905 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002906 // Save both the value and variable IDs for later.
2907 WorkgroupSizeValueID = InitializerID;
2908 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002909 } else {
2910 ResultID = VMap[&GV];
2911 }
2912
2913 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002914 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2915 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002916
David Neto87846742018-04-11 17:36:22 -04002917 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002918 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002919 } else if (module_scope_constant_external_init) {
2920 // This module scope constant is initialized from a storage buffer with data
2921 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002922 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002923
David Neto862b7d82018-06-14 18:48:37 -04002924 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002925 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2926 // that later to other types, like uniform buffer.
2927 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2928 << ",binding,0,kind,buffer,hexbytes,";
2929 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2930 descriptorMapOut << "\n";
2931
2932 // Find Insert Point for OpDecorate.
2933 auto DecoInsertPoint =
2934 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2935 [](SPIRVInstruction *Inst) -> bool {
2936 return Inst->getOpcode() != spv::OpDecorate &&
2937 Inst->getOpcode() != spv::OpMemberDecorate &&
2938 Inst->getOpcode() != spv::OpExtInstImport;
2939 });
2940
David Neto257c3892018-04-11 13:19:45 -04002941 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002942 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002943 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2944 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002945 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002946
2947 // OpDecorate %var DescriptorSet <descriptor_set>
2948 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002949 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2950 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002951 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002952 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002953 }
2954}
2955
David Netoc6f3ab22018-04-06 18:02:31 -04002956void SPIRVProducerPass::GenerateWorkgroupVars() {
2957 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002958 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2959 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002960 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002961
2962 // Generate OpVariable.
2963 //
2964 // GIDOps[0] : Result Type ID
2965 // GIDOps[1] : Storage Class
2966 SPIRVOperandList Ops;
2967 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2968
2969 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002970 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002971 }
2972}
2973
David Neto862b7d82018-06-14 18:48:37 -04002974void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2975 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002976 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2977 return;
2978 }
David Neto862b7d82018-06-14 18:48:37 -04002979 // Gather the list of resources that are used by this function's arguments.
2980 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2981
2982 auto remap_arg_kind = [](StringRef argKind) {
2983 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2984 ? "pod_ubo"
2985 : argKind;
2986 };
2987
2988 auto *fty = F.getType()->getPointerElementType();
2989 auto *func_ty = dyn_cast<FunctionType>(fty);
2990
2991 // If we've clustereed POD arguments, then argument details are in metadata.
2992 // If an argument maps to a resource variable, then get descriptor set and
2993 // binding from the resoure variable. Other info comes from the metadata.
2994 const auto *arg_map = F.getMetadata("kernel_arg_map");
2995 if (arg_map) {
2996 for (const auto &arg : arg_map->operands()) {
2997 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002998 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002999 const auto name =
3000 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3001 const auto old_index =
3002 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3003 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003004 const size_t new_index = static_cast<size_t>(
3005 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003006 const auto offset =
3007 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003008 const auto arg_size =
3009 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003010 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003011 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003012 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003013 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003014 if (spec_id > 0) {
3015 // This was a pointer-to-local argument. It is not associated with a
3016 // resource variable.
3017 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
3018 << ",argOrdinal," << old_index << ",argKind,"
3019 << argKind << ",arrayElemSize,"
Alan Bakerfcda9482018-10-02 17:09:59 -04003020 << GetTypeAllocSize(
David Neto862b7d82018-06-14 18:48:37 -04003021 func_ty->getParamType(unsigned(new_index))
alan-bakerb6b09dc2018-11-08 16:59:28 -05003022 ->getPointerElementType(),
3023 DL)
David Neto862b7d82018-06-14 18:48:37 -04003024 << ",arrayNumElemSpecId," << spec_id << "\n";
3025 } else {
3026 auto *info = resource_var_at_index[new_index];
3027 assert(info);
3028 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
3029 << ",argOrdinal," << old_index << ",descriptorSet,"
3030 << info->descriptor_set << ",binding," << info->binding
Kévin PETITa353c832018-03-20 23:21:21 +00003031 << ",offset," << offset << ",argKind," << argKind;
3032 if (argKind.startswith("pod")) {
3033 descriptorMapOut << ",argSize," << arg_size;
3034 }
3035 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003036 }
3037 }
3038 } else {
3039 // There is no argument map.
3040 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003041 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003042
3043 SmallVector<Argument *, 4> arguments;
3044 for (auto &arg : F.args()) {
3045 arguments.push_back(&arg);
3046 }
3047
3048 unsigned arg_index = 0;
3049 for (auto *info : resource_var_at_index) {
3050 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003051 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003052 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003053 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003054 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003055 }
3056
David Neto862b7d82018-06-14 18:48:37 -04003057 descriptorMapOut << "kernel," << F.getName() << ",arg,"
alan-bakerb6b09dc2018-11-08 16:59:28 -05003058 << arg->getName() << ",argOrdinal," << arg_index
3059 << ",descriptorSet," << info->descriptor_set
3060 << ",binding," << info->binding << ",offset," << 0
3061 << ",argKind,"
David Neto862b7d82018-06-14 18:48:37 -04003062 << remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003063 clspv::GetArgKindName(info->arg_kind));
3064 if (info->arg_kind == clspv::ArgKind::Pod) {
3065 descriptorMapOut << ",argSize," << arg_size;
3066 }
3067 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003068 }
3069 arg_index++;
3070 }
3071 // Generate mappings for pointer-to-local arguments.
3072 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3073 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003074 auto where = LocalArgSpecIds.find(arg);
3075 if (where != LocalArgSpecIds.end()) {
3076 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003077 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3078 << arg->getName() << ",argOrdinal," << arg_index
3079 << ",argKind,"
3080 << "local"
3081 << ",arrayElemSize,"
Alan Bakerfcda9482018-10-02 17:09:59 -04003082 << GetTypeAllocSize(local_arg_info.elem_type, DL)
David Neto862b7d82018-06-14 18:48:37 -04003083 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3084 << "\n";
3085 }
3086 }
3087 }
3088}
3089
David Neto22f144c2017-06-12 14:26:21 -04003090void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3091 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3092 ValueMapType &VMap = getValueMap();
3093 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003094 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3095 auto &GlobalConstArgSet = getGlobalConstArgSet();
3096
3097 FunctionType *FTy = F.getFunctionType();
3098
3099 //
David Neto22f144c2017-06-12 14:26:21 -04003100 // Generate OPFunction.
3101 //
3102
3103 // FOps[0] : Result Type ID
3104 // FOps[1] : Function Control
3105 // FOps[2] : Function Type ID
3106 SPIRVOperandList FOps;
3107
3108 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003109 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003110
3111 // Check function attributes for SPIRV Function Control.
3112 uint32_t FuncControl = spv::FunctionControlMaskNone;
3113 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3114 FuncControl |= spv::FunctionControlInlineMask;
3115 }
3116 if (F.hasFnAttribute(Attribute::NoInline)) {
3117 FuncControl |= spv::FunctionControlDontInlineMask;
3118 }
3119 // TODO: Check llvm attribute for Function Control Pure.
3120 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3121 FuncControl |= spv::FunctionControlPureMask;
3122 }
3123 // TODO: Check llvm attribute for Function Control Const.
3124 if (F.hasFnAttribute(Attribute::ReadNone)) {
3125 FuncControl |= spv::FunctionControlConstMask;
3126 }
3127
David Neto257c3892018-04-11 13:19:45 -04003128 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003129
3130 uint32_t FTyID;
3131 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3132 SmallVector<Type *, 4> NewFuncParamTys;
3133 FunctionType *NewFTy =
3134 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3135 FTyID = lookupType(NewFTy);
3136 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003137 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003138 if (GlobalConstFuncTyMap.count(FTy)) {
3139 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3140 } else {
3141 FTyID = lookupType(FTy);
3142 }
3143 }
3144
David Neto257c3892018-04-11 13:19:45 -04003145 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003146
3147 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3148 EntryPoints.push_back(std::make_pair(&F, nextID));
3149 }
3150
3151 VMap[&F] = nextID;
3152
David Neto482550a2018-03-24 05:21:07 -07003153 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003154 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3155 }
David Neto22f144c2017-06-12 14:26:21 -04003156 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003157 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003158 SPIRVInstList.push_back(FuncInst);
3159
3160 //
3161 // Generate OpFunctionParameter for Normal function.
3162 //
3163
3164 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3165 // Iterate Argument for name instead of param type from function type.
3166 unsigned ArgIdx = 0;
3167 for (Argument &Arg : F.args()) {
3168 VMap[&Arg] = nextID;
3169
3170 // ParamOps[0] : Result Type ID
3171 SPIRVOperandList ParamOps;
3172
3173 // Find SPIRV instruction for parameter type.
3174 uint32_t ParamTyID = lookupType(Arg.getType());
3175 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3176 if (GlobalConstFuncTyMap.count(FTy)) {
3177 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3178 Type *EleTy = PTy->getPointerElementType();
3179 Type *ArgTy =
3180 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3181 ParamTyID = lookupType(ArgTy);
3182 GlobalConstArgSet.insert(&Arg);
3183 }
3184 }
3185 }
David Neto257c3892018-04-11 13:19:45 -04003186 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003187
3188 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003189 auto *ParamInst =
3190 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003191 SPIRVInstList.push_back(ParamInst);
3192
3193 ArgIdx++;
3194 }
3195 }
3196}
3197
alan-bakerb6b09dc2018-11-08 16:59:28 -05003198void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003199 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3200 EntryPointVecType &EntryPoints = getEntryPointVec();
3201 ValueMapType &VMap = getValueMap();
3202 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3203 uint32_t &ExtInstImportID = getOpExtInstImportID();
3204 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3205
3206 // Set up insert point.
3207 auto InsertPoint = SPIRVInstList.begin();
3208
3209 //
3210 // Generate OpCapability
3211 //
3212 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3213
3214 // Ops[0] = Capability
3215 SPIRVOperandList Ops;
3216
David Neto87846742018-04-11 17:36:22 -04003217 auto *CapInst =
3218 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003219 SPIRVInstList.insert(InsertPoint, CapInst);
3220
3221 for (Type *Ty : getTypeList()) {
3222 // Find the i16 type.
3223 if (Ty->isIntegerTy(16)) {
3224 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003225 SPIRVInstList.insert(InsertPoint,
3226 new SPIRVInstruction(spv::OpCapability,
3227 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003228 } else if (Ty->isIntegerTy(64)) {
3229 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003230 SPIRVInstList.insert(InsertPoint,
3231 new SPIRVInstruction(spv::OpCapability,
3232 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003233 } else if (Ty->isHalfTy()) {
3234 // Generate OpCapability for half type.
3235 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003236 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3237 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003238 } else if (Ty->isDoubleTy()) {
3239 // Generate OpCapability for double type.
3240 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003241 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3242 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003243 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3244 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003245 if (STy->getName().equals("opencl.image2d_wo_t") ||
3246 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003247 // Generate OpCapability for write only image type.
3248 SPIRVInstList.insert(
3249 InsertPoint,
3250 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003251 spv::OpCapability,
3252 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003253 }
3254 }
3255 }
3256 }
3257
David Neto5c22a252018-03-15 16:07:41 -04003258 { // OpCapability ImageQuery
3259 bool hasImageQuery = false;
3260 for (const char *imageQuery : {
3261 "_Z15get_image_width14ocl_image2d_ro",
3262 "_Z15get_image_width14ocl_image2d_wo",
3263 "_Z16get_image_height14ocl_image2d_ro",
3264 "_Z16get_image_height14ocl_image2d_wo",
3265 }) {
3266 if (module.getFunction(imageQuery)) {
3267 hasImageQuery = true;
3268 break;
3269 }
3270 }
3271 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003272 auto *ImageQueryCapInst = new SPIRVInstruction(
3273 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003274 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3275 }
3276 }
3277
David Neto22f144c2017-06-12 14:26:21 -04003278 if (hasVariablePointers()) {
3279 //
3280 // Generate OpCapability and OpExtension
3281 //
3282
3283 //
3284 // Generate OpCapability.
3285 //
3286 // Ops[0] = Capability
3287 //
3288 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003289 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003290
David Neto87846742018-04-11 17:36:22 -04003291 SPIRVInstList.insert(InsertPoint,
3292 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003293
3294 //
3295 // Generate OpExtension.
3296 //
3297 // Ops[0] = Name (Literal String)
3298 //
David Netoa772fd12017-08-04 14:17:33 -04003299 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3300 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003301
David Neto87846742018-04-11 17:36:22 -04003302 auto *ExtensionInst =
3303 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003304 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003305 }
David Neto22f144c2017-06-12 14:26:21 -04003306 }
3307
3308 if (ExtInstImportID) {
3309 ++InsertPoint;
3310 }
3311
3312 //
3313 // Generate OpMemoryModel
3314 //
3315 // Memory model for Vulkan will always be GLSL450.
3316
3317 // Ops[0] = Addressing Model
3318 // Ops[1] = Memory Model
3319 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003320 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003321
David Neto87846742018-04-11 17:36:22 -04003322 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003323 SPIRVInstList.insert(InsertPoint, MemModelInst);
3324
3325 //
3326 // Generate OpEntryPoint
3327 //
3328 for (auto EntryPoint : EntryPoints) {
3329 // Ops[0] = Execution Model
3330 // Ops[1] = EntryPoint ID
3331 // Ops[2] = Name (Literal String)
3332 // ...
3333 //
3334 // TODO: Do we need to consider Interface ID for forward references???
3335 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003336 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003337 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3338 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003339
David Neto22f144c2017-06-12 14:26:21 -04003340 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003341 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003342 }
3343
David Neto87846742018-04-11 17:36:22 -04003344 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003345 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3346 }
3347
3348 for (auto EntryPoint : EntryPoints) {
3349 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3350 ->getMetadata("reqd_work_group_size")) {
3351
3352 if (!BuiltinDimVec.empty()) {
3353 llvm_unreachable(
3354 "Kernels should have consistent work group size definition");
3355 }
3356
3357 //
3358 // Generate OpExecutionMode
3359 //
3360
3361 // Ops[0] = Entry Point ID
3362 // Ops[1] = Execution Mode
3363 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3364 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003365 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003366
3367 uint32_t XDim = static_cast<uint32_t>(
3368 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3369 uint32_t YDim = static_cast<uint32_t>(
3370 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3371 uint32_t ZDim = static_cast<uint32_t>(
3372 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3373
David Neto257c3892018-04-11 13:19:45 -04003374 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003375
David Neto87846742018-04-11 17:36:22 -04003376 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003377 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3378 }
3379 }
3380
3381 //
3382 // Generate OpSource.
3383 //
3384 // Ops[0] = SourceLanguage ID
3385 // Ops[1] = Version (LiteralNum)
3386 //
3387 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003388 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003389
David Neto87846742018-04-11 17:36:22 -04003390 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003391 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3392
3393 if (!BuiltinDimVec.empty()) {
3394 //
3395 // Generate OpDecorates for x/y/z dimension.
3396 //
3397 // Ops[0] = Target ID
3398 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003399 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003400
3401 // X Dimension
3402 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003403 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003404 SPIRVInstList.insert(InsertPoint,
3405 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003406
3407 // Y Dimension
3408 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003409 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003410 SPIRVInstList.insert(InsertPoint,
3411 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003412
3413 // Z Dimension
3414 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003415 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003416 SPIRVInstList.insert(InsertPoint,
3417 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003418 }
3419}
3420
David Netob6e2e062018-04-25 10:32:06 -04003421void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3422 // Work around a driver bug. Initializers on Private variables might not
3423 // work. So the start of the kernel should store the initializer value to the
3424 // variables. Yes, *every* entry point pays this cost if *any* entry point
3425 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3426 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003427 // TODO(dneto): Remove this at some point once fixed drivers are widely
3428 // available.
David Netob6e2e062018-04-25 10:32:06 -04003429 if (WorkgroupSizeVarID) {
3430 assert(WorkgroupSizeValueID);
3431
3432 SPIRVOperandList Ops;
3433 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3434
3435 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3436 getSPIRVInstList().push_back(Inst);
3437 }
3438}
3439
David Neto22f144c2017-06-12 14:26:21 -04003440void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3441 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3442 ValueMapType &VMap = getValueMap();
3443
David Netob6e2e062018-04-25 10:32:06 -04003444 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003445
3446 for (BasicBlock &BB : F) {
3447 // Register BasicBlock to ValueMap.
3448 VMap[&BB] = nextID;
3449
3450 //
3451 // Generate OpLabel for Basic Block.
3452 //
3453 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003454 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003455 SPIRVInstList.push_back(Inst);
3456
David Neto6dcd4712017-06-23 11:06:47 -04003457 // OpVariable instructions must come first.
3458 for (Instruction &I : BB) {
3459 if (isa<AllocaInst>(I)) {
3460 GenerateInstruction(I);
3461 }
3462 }
3463
David Neto22f144c2017-06-12 14:26:21 -04003464 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003465 if (clspv::Option::HackInitializers()) {
3466 GenerateEntryPointInitialStores();
3467 }
David Neto22f144c2017-06-12 14:26:21 -04003468 }
3469
3470 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003471 if (!isa<AllocaInst>(I)) {
3472 GenerateInstruction(I);
3473 }
David Neto22f144c2017-06-12 14:26:21 -04003474 }
3475 }
3476}
3477
3478spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3479 const std::map<CmpInst::Predicate, spv::Op> Map = {
3480 {CmpInst::ICMP_EQ, spv::OpIEqual},
3481 {CmpInst::ICMP_NE, spv::OpINotEqual},
3482 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3483 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3484 {CmpInst::ICMP_ULT, spv::OpULessThan},
3485 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3486 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3487 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3488 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3489 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3490 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3491 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3492 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3493 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3494 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3495 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3496 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3497 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3498 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3499 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3500 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3501 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3502
3503 assert(0 != Map.count(I->getPredicate()));
3504
3505 return Map.at(I->getPredicate());
3506}
3507
3508spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3509 const std::map<unsigned, spv::Op> Map{
3510 {Instruction::Trunc, spv::OpUConvert},
3511 {Instruction::ZExt, spv::OpUConvert},
3512 {Instruction::SExt, spv::OpSConvert},
3513 {Instruction::FPToUI, spv::OpConvertFToU},
3514 {Instruction::FPToSI, spv::OpConvertFToS},
3515 {Instruction::UIToFP, spv::OpConvertUToF},
3516 {Instruction::SIToFP, spv::OpConvertSToF},
3517 {Instruction::FPTrunc, spv::OpFConvert},
3518 {Instruction::FPExt, spv::OpFConvert},
3519 {Instruction::BitCast, spv::OpBitcast}};
3520
3521 assert(0 != Map.count(I.getOpcode()));
3522
3523 return Map.at(I.getOpcode());
3524}
3525
3526spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003527 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003528 switch (I.getOpcode()) {
3529 default:
3530 break;
3531 case Instruction::Or:
3532 return spv::OpLogicalOr;
3533 case Instruction::And:
3534 return spv::OpLogicalAnd;
3535 case Instruction::Xor:
3536 return spv::OpLogicalNotEqual;
3537 }
3538 }
3539
alan-bakerb6b09dc2018-11-08 16:59:28 -05003540 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003541 {Instruction::Add, spv::OpIAdd},
3542 {Instruction::FAdd, spv::OpFAdd},
3543 {Instruction::Sub, spv::OpISub},
3544 {Instruction::FSub, spv::OpFSub},
3545 {Instruction::Mul, spv::OpIMul},
3546 {Instruction::FMul, spv::OpFMul},
3547 {Instruction::UDiv, spv::OpUDiv},
3548 {Instruction::SDiv, spv::OpSDiv},
3549 {Instruction::FDiv, spv::OpFDiv},
3550 {Instruction::URem, spv::OpUMod},
3551 {Instruction::SRem, spv::OpSRem},
3552 {Instruction::FRem, spv::OpFRem},
3553 {Instruction::Or, spv::OpBitwiseOr},
3554 {Instruction::Xor, spv::OpBitwiseXor},
3555 {Instruction::And, spv::OpBitwiseAnd},
3556 {Instruction::Shl, spv::OpShiftLeftLogical},
3557 {Instruction::LShr, spv::OpShiftRightLogical},
3558 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3559
3560 assert(0 != Map.count(I.getOpcode()));
3561
3562 return Map.at(I.getOpcode());
3563}
3564
3565void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3566 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3567 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003568 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3569 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3570
3571 // Register Instruction to ValueMap.
3572 if (0 == VMap[&I]) {
3573 VMap[&I] = nextID;
3574 }
3575
3576 switch (I.getOpcode()) {
3577 default: {
3578 if (Instruction::isCast(I.getOpcode())) {
3579 //
3580 // Generate SPIRV instructions for cast operators.
3581 //
3582
David Netod2de94a2017-08-28 17:27:47 -04003583 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003584 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003585 auto toI8 = Ty == Type::getInt8Ty(Context);
3586 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003587 // Handle zext, sext and uitofp with i1 type specially.
3588 if ((I.getOpcode() == Instruction::ZExt ||
3589 I.getOpcode() == Instruction::SExt ||
3590 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003591 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003592 //
3593 // Generate OpSelect.
3594 //
3595
3596 // Ops[0] = Result Type ID
3597 // Ops[1] = Condition ID
3598 // Ops[2] = True Constant ID
3599 // Ops[3] = False Constant ID
3600 SPIRVOperandList Ops;
3601
David Neto257c3892018-04-11 13:19:45 -04003602 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003603
David Neto22f144c2017-06-12 14:26:21 -04003604 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003605 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003606
3607 uint32_t TrueID = 0;
3608 if (I.getOpcode() == Instruction::ZExt) {
3609 APInt One(32, 1);
3610 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3611 } else if (I.getOpcode() == Instruction::SExt) {
3612 APInt MinusOne(32, UINT64_MAX, true);
3613 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3614 } else {
3615 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3616 }
David Neto257c3892018-04-11 13:19:45 -04003617 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003618
3619 uint32_t FalseID = 0;
3620 if (I.getOpcode() == Instruction::ZExt) {
3621 FalseID = VMap[Constant::getNullValue(I.getType())];
3622 } else if (I.getOpcode() == Instruction::SExt) {
3623 FalseID = VMap[Constant::getNullValue(I.getType())];
3624 } else {
3625 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3626 }
David Neto257c3892018-04-11 13:19:45 -04003627 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003628
David Neto87846742018-04-11 17:36:22 -04003629 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003630 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003631 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3632 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3633 // 8 bits.
3634 // Before:
3635 // %result = trunc i32 %a to i8
3636 // After
3637 // %result = OpBitwiseAnd %uint %a %uint_255
3638
3639 SPIRVOperandList Ops;
3640
David Neto257c3892018-04-11 13:19:45 -04003641 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003642
3643 Type *UintTy = Type::getInt32Ty(Context);
3644 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003645 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003646
David Neto87846742018-04-11 17:36:22 -04003647 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003648 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003649 } else {
3650 // Ops[0] = Result Type ID
3651 // Ops[1] = Source Value ID
3652 SPIRVOperandList Ops;
3653
David Neto257c3892018-04-11 13:19:45 -04003654 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003655
David Neto87846742018-04-11 17:36:22 -04003656 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003657 SPIRVInstList.push_back(Inst);
3658 }
3659 } else if (isa<BinaryOperator>(I)) {
3660 //
3661 // Generate SPIRV instructions for binary operators.
3662 //
3663
3664 // Handle xor with i1 type specially.
3665 if (I.getOpcode() == Instruction::Xor &&
3666 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003667 ((isa<ConstantInt>(I.getOperand(0)) &&
3668 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3669 (isa<ConstantInt>(I.getOperand(1)) &&
3670 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003671 //
3672 // Generate OpLogicalNot.
3673 //
3674 // Ops[0] = Result Type ID
3675 // Ops[1] = Operand
3676 SPIRVOperandList Ops;
3677
David Neto257c3892018-04-11 13:19:45 -04003678 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003679
3680 Value *CondV = I.getOperand(0);
3681 if (isa<Constant>(I.getOperand(0))) {
3682 CondV = I.getOperand(1);
3683 }
David Neto257c3892018-04-11 13:19:45 -04003684 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003685
David Neto87846742018-04-11 17:36:22 -04003686 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003687 SPIRVInstList.push_back(Inst);
3688 } else {
3689 // Ops[0] = Result Type ID
3690 // Ops[1] = Operand 0
3691 // Ops[2] = Operand 1
3692 SPIRVOperandList Ops;
3693
David Neto257c3892018-04-11 13:19:45 -04003694 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3695 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003696
David Neto87846742018-04-11 17:36:22 -04003697 auto *Inst =
3698 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003699 SPIRVInstList.push_back(Inst);
3700 }
3701 } else {
3702 I.print(errs());
3703 llvm_unreachable("Unsupported instruction???");
3704 }
3705 break;
3706 }
3707 case Instruction::GetElementPtr: {
3708 auto &GlobalConstArgSet = getGlobalConstArgSet();
3709
3710 //
3711 // Generate OpAccessChain.
3712 //
3713 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3714
3715 //
3716 // Generate OpAccessChain.
3717 //
3718
3719 // Ops[0] = Result Type ID
3720 // Ops[1] = Base ID
3721 // Ops[2] ... Ops[n] = Indexes ID
3722 SPIRVOperandList Ops;
3723
alan-bakerb6b09dc2018-11-08 16:59:28 -05003724 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003725 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3726 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3727 // Use pointer type with private address space for global constant.
3728 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003729 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003730 }
David Neto257c3892018-04-11 13:19:45 -04003731
3732 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003733
David Neto862b7d82018-06-14 18:48:37 -04003734 // Generate the base pointer.
3735 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003736
David Neto862b7d82018-06-14 18:48:37 -04003737 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003738
3739 //
3740 // Follows below rules for gep.
3741 //
David Neto862b7d82018-06-14 18:48:37 -04003742 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3743 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003744 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3745 // first index.
3746 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3747 // use gep's first index.
3748 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3749 // gep's first index.
3750 //
3751 spv::Op Opcode = spv::OpAccessChain;
3752 unsigned offset = 0;
3753 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003754 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003755 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003756 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003757 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003758 }
David Neto862b7d82018-06-14 18:48:37 -04003759 } else {
David Neto22f144c2017-06-12 14:26:21 -04003760 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003761 }
3762
3763 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003764 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003765 // Do we need to generate ArrayStride? Check against the GEP result type
3766 // rather than the pointer type of the base because when indexing into
3767 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3768 // for something else in the SPIR-V.
3769 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
Alan Bakerfcda9482018-10-02 17:09:59 -04003770 switch (GetStorageClass(ResultType->getAddressSpace())) {
3771 case spv::StorageClassStorageBuffer:
3772 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003773 // Save the need to generate an ArrayStride decoration. But defer
3774 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003775 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003776 break;
3777 default:
3778 break;
David Neto1a1a0582017-07-07 12:01:44 -04003779 }
David Neto22f144c2017-06-12 14:26:21 -04003780 }
3781
3782 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003783 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003784 }
3785
David Neto87846742018-04-11 17:36:22 -04003786 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003787 SPIRVInstList.push_back(Inst);
3788 break;
3789 }
3790 case Instruction::ExtractValue: {
3791 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3792 // Ops[0] = Result Type ID
3793 // Ops[1] = Composite ID
3794 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3795 SPIRVOperandList Ops;
3796
David Neto257c3892018-04-11 13:19:45 -04003797 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003798
3799 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003800 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003801
3802 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003803 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003804 }
3805
David Neto87846742018-04-11 17:36:22 -04003806 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003807 SPIRVInstList.push_back(Inst);
3808 break;
3809 }
3810 case Instruction::InsertValue: {
3811 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3812 // Ops[0] = Result Type ID
3813 // Ops[1] = Object ID
3814 // Ops[2] = Composite ID
3815 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3816 SPIRVOperandList Ops;
3817
3818 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003819 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003820
3821 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003822 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003823
3824 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003825 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003826
3827 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003828 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003829 }
3830
David Neto87846742018-04-11 17:36:22 -04003831 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003832 SPIRVInstList.push_back(Inst);
3833 break;
3834 }
3835 case Instruction::Select: {
3836 //
3837 // Generate OpSelect.
3838 //
3839
3840 // Ops[0] = Result Type ID
3841 // Ops[1] = Condition ID
3842 // Ops[2] = True Constant ID
3843 // Ops[3] = False Constant ID
3844 SPIRVOperandList Ops;
3845
3846 // Find SPIRV instruction for parameter type.
3847 auto Ty = I.getType();
3848 if (Ty->isPointerTy()) {
3849 auto PointeeTy = Ty->getPointerElementType();
3850 if (PointeeTy->isStructTy() &&
3851 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3852 Ty = PointeeTy;
3853 }
3854 }
3855
David Neto257c3892018-04-11 13:19:45 -04003856 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3857 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003858
David Neto87846742018-04-11 17:36:22 -04003859 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003860 SPIRVInstList.push_back(Inst);
3861 break;
3862 }
3863 case Instruction::ExtractElement: {
3864 // Handle <4 x i8> type manually.
3865 Type *CompositeTy = I.getOperand(0)->getType();
3866 if (is4xi8vec(CompositeTy)) {
3867 //
3868 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3869 // <4 x i8>.
3870 //
3871
3872 //
3873 // Generate OpShiftRightLogical
3874 //
3875 // Ops[0] = Result Type ID
3876 // Ops[1] = Operand 0
3877 // Ops[2] = Operand 1
3878 //
3879 SPIRVOperandList Ops;
3880
David Neto257c3892018-04-11 13:19:45 -04003881 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003882
3883 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003884 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003885
3886 uint32_t Op1ID = 0;
3887 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3888 // Handle constant index.
3889 uint64_t Idx = CI->getZExtValue();
3890 Value *ShiftAmount =
3891 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3892 Op1ID = VMap[ShiftAmount];
3893 } else {
3894 // Handle variable index.
3895 SPIRVOperandList TmpOps;
3896
David Neto257c3892018-04-11 13:19:45 -04003897 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3898 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003899
3900 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003901 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003902
3903 Op1ID = nextID;
3904
David Neto87846742018-04-11 17:36:22 -04003905 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003906 SPIRVInstList.push_back(TmpInst);
3907 }
David Neto257c3892018-04-11 13:19:45 -04003908 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003909
3910 uint32_t ShiftID = nextID;
3911
David Neto87846742018-04-11 17:36:22 -04003912 auto *Inst =
3913 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003914 SPIRVInstList.push_back(Inst);
3915
3916 //
3917 // Generate OpBitwiseAnd
3918 //
3919 // Ops[0] = Result Type ID
3920 // Ops[1] = Operand 0
3921 // Ops[2] = Operand 1
3922 //
3923 Ops.clear();
3924
David Neto257c3892018-04-11 13:19:45 -04003925 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003926
3927 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003928 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003929
David Neto9b2d6252017-09-06 15:47:37 -04003930 // Reset mapping for this value to the result of the bitwise and.
3931 VMap[&I] = nextID;
3932
David Neto87846742018-04-11 17:36:22 -04003933 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003934 SPIRVInstList.push_back(Inst);
3935 break;
3936 }
3937
3938 // Ops[0] = Result Type ID
3939 // Ops[1] = Composite ID
3940 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3941 SPIRVOperandList Ops;
3942
David Neto257c3892018-04-11 13:19:45 -04003943 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003944
3945 spv::Op Opcode = spv::OpCompositeExtract;
3946 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003947 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003948 } else {
David Neto257c3892018-04-11 13:19:45 -04003949 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003950 Opcode = spv::OpVectorExtractDynamic;
3951 }
3952
David Neto87846742018-04-11 17:36:22 -04003953 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003954 SPIRVInstList.push_back(Inst);
3955 break;
3956 }
3957 case Instruction::InsertElement: {
3958 // Handle <4 x i8> type manually.
3959 Type *CompositeTy = I.getOperand(0)->getType();
3960 if (is4xi8vec(CompositeTy)) {
3961 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3962 uint32_t CstFFID = VMap[CstFF];
3963
3964 uint32_t ShiftAmountID = 0;
3965 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3966 // Handle constant index.
3967 uint64_t Idx = CI->getZExtValue();
3968 Value *ShiftAmount =
3969 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3970 ShiftAmountID = VMap[ShiftAmount];
3971 } else {
3972 // Handle variable index.
3973 SPIRVOperandList TmpOps;
3974
David Neto257c3892018-04-11 13:19:45 -04003975 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3976 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003977
3978 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003979 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003980
3981 ShiftAmountID = nextID;
3982
David Neto87846742018-04-11 17:36:22 -04003983 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003984 SPIRVInstList.push_back(TmpInst);
3985 }
3986
3987 //
3988 // Generate mask operations.
3989 //
3990
3991 // ShiftLeft mask according to index of insertelement.
3992 SPIRVOperandList Ops;
3993
David Neto257c3892018-04-11 13:19:45 -04003994 const uint32_t ResTyID = lookupType(CompositeTy);
3995 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003996
3997 uint32_t MaskID = nextID;
3998
David Neto87846742018-04-11 17:36:22 -04003999 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004000 SPIRVInstList.push_back(Inst);
4001
4002 // Inverse mask.
4003 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004004 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004005
4006 uint32_t InvMaskID = nextID;
4007
David Neto87846742018-04-11 17:36:22 -04004008 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004009 SPIRVInstList.push_back(Inst);
4010
4011 // Apply mask.
4012 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004013 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004014
4015 uint32_t OrgValID = nextID;
4016
David Neto87846742018-04-11 17:36:22 -04004017 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004018 SPIRVInstList.push_back(Inst);
4019
4020 // Create correct value according to index of insertelement.
4021 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004022 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4023 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004024
4025 uint32_t InsertValID = nextID;
4026
David Neto87846742018-04-11 17:36:22 -04004027 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004028 SPIRVInstList.push_back(Inst);
4029
4030 // Insert value to original value.
4031 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004032 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004033
David Netoa394f392017-08-26 20:45:29 -04004034 VMap[&I] = nextID;
4035
David Neto87846742018-04-11 17:36:22 -04004036 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004037 SPIRVInstList.push_back(Inst);
4038
4039 break;
4040 }
4041
David Neto22f144c2017-06-12 14:26:21 -04004042 SPIRVOperandList Ops;
4043
James Priced26efea2018-06-09 23:28:32 +01004044 // Ops[0] = Result Type ID
4045 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004046
4047 spv::Op Opcode = spv::OpCompositeInsert;
4048 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004049 const auto value = CI->getZExtValue();
4050 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004051 // Ops[1] = Object ID
4052 // Ops[2] = Composite ID
4053 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004054 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004055 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004056 } else {
James Priced26efea2018-06-09 23:28:32 +01004057 // Ops[1] = Composite ID
4058 // Ops[2] = Object ID
4059 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004060 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004061 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004062 Opcode = spv::OpVectorInsertDynamic;
4063 }
4064
David Neto87846742018-04-11 17:36:22 -04004065 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004066 SPIRVInstList.push_back(Inst);
4067 break;
4068 }
4069 case Instruction::ShuffleVector: {
4070 // Ops[0] = Result Type ID
4071 // Ops[1] = Vector 1 ID
4072 // Ops[2] = Vector 2 ID
4073 // Ops[3] ... Ops[n] = Components (Literal Number)
4074 SPIRVOperandList Ops;
4075
David Neto257c3892018-04-11 13:19:45 -04004076 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4077 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004078
4079 uint64_t NumElements = 0;
4080 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4081 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4082
4083 if (Cst->isNullValue()) {
4084 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004085 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004086 }
4087 } else if (const ConstantDataSequential *CDS =
4088 dyn_cast<ConstantDataSequential>(Cst)) {
4089 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4090 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004091 const auto value = CDS->getElementAsInteger(i);
4092 assert(value <= UINT32_MAX);
4093 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004094 }
4095 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4096 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4097 auto Op = CV->getOperand(i);
4098
4099 uint32_t literal = 0;
4100
4101 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4102 literal = static_cast<uint32_t>(CI->getZExtValue());
4103 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4104 literal = 0xFFFFFFFFu;
4105 } else {
4106 Op->print(errs());
4107 llvm_unreachable("Unsupported element in ConstantVector!");
4108 }
4109
David Neto257c3892018-04-11 13:19:45 -04004110 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004111 }
4112 } else {
4113 Cst->print(errs());
4114 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4115 }
4116 }
4117
David Neto87846742018-04-11 17:36:22 -04004118 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004119 SPIRVInstList.push_back(Inst);
4120 break;
4121 }
4122 case Instruction::ICmp:
4123 case Instruction::FCmp: {
4124 CmpInst *CmpI = cast<CmpInst>(&I);
4125
David Netod4ca2e62017-07-06 18:47:35 -04004126 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004127 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004128 if (isa<PointerType>(ArgTy)) {
4129 CmpI->print(errs());
4130 std::string name = I.getParent()->getParent()->getName();
4131 errs()
4132 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4133 << "in function " << name << "\n";
4134 llvm_unreachable("Pointer equality check is invalid");
4135 break;
4136 }
4137
David Neto257c3892018-04-11 13:19:45 -04004138 // Ops[0] = Result Type ID
4139 // Ops[1] = Operand 1 ID
4140 // Ops[2] = Operand 2 ID
4141 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004142
David Neto257c3892018-04-11 13:19:45 -04004143 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4144 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004145
4146 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004147 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004148 SPIRVInstList.push_back(Inst);
4149 break;
4150 }
4151 case Instruction::Br: {
4152 // Branch instrucion is deferred because it needs label's ID. Record slot's
4153 // location on SPIRVInstructionList.
4154 DeferredInsts.push_back(
4155 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4156 break;
4157 }
4158 case Instruction::Switch: {
4159 I.print(errs());
4160 llvm_unreachable("Unsupported instruction???");
4161 break;
4162 }
4163 case Instruction::IndirectBr: {
4164 I.print(errs());
4165 llvm_unreachable("Unsupported instruction???");
4166 break;
4167 }
4168 case Instruction::PHI: {
4169 // Branch instrucion is deferred because it needs label's ID. Record slot's
4170 // location on SPIRVInstructionList.
4171 DeferredInsts.push_back(
4172 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4173 break;
4174 }
4175 case Instruction::Alloca: {
4176 //
4177 // Generate OpVariable.
4178 //
4179 // Ops[0] : Result Type ID
4180 // Ops[1] : Storage Class
4181 SPIRVOperandList Ops;
4182
David Neto257c3892018-04-11 13:19:45 -04004183 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004184
David Neto87846742018-04-11 17:36:22 -04004185 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004186 SPIRVInstList.push_back(Inst);
4187 break;
4188 }
4189 case Instruction::Load: {
4190 LoadInst *LD = cast<LoadInst>(&I);
4191 //
4192 // Generate OpLoad.
4193 //
4194
David Neto0a2f98d2017-09-15 19:38:40 -04004195 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004196 uint32_t PointerID = VMap[LD->getPointerOperand()];
4197
4198 // This is a hack to work around what looks like a driver bug.
4199 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004200 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4201 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004202 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004203 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004204 // Generate a bitwise-and of the original value with itself.
4205 // We should have been able to get away with just an OpCopyObject,
4206 // but we need something more complex to get past certain driver bugs.
4207 // This is ridiculous, but necessary.
4208 // TODO(dneto): Revisit this once drivers fix their bugs.
4209
4210 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004211 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4212 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004213
David Neto87846742018-04-11 17:36:22 -04004214 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004215 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004216 break;
4217 }
4218
4219 // This is the normal path. Generate a load.
4220
David Neto22f144c2017-06-12 14:26:21 -04004221 // Ops[0] = Result Type ID
4222 // Ops[1] = Pointer ID
4223 // Ops[2] ... Ops[n] = Optional Memory Access
4224 //
4225 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004226
David Neto22f144c2017-06-12 14:26:21 -04004227 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004228 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004229
David Neto87846742018-04-11 17:36:22 -04004230 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004231 SPIRVInstList.push_back(Inst);
4232 break;
4233 }
4234 case Instruction::Store: {
4235 StoreInst *ST = cast<StoreInst>(&I);
4236 //
4237 // Generate OpStore.
4238 //
4239
4240 // Ops[0] = Pointer ID
4241 // Ops[1] = Object ID
4242 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4243 //
4244 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004245 SPIRVOperandList Ops;
4246 Ops << MkId(VMap[ST->getPointerOperand()])
4247 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004248
David Neto87846742018-04-11 17:36:22 -04004249 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004250 SPIRVInstList.push_back(Inst);
4251 break;
4252 }
4253 case Instruction::AtomicCmpXchg: {
4254 I.print(errs());
4255 llvm_unreachable("Unsupported instruction???");
4256 break;
4257 }
4258 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004259 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4260
4261 spv::Op opcode;
4262
4263 switch (AtomicRMW->getOperation()) {
4264 default:
4265 I.print(errs());
4266 llvm_unreachable("Unsupported instruction???");
4267 case llvm::AtomicRMWInst::Add:
4268 opcode = spv::OpAtomicIAdd;
4269 break;
4270 case llvm::AtomicRMWInst::Sub:
4271 opcode = spv::OpAtomicISub;
4272 break;
4273 case llvm::AtomicRMWInst::Xchg:
4274 opcode = spv::OpAtomicExchange;
4275 break;
4276 case llvm::AtomicRMWInst::Min:
4277 opcode = spv::OpAtomicSMin;
4278 break;
4279 case llvm::AtomicRMWInst::Max:
4280 opcode = spv::OpAtomicSMax;
4281 break;
4282 case llvm::AtomicRMWInst::UMin:
4283 opcode = spv::OpAtomicUMin;
4284 break;
4285 case llvm::AtomicRMWInst::UMax:
4286 opcode = spv::OpAtomicUMax;
4287 break;
4288 case llvm::AtomicRMWInst::And:
4289 opcode = spv::OpAtomicAnd;
4290 break;
4291 case llvm::AtomicRMWInst::Or:
4292 opcode = spv::OpAtomicOr;
4293 break;
4294 case llvm::AtomicRMWInst::Xor:
4295 opcode = spv::OpAtomicXor;
4296 break;
4297 }
4298
4299 //
4300 // Generate OpAtomic*.
4301 //
4302 SPIRVOperandList Ops;
4303
David Neto257c3892018-04-11 13:19:45 -04004304 Ops << MkId(lookupType(I.getType()))
4305 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004306
4307 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004308 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004309 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004310
4311 const auto ConstantMemorySemantics = ConstantInt::get(
4312 IntTy, spv::MemorySemanticsUniformMemoryMask |
4313 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004314 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004315
David Neto257c3892018-04-11 13:19:45 -04004316 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004317
4318 VMap[&I] = nextID;
4319
David Neto87846742018-04-11 17:36:22 -04004320 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004321 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004322 break;
4323 }
4324 case Instruction::Fence: {
4325 I.print(errs());
4326 llvm_unreachable("Unsupported instruction???");
4327 break;
4328 }
4329 case Instruction::Call: {
4330 CallInst *Call = dyn_cast<CallInst>(&I);
4331 Function *Callee = Call->getCalledFunction();
4332
Alan Baker202c8c72018-08-13 13:47:44 -04004333 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004334 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4335 // Generate an OpLoad
4336 SPIRVOperandList Ops;
4337 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004338
David Neto862b7d82018-06-14 18:48:37 -04004339 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4340 << MkId(ResourceVarDeferredLoadCalls[Call]);
4341
4342 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4343 SPIRVInstList.push_back(Inst);
4344 VMap[Call] = load_id;
4345 break;
4346
4347 } else {
4348 // This maps to an OpVariable we've already generated.
4349 // No code is generated for the call.
4350 }
4351 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004352 } else if (Callee->getName().startswith(
4353 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004354 // Don't codegen an instruction here, but instead map this call directly
4355 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004356 int spec_id = static_cast<int>(
4357 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004358 const auto &info = LocalSpecIdInfoMap[spec_id];
4359 VMap[Call] = info.variable_id;
4360 break;
David Neto862b7d82018-06-14 18:48:37 -04004361 }
4362
4363 // Sampler initializers become a load of the corresponding sampler.
4364
4365 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4366 // Map this to a load from the variable.
4367 const auto index_into_sampler_map =
4368 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4369
4370 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004371 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004372 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004373
David Neto257c3892018-04-11 13:19:45 -04004374 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004375 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4376 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004377
David Neto862b7d82018-06-14 18:48:37 -04004378 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004379 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004380 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004381 break;
4382 }
4383
4384 if (Callee->getName().startswith("spirv.atomic")) {
4385 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4386 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4387 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4388 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4389 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4390 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4391 .Case("spirv.atomic_compare_exchange",
4392 spv::OpAtomicCompareExchange)
4393 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4394 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4395 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4396 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4397 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4398 .Case("spirv.atomic_or", spv::OpAtomicOr)
4399 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4400 .Default(spv::OpNop);
4401
4402 //
4403 // Generate OpAtomic*.
4404 //
4405 SPIRVOperandList Ops;
4406
David Neto257c3892018-04-11 13:19:45 -04004407 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004408
4409 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004410 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004411 }
4412
4413 VMap[&I] = nextID;
4414
David Neto87846742018-04-11 17:36:22 -04004415 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004416 SPIRVInstList.push_back(Inst);
4417 break;
4418 }
4419
4420 if (Callee->getName().startswith("_Z3dot")) {
4421 // If the argument is a vector type, generate OpDot
4422 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4423 //
4424 // Generate OpDot.
4425 //
4426 SPIRVOperandList Ops;
4427
David Neto257c3892018-04-11 13:19:45 -04004428 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004429
4430 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004431 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004432 }
4433
4434 VMap[&I] = nextID;
4435
David Neto87846742018-04-11 17:36:22 -04004436 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004437 SPIRVInstList.push_back(Inst);
4438 } else {
4439 //
4440 // Generate OpFMul.
4441 //
4442 SPIRVOperandList Ops;
4443
David Neto257c3892018-04-11 13:19:45 -04004444 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004445
4446 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004447 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004448 }
4449
4450 VMap[&I] = nextID;
4451
David Neto87846742018-04-11 17:36:22 -04004452 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004453 SPIRVInstList.push_back(Inst);
4454 }
4455 break;
4456 }
4457
David Neto8505ebf2017-10-13 18:50:50 -04004458 if (Callee->getName().startswith("_Z4fmod")) {
4459 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4460 // The sign for a non-zero result is taken from x.
4461 // (Try an example.)
4462 // So translate to OpFRem
4463
4464 SPIRVOperandList Ops;
4465
David Neto257c3892018-04-11 13:19:45 -04004466 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004467
4468 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004469 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004470 }
4471
4472 VMap[&I] = nextID;
4473
David Neto87846742018-04-11 17:36:22 -04004474 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004475 SPIRVInstList.push_back(Inst);
4476 break;
4477 }
4478
David Neto22f144c2017-06-12 14:26:21 -04004479 // spirv.store_null.* intrinsics become OpStore's.
4480 if (Callee->getName().startswith("spirv.store_null")) {
4481 //
4482 // Generate OpStore.
4483 //
4484
4485 // Ops[0] = Pointer ID
4486 // Ops[1] = Object ID
4487 // Ops[2] ... Ops[n]
4488 SPIRVOperandList Ops;
4489
4490 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004491 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004492 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004493
David Neto87846742018-04-11 17:36:22 -04004494 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004495
4496 break;
4497 }
4498
4499 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4500 if (Callee->getName().startswith("spirv.copy_memory")) {
4501 //
4502 // Generate OpCopyMemory.
4503 //
4504
4505 // Ops[0] = Dst ID
4506 // Ops[1] = Src ID
4507 // Ops[2] = Memory Access
4508 // Ops[3] = Alignment
4509
4510 auto IsVolatile =
4511 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4512
4513 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4514 : spv::MemoryAccessMaskNone;
4515
4516 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4517
4518 auto Alignment =
4519 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4520
David Neto257c3892018-04-11 13:19:45 -04004521 SPIRVOperandList Ops;
4522 Ops << MkId(VMap[Call->getArgOperand(0)])
4523 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4524 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004525
David Neto87846742018-04-11 17:36:22 -04004526 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004527
4528 SPIRVInstList.push_back(Inst);
4529
4530 break;
4531 }
4532
4533 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4534 // with unit.
4535 if (Callee->getName().equals("_Z3absj") ||
4536 Callee->getName().equals("_Z3absDv2_j") ||
4537 Callee->getName().equals("_Z3absDv3_j") ||
4538 Callee->getName().equals("_Z3absDv4_j")) {
4539 VMap[&I] = VMap[Call->getOperand(0)];
4540 break;
4541 }
4542
4543 // barrier is converted to OpControlBarrier
4544 if (Callee->getName().equals("__spirv_control_barrier")) {
4545 //
4546 // Generate OpControlBarrier.
4547 //
4548 // Ops[0] = Execution Scope ID
4549 // Ops[1] = Memory Scope ID
4550 // Ops[2] = Memory Semantics ID
4551 //
4552 Value *ExecutionScope = Call->getArgOperand(0);
4553 Value *MemoryScope = Call->getArgOperand(1);
4554 Value *MemorySemantics = Call->getArgOperand(2);
4555
David Neto257c3892018-04-11 13:19:45 -04004556 SPIRVOperandList Ops;
4557 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4558 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004559
David Neto87846742018-04-11 17:36:22 -04004560 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004561 break;
4562 }
4563
4564 // memory barrier is converted to OpMemoryBarrier
4565 if (Callee->getName().equals("__spirv_memory_barrier")) {
4566 //
4567 // Generate OpMemoryBarrier.
4568 //
4569 // Ops[0] = Memory Scope ID
4570 // Ops[1] = Memory Semantics ID
4571 //
4572 SPIRVOperandList Ops;
4573
David Neto257c3892018-04-11 13:19:45 -04004574 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4575 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004576
David Neto257c3892018-04-11 13:19:45 -04004577 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004578
David Neto87846742018-04-11 17:36:22 -04004579 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004580 SPIRVInstList.push_back(Inst);
4581 break;
4582 }
4583
4584 // isinf is converted to OpIsInf
4585 if (Callee->getName().equals("__spirv_isinff") ||
4586 Callee->getName().equals("__spirv_isinfDv2_f") ||
4587 Callee->getName().equals("__spirv_isinfDv3_f") ||
4588 Callee->getName().equals("__spirv_isinfDv4_f")) {
4589 //
4590 // Generate OpIsInf.
4591 //
4592 // Ops[0] = Result Type ID
4593 // Ops[1] = X ID
4594 //
4595 SPIRVOperandList Ops;
4596
David Neto257c3892018-04-11 13:19:45 -04004597 Ops << MkId(lookupType(I.getType()))
4598 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004599
4600 VMap[&I] = nextID;
4601
David Neto87846742018-04-11 17:36:22 -04004602 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004603 SPIRVInstList.push_back(Inst);
4604 break;
4605 }
4606
4607 // isnan is converted to OpIsNan
4608 if (Callee->getName().equals("__spirv_isnanf") ||
4609 Callee->getName().equals("__spirv_isnanDv2_f") ||
4610 Callee->getName().equals("__spirv_isnanDv3_f") ||
4611 Callee->getName().equals("__spirv_isnanDv4_f")) {
4612 //
4613 // Generate OpIsInf.
4614 //
4615 // Ops[0] = Result Type ID
4616 // Ops[1] = X ID
4617 //
4618 SPIRVOperandList Ops;
4619
David Neto257c3892018-04-11 13:19:45 -04004620 Ops << MkId(lookupType(I.getType()))
4621 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004622
4623 VMap[&I] = nextID;
4624
David Neto87846742018-04-11 17:36:22 -04004625 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004626 SPIRVInstList.push_back(Inst);
4627 break;
4628 }
4629
4630 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004631 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004632 //
4633 // Generate OpAll.
4634 //
4635 // Ops[0] = Result Type ID
4636 // Ops[1] = Vector ID
4637 //
4638 SPIRVOperandList Ops;
4639
David Neto257c3892018-04-11 13:19:45 -04004640 Ops << MkId(lookupType(I.getType()))
4641 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004642
4643 VMap[&I] = nextID;
4644
David Neto87846742018-04-11 17:36:22 -04004645 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004646 SPIRVInstList.push_back(Inst);
4647 break;
4648 }
4649
4650 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004651 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004652 //
4653 // Generate OpAny.
4654 //
4655 // Ops[0] = Result Type ID
4656 // Ops[1] = Vector ID
4657 //
4658 SPIRVOperandList Ops;
4659
David Neto257c3892018-04-11 13:19:45 -04004660 Ops << MkId(lookupType(I.getType()))
4661 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004662
4663 VMap[&I] = nextID;
4664
David Neto87846742018-04-11 17:36:22 -04004665 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004666 SPIRVInstList.push_back(Inst);
4667 break;
4668 }
4669
4670 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4671 // Additionally, OpTypeSampledImage is generated.
4672 if (Callee->getName().equals(
4673 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4674 Callee->getName().equals(
4675 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4676 //
4677 // Generate OpSampledImage.
4678 //
4679 // Ops[0] = Result Type ID
4680 // Ops[1] = Image ID
4681 // Ops[2] = Sampler ID
4682 //
4683 SPIRVOperandList Ops;
4684
4685 Value *Image = Call->getArgOperand(0);
4686 Value *Sampler = Call->getArgOperand(1);
4687 Value *Coordinate = Call->getArgOperand(2);
4688
4689 TypeMapType &OpImageTypeMap = getImageTypeMap();
4690 Type *ImageTy = Image->getType()->getPointerElementType();
4691 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004692 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004693 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004694
4695 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004696
4697 uint32_t SampledImageID = nextID;
4698
David Neto87846742018-04-11 17:36:22 -04004699 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004700 SPIRVInstList.push_back(Inst);
4701
4702 //
4703 // Generate OpImageSampleExplicitLod.
4704 //
4705 // Ops[0] = Result Type ID
4706 // Ops[1] = Sampled Image ID
4707 // Ops[2] = Coordinate ID
4708 // Ops[3] = Image Operands Type ID
4709 // Ops[4] ... Ops[n] = Operands ID
4710 //
4711 Ops.clear();
4712
David Neto257c3892018-04-11 13:19:45 -04004713 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4714 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004715
4716 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004717 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004718
4719 VMap[&I] = nextID;
4720
David Neto87846742018-04-11 17:36:22 -04004721 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004722 SPIRVInstList.push_back(Inst);
4723 break;
4724 }
4725
4726 // write_imagef is mapped to OpImageWrite.
4727 if (Callee->getName().equals(
4728 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4729 Callee->getName().equals(
4730 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4731 //
4732 // Generate OpImageWrite.
4733 //
4734 // Ops[0] = Image ID
4735 // Ops[1] = Coordinate ID
4736 // Ops[2] = Texel ID
4737 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4738 // Ops[4] ... Ops[n] = (Optional) Operands ID
4739 //
4740 SPIRVOperandList Ops;
4741
4742 Value *Image = Call->getArgOperand(0);
4743 Value *Coordinate = Call->getArgOperand(1);
4744 Value *Texel = Call->getArgOperand(2);
4745
4746 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004747 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004748 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004749 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004750
David Neto87846742018-04-11 17:36:22 -04004751 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004752 SPIRVInstList.push_back(Inst);
4753 break;
4754 }
4755
David Neto5c22a252018-03-15 16:07:41 -04004756 // get_image_width is mapped to OpImageQuerySize
4757 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4758 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4759 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4760 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4761 //
4762 // Generate OpImageQuerySize, then pull out the right component.
4763 // Assume 2D image for now.
4764 //
4765 // Ops[0] = Image ID
4766 //
4767 // %sizes = OpImageQuerySizes %uint2 %im
4768 // %result = OpCompositeExtract %uint %sizes 0-or-1
4769 SPIRVOperandList Ops;
4770
4771 // Implement:
4772 // %sizes = OpImageQuerySizes %uint2 %im
4773 uint32_t SizesTypeID =
4774 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004775 Value *Image = Call->getArgOperand(0);
4776 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004777 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004778
4779 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004780 auto *QueryInst =
4781 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004782 SPIRVInstList.push_back(QueryInst);
4783
4784 // Reset value map entry since we generated an intermediate instruction.
4785 VMap[&I] = nextID;
4786
4787 // Implement:
4788 // %result = OpCompositeExtract %uint %sizes 0-or-1
4789 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004790 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004791
4792 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004793 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004794
David Neto87846742018-04-11 17:36:22 -04004795 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004796 SPIRVInstList.push_back(Inst);
4797 break;
4798 }
4799
David Neto22f144c2017-06-12 14:26:21 -04004800 // Call instrucion is deferred because it needs function's ID. Record
4801 // slot's location on SPIRVInstructionList.
4802 DeferredInsts.push_back(
4803 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4804
David Neto3fbb4072017-10-16 11:28:14 -04004805 // Check whether the implementation of this call uses an extended
4806 // instruction plus one more value-producing instruction. If so, then
4807 // reserve the id for the extra value-producing slot.
4808 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4809 if (EInst != kGlslExtInstBad) {
4810 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004811 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004812 VMap[&I] = nextID;
4813 nextID++;
4814 }
4815 break;
4816 }
4817 case Instruction::Ret: {
4818 unsigned NumOps = I.getNumOperands();
4819 if (NumOps == 0) {
4820 //
4821 // Generate OpReturn.
4822 //
David Neto87846742018-04-11 17:36:22 -04004823 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004824 } else {
4825 //
4826 // Generate OpReturnValue.
4827 //
4828
4829 // Ops[0] = Return Value ID
4830 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004831
4832 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004833
David Neto87846742018-04-11 17:36:22 -04004834 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004835 SPIRVInstList.push_back(Inst);
4836 break;
4837 }
4838 break;
4839 }
4840 }
4841}
4842
4843void SPIRVProducerPass::GenerateFuncEpilogue() {
4844 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4845
4846 //
4847 // Generate OpFunctionEnd
4848 //
4849
David Neto87846742018-04-11 17:36:22 -04004850 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004851 SPIRVInstList.push_back(Inst);
4852}
4853
4854bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4855 LLVMContext &Context = Ty->getContext();
4856 if (Ty->isVectorTy()) {
4857 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4858 Ty->getVectorNumElements() == 4) {
4859 return true;
4860 }
4861 }
4862
4863 return false;
4864}
4865
David Neto257c3892018-04-11 13:19:45 -04004866uint32_t SPIRVProducerPass::GetI32Zero() {
4867 if (0 == constant_i32_zero_id_) {
4868 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4869 "defined in the SPIR-V module");
4870 }
4871 return constant_i32_zero_id_;
4872}
4873
David Neto22f144c2017-06-12 14:26:21 -04004874void SPIRVProducerPass::HandleDeferredInstruction() {
4875 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4876 ValueMapType &VMap = getValueMap();
4877 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4878
4879 for (auto DeferredInst = DeferredInsts.rbegin();
4880 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4881 Value *Inst = std::get<0>(*DeferredInst);
4882 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4883 if (InsertPoint != SPIRVInstList.end()) {
4884 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4885 ++InsertPoint;
4886 }
4887 }
4888
4889 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4890 // Check whether basic block, which has this branch instruction, is loop
4891 // header or not. If it is loop header, generate OpLoopMerge and
4892 // OpBranchConditional.
4893 Function *Func = Br->getParent()->getParent();
4894 DominatorTree &DT =
4895 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4896 const LoopInfo &LI =
4897 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4898
4899 BasicBlock *BrBB = Br->getParent();
4900 if (LI.isLoopHeader(BrBB)) {
4901 Value *ContinueBB = nullptr;
4902 Value *MergeBB = nullptr;
4903
4904 Loop *L = LI.getLoopFor(BrBB);
4905 MergeBB = L->getExitBlock();
4906 if (!MergeBB) {
4907 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4908 // has regions with single entry/exit. As a result, loop should not
4909 // have multiple exits.
4910 llvm_unreachable("Loop has multiple exits???");
4911 }
4912
4913 if (L->isLoopLatch(BrBB)) {
4914 ContinueBB = BrBB;
4915 } else {
4916 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4917 // block.
4918 BasicBlock *Header = L->getHeader();
4919 BasicBlock *Latch = L->getLoopLatch();
4920 for (BasicBlock *BB : L->blocks()) {
4921 if (BB == Header) {
4922 continue;
4923 }
4924
4925 // Check whether block dominates block with back-edge.
4926 if (DT.dominates(BB, Latch)) {
4927 ContinueBB = BB;
4928 }
4929 }
4930
4931 if (!ContinueBB) {
4932 llvm_unreachable("Wrong continue block from loop");
4933 }
4934 }
4935
4936 //
4937 // Generate OpLoopMerge.
4938 //
4939 // Ops[0] = Merge Block ID
4940 // Ops[1] = Continue Target ID
4941 // Ops[2] = Selection Control
4942 SPIRVOperandList Ops;
4943
4944 // StructurizeCFG pass already manipulated CFG. Just use false block of
4945 // branch instruction as merge block.
4946 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004947 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004948 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4949 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004950
David Neto87846742018-04-11 17:36:22 -04004951 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004952 SPIRVInstList.insert(InsertPoint, MergeInst);
4953
4954 } else if (Br->isConditional()) {
4955 bool HasBackEdge = false;
4956
4957 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4958 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4959 HasBackEdge = true;
4960 }
4961 }
4962 if (!HasBackEdge) {
4963 //
4964 // Generate OpSelectionMerge.
4965 //
4966 // Ops[0] = Merge Block ID
4967 // Ops[1] = Selection Control
4968 SPIRVOperandList Ops;
4969
4970 // StructurizeCFG pass already manipulated CFG. Just use false block
4971 // of branch instruction as merge block.
4972 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004973 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004974
David Neto87846742018-04-11 17:36:22 -04004975 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004976 SPIRVInstList.insert(InsertPoint, MergeInst);
4977 }
4978 }
4979
4980 if (Br->isConditional()) {
4981 //
4982 // Generate OpBranchConditional.
4983 //
4984 // Ops[0] = Condition ID
4985 // Ops[1] = True Label ID
4986 // Ops[2] = False Label ID
4987 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4988 SPIRVOperandList Ops;
4989
4990 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004991 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004992 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004993
4994 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004995
David Neto87846742018-04-11 17:36:22 -04004996 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004997 SPIRVInstList.insert(InsertPoint, BrInst);
4998 } else {
4999 //
5000 // Generate OpBranch.
5001 //
5002 // Ops[0] = Target Label ID
5003 SPIRVOperandList Ops;
5004
5005 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005006 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005007
David Neto87846742018-04-11 17:36:22 -04005008 SPIRVInstList.insert(InsertPoint,
5009 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005010 }
5011 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5012 //
5013 // Generate OpPhi.
5014 //
5015 // Ops[0] = Result Type ID
5016 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5017 SPIRVOperandList Ops;
5018
David Neto257c3892018-04-11 13:19:45 -04005019 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005020
David Neto22f144c2017-06-12 14:26:21 -04005021 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5022 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005023 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005024 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005025 }
5026
5027 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005028 InsertPoint,
5029 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005030 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5031 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005032 auto callee_name = Callee->getName();
5033 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005034
5035 if (EInst) {
5036 uint32_t &ExtInstImportID = getOpExtInstImportID();
5037
5038 //
5039 // Generate OpExtInst.
5040 //
5041
5042 // Ops[0] = Result Type ID
5043 // Ops[1] = Set ID (OpExtInstImport ID)
5044 // Ops[2] = Instruction Number (Literal Number)
5045 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5046 SPIRVOperandList Ops;
5047
David Neto862b7d82018-06-14 18:48:37 -04005048 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5049 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005050
David Neto22f144c2017-06-12 14:26:21 -04005051 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5052 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005053 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005054 }
5055
David Neto87846742018-04-11 17:36:22 -04005056 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5057 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005058 SPIRVInstList.insert(InsertPoint, ExtInst);
5059
David Neto3fbb4072017-10-16 11:28:14 -04005060 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5061 if (IndirectExtInst != kGlslExtInstBad) {
5062 // Generate one more instruction that uses the result of the extended
5063 // instruction. Its result id is one more than the id of the
5064 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005065 LLVMContext &Context =
5066 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005067
David Neto3fbb4072017-10-16 11:28:14 -04005068 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5069 &VMap, &SPIRVInstList, &InsertPoint](
5070 spv::Op opcode, Constant *constant) {
5071 //
5072 // Generate instruction like:
5073 // result = opcode constant <extinst-result>
5074 //
5075 // Ops[0] = Result Type ID
5076 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5077 // Ops[2] = Operand 1 ;; the result of the extended instruction
5078 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005079
David Neto3fbb4072017-10-16 11:28:14 -04005080 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005081 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005082
5083 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5084 constant = ConstantVector::getSplat(
5085 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5086 }
David Neto257c3892018-04-11 13:19:45 -04005087 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005088
5089 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005090 InsertPoint, new SPIRVInstruction(
5091 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005092 };
5093
5094 switch (IndirectExtInst) {
5095 case glsl::ExtInstFindUMsb: // Implementing clz
5096 generate_extra_inst(
5097 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5098 break;
5099 case glsl::ExtInstAcos: // Implementing acospi
5100 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005101 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005102 case glsl::ExtInstAtan2: // Implementing atan2pi
5103 generate_extra_inst(
5104 spv::OpFMul,
5105 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5106 break;
5107
5108 default:
5109 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005110 }
David Neto22f144c2017-06-12 14:26:21 -04005111 }
David Neto3fbb4072017-10-16 11:28:14 -04005112
David Neto862b7d82018-06-14 18:48:37 -04005113 } else if (callee_name.equals("_Z8popcounti") ||
5114 callee_name.equals("_Z8popcountj") ||
5115 callee_name.equals("_Z8popcountDv2_i") ||
5116 callee_name.equals("_Z8popcountDv3_i") ||
5117 callee_name.equals("_Z8popcountDv4_i") ||
5118 callee_name.equals("_Z8popcountDv2_j") ||
5119 callee_name.equals("_Z8popcountDv3_j") ||
5120 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005121 //
5122 // Generate OpBitCount
5123 //
5124 // Ops[0] = Result Type ID
5125 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005126 SPIRVOperandList Ops;
5127 Ops << MkId(lookupType(Call->getType()))
5128 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005129
5130 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005131 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005132 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005133
David Neto862b7d82018-06-14 18:48:37 -04005134 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005135
5136 // Generate an OpCompositeConstruct
5137 SPIRVOperandList Ops;
5138
5139 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005140 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005141
5142 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005143 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005144 }
5145
5146 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005147 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5148 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005149
Alan Baker202c8c72018-08-13 13:47:44 -04005150 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5151
5152 // We have already mapped the call's result value to an ID.
5153 // Don't generate any code now.
5154
5155 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005156
5157 // We have already mapped the call's result value to an ID.
5158 // Don't generate any code now.
5159
David Neto22f144c2017-06-12 14:26:21 -04005160 } else {
5161 //
5162 // Generate OpFunctionCall.
5163 //
5164
5165 // Ops[0] = Result Type ID
5166 // Ops[1] = Callee Function ID
5167 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5168 SPIRVOperandList Ops;
5169
David Neto862b7d82018-06-14 18:48:37 -04005170 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005171
5172 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005173 if (CalleeID == 0) {
5174 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005175 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005176 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5177 // causes an infinite loop. Instead, go ahead and generate
5178 // the bad function call. A validator will catch the 0-Id.
5179 // llvm_unreachable("Can't translate function call");
5180 }
David Neto22f144c2017-06-12 14:26:21 -04005181
David Neto257c3892018-04-11 13:19:45 -04005182 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005183
David Neto22f144c2017-06-12 14:26:21 -04005184 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5185 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005186 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005187 }
5188
David Neto87846742018-04-11 17:36:22 -04005189 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5190 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005191 SPIRVInstList.insert(InsertPoint, CallInst);
5192 }
5193 }
5194 }
5195}
5196
David Neto1a1a0582017-07-07 12:01:44 -04005197void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005198 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005199 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005200 }
David Neto1a1a0582017-07-07 12:01:44 -04005201
5202 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005203
5204 // Find an iterator pointing just past the last decoration.
5205 bool seen_decorations = false;
5206 auto DecoInsertPoint =
5207 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5208 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5209 const bool is_decoration =
5210 Inst->getOpcode() == spv::OpDecorate ||
5211 Inst->getOpcode() == spv::OpMemberDecorate;
5212 if (is_decoration) {
5213 seen_decorations = true;
5214 return false;
5215 } else {
5216 return seen_decorations;
5217 }
5218 });
5219
David Netoc6f3ab22018-04-06 18:02:31 -04005220 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5221 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005222 for (auto *type : getTypesNeedingArrayStride()) {
5223 Type *elemTy = nullptr;
5224 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5225 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005226 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005227 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005228 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005229 elemTy = seqTy->getSequentialElementType();
5230 } else {
5231 errs() << "Unhandled strided type " << *type << "\n";
5232 llvm_unreachable("Unhandled strided type");
5233 }
David Neto1a1a0582017-07-07 12:01:44 -04005234
5235 // Ops[0] = Target ID
5236 // Ops[1] = Decoration (ArrayStride)
5237 // Ops[2] = Stride number (Literal Number)
5238 SPIRVOperandList Ops;
5239
David Neto85082642018-03-24 06:55:20 -07005240 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005241 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005242
5243 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5244 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005245
David Neto87846742018-04-11 17:36:22 -04005246 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005247 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5248 }
David Netoc6f3ab22018-04-06 18:02:31 -04005249
5250 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005251 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5252 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005253 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005254 SPIRVOperandList Ops;
5255 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5256 << MkNum(arg_info.spec_id);
5257 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005258 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005259 }
David Neto1a1a0582017-07-07 12:01:44 -04005260}
5261
David Neto22f144c2017-06-12 14:26:21 -04005262glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5263 return StringSwitch<glsl::ExtInst>(Name)
5264 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5265 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5266 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5267 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5268 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5269 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5270 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5271 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5272 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5273 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5274 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5275 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5276 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5277 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5278 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5279 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005280 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5281 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5282 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5283 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5284 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5285 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5286 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5287 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5288 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5289 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5290 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5291 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5292 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5293 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5294 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5295 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5296 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5297 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5298 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5299 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5300 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5301 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5302 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5303 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5304 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5305 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5306 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5307 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5308 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5309 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5310 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5311 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5312 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5313 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5314 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5315 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5316 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5317 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5318 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5319 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5320 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5321 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5322 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5323 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5324 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5325 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5326 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5327 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5328 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5329 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5330 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5331 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5332 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5333 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5334 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5335 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5336 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5337 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5338 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5339 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5340 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5341 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005342 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005343 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5344 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5345 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5346 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5347 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5348 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5349 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5350 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5351 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5352 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5353 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5354 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5355 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5356 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5357 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5358 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5359 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005360 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005361 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005362 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005363 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005364 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005365 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5366 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005367 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005368 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5369 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5370 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005371 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5372 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5373 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5374 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005375 .Default(kGlslExtInstBad);
5376}
5377
5378glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5379 // Check indirect cases.
5380 return StringSwitch<glsl::ExtInst>(Name)
5381 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5382 // Use exact match on float arg because these need a multiply
5383 // of a constant of the right floating point type.
5384 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5385 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5386 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5387 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5388 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5389 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5390 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5391 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005392 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5393 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5394 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5395 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005396 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5397 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5398 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5399 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5400 .Default(kGlslExtInstBad);
5401}
5402
alan-bakerb6b09dc2018-11-08 16:59:28 -05005403glsl::ExtInst
5404SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005405 auto direct = getExtInstEnum(Name);
5406 if (direct != kGlslExtInstBad)
5407 return direct;
5408 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005409}
5410
5411void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5412 out << "%" << Inst->getResultID();
5413}
5414
5415void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5416 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5417 out << "\t" << spv::getOpName(Opcode);
5418}
5419
5420void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5421 SPIRVOperandType OpTy = Op->getType();
5422 switch (OpTy) {
5423 default: {
5424 llvm_unreachable("Unsupported SPIRV Operand Type???");
5425 break;
5426 }
5427 case SPIRVOperandType::NUMBERID: {
5428 out << "%" << Op->getNumID();
5429 break;
5430 }
5431 case SPIRVOperandType::LITERAL_STRING: {
5432 out << "\"" << Op->getLiteralStr() << "\"";
5433 break;
5434 }
5435 case SPIRVOperandType::LITERAL_INTEGER: {
5436 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005437 auto Words = Op->getLiteralNum();
5438 auto NumWords = Words.size();
5439
5440 if (NumWords == 1) {
5441 out << Words[0];
5442 } else if (NumWords == 2) {
5443 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5444 out << Val;
5445 } else {
5446 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005447 }
5448 break;
5449 }
5450 case SPIRVOperandType::LITERAL_FLOAT: {
5451 // TODO: Handle LiteralNum carefully.
5452 for (auto Word : Op->getLiteralNum()) {
5453 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5454 SmallString<8> Str;
5455 APF.toString(Str, 6, 2);
5456 out << Str;
5457 }
5458 break;
5459 }
5460 }
5461}
5462
5463void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5464 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5465 out << spv::getCapabilityName(Cap);
5466}
5467
5468void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5469 auto LiteralNum = Op->getLiteralNum();
5470 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5471 out << glsl::getExtInstName(Ext);
5472}
5473
5474void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5475 spv::AddressingModel AddrModel =
5476 static_cast<spv::AddressingModel>(Op->getNumID());
5477 out << spv::getAddressingModelName(AddrModel);
5478}
5479
5480void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5481 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5482 out << spv::getMemoryModelName(MemModel);
5483}
5484
5485void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5486 spv::ExecutionModel ExecModel =
5487 static_cast<spv::ExecutionModel>(Op->getNumID());
5488 out << spv::getExecutionModelName(ExecModel);
5489}
5490
5491void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5492 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5493 out << spv::getExecutionModeName(ExecMode);
5494}
5495
5496void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005497 spv::SourceLanguage SourceLang =
5498 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005499 out << spv::getSourceLanguageName(SourceLang);
5500}
5501
5502void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5503 spv::FunctionControlMask FuncCtrl =
5504 static_cast<spv::FunctionControlMask>(Op->getNumID());
5505 out << spv::getFunctionControlName(FuncCtrl);
5506}
5507
5508void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5509 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5510 out << getStorageClassName(StClass);
5511}
5512
5513void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5514 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5515 out << getDecorationName(Deco);
5516}
5517
5518void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5519 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5520 out << getBuiltInName(BIn);
5521}
5522
5523void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5524 spv::SelectionControlMask BIn =
5525 static_cast<spv::SelectionControlMask>(Op->getNumID());
5526 out << getSelectionControlName(BIn);
5527}
5528
5529void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5530 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5531 out << getLoopControlName(BIn);
5532}
5533
5534void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5535 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5536 out << getDimName(DIM);
5537}
5538
5539void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5540 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5541 out << getImageFormatName(Format);
5542}
5543
5544void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5545 out << spv::getMemoryAccessName(
5546 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5547}
5548
5549void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5550 auto LiteralNum = Op->getLiteralNum();
5551 spv::ImageOperandsMask Type =
5552 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5553 out << getImageOperandsName(Type);
5554}
5555
5556void SPIRVProducerPass::WriteSPIRVAssembly() {
5557 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5558
5559 for (auto Inst : SPIRVInstList) {
5560 SPIRVOperandList Ops = Inst->getOperands();
5561 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5562
5563 switch (Opcode) {
5564 default: {
5565 llvm_unreachable("Unsupported SPIRV instruction");
5566 break;
5567 }
5568 case spv::OpCapability: {
5569 // Ops[0] = Capability
5570 PrintOpcode(Inst);
5571 out << " ";
5572 PrintCapability(Ops[0]);
5573 out << "\n";
5574 break;
5575 }
5576 case spv::OpMemoryModel: {
5577 // Ops[0] = Addressing Model
5578 // Ops[1] = Memory Model
5579 PrintOpcode(Inst);
5580 out << " ";
5581 PrintAddrModel(Ops[0]);
5582 out << " ";
5583 PrintMemModel(Ops[1]);
5584 out << "\n";
5585 break;
5586 }
5587 case spv::OpEntryPoint: {
5588 // Ops[0] = Execution Model
5589 // Ops[1] = EntryPoint ID
5590 // Ops[2] = Name (Literal String)
5591 // Ops[3] ... Ops[n] = Interface ID
5592 PrintOpcode(Inst);
5593 out << " ";
5594 PrintExecModel(Ops[0]);
5595 for (uint32_t i = 1; i < Ops.size(); i++) {
5596 out << " ";
5597 PrintOperand(Ops[i]);
5598 }
5599 out << "\n";
5600 break;
5601 }
5602 case spv::OpExecutionMode: {
5603 // Ops[0] = Entry Point ID
5604 // Ops[1] = Execution Mode
5605 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5606 PrintOpcode(Inst);
5607 out << " ";
5608 PrintOperand(Ops[0]);
5609 out << " ";
5610 PrintExecMode(Ops[1]);
5611 for (uint32_t i = 2; i < Ops.size(); i++) {
5612 out << " ";
5613 PrintOperand(Ops[i]);
5614 }
5615 out << "\n";
5616 break;
5617 }
5618 case spv::OpSource: {
5619 // Ops[0] = SourceLanguage ID
5620 // Ops[1] = Version (LiteralNum)
5621 PrintOpcode(Inst);
5622 out << " ";
5623 PrintSourceLanguage(Ops[0]);
5624 out << " ";
5625 PrintOperand(Ops[1]);
5626 out << "\n";
5627 break;
5628 }
5629 case spv::OpDecorate: {
5630 // Ops[0] = Target ID
5631 // Ops[1] = Decoration (Block or BufferBlock)
5632 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5633 PrintOpcode(Inst);
5634 out << " ";
5635 PrintOperand(Ops[0]);
5636 out << " ";
5637 PrintDecoration(Ops[1]);
5638 // Handle BuiltIn OpDecorate specially.
5639 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5640 out << " ";
5641 PrintBuiltIn(Ops[2]);
5642 } else {
5643 for (uint32_t i = 2; i < Ops.size(); i++) {
5644 out << " ";
5645 PrintOperand(Ops[i]);
5646 }
5647 }
5648 out << "\n";
5649 break;
5650 }
5651 case spv::OpMemberDecorate: {
5652 // Ops[0] = Structure Type ID
5653 // Ops[1] = Member Index(Literal Number)
5654 // Ops[2] = Decoration
5655 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5656 PrintOpcode(Inst);
5657 out << " ";
5658 PrintOperand(Ops[0]);
5659 out << " ";
5660 PrintOperand(Ops[1]);
5661 out << " ";
5662 PrintDecoration(Ops[2]);
5663 for (uint32_t i = 3; i < Ops.size(); i++) {
5664 out << " ";
5665 PrintOperand(Ops[i]);
5666 }
5667 out << "\n";
5668 break;
5669 }
5670 case spv::OpTypePointer: {
5671 // Ops[0] = Storage Class
5672 // Ops[1] = Element Type ID
5673 PrintResID(Inst);
5674 out << " = ";
5675 PrintOpcode(Inst);
5676 out << " ";
5677 PrintStorageClass(Ops[0]);
5678 out << " ";
5679 PrintOperand(Ops[1]);
5680 out << "\n";
5681 break;
5682 }
5683 case spv::OpTypeImage: {
5684 // Ops[0] = Sampled Type ID
5685 // Ops[1] = Dim ID
5686 // Ops[2] = Depth (Literal Number)
5687 // Ops[3] = Arrayed (Literal Number)
5688 // Ops[4] = MS (Literal Number)
5689 // Ops[5] = Sampled (Literal Number)
5690 // Ops[6] = Image Format ID
5691 PrintResID(Inst);
5692 out << " = ";
5693 PrintOpcode(Inst);
5694 out << " ";
5695 PrintOperand(Ops[0]);
5696 out << " ";
5697 PrintDimensionality(Ops[1]);
5698 out << " ";
5699 PrintOperand(Ops[2]);
5700 out << " ";
5701 PrintOperand(Ops[3]);
5702 out << " ";
5703 PrintOperand(Ops[4]);
5704 out << " ";
5705 PrintOperand(Ops[5]);
5706 out << " ";
5707 PrintImageFormat(Ops[6]);
5708 out << "\n";
5709 break;
5710 }
5711 case spv::OpFunction: {
5712 // Ops[0] : Result Type ID
5713 // Ops[1] : Function Control
5714 // Ops[2] : Function Type ID
5715 PrintResID(Inst);
5716 out << " = ";
5717 PrintOpcode(Inst);
5718 out << " ";
5719 PrintOperand(Ops[0]);
5720 out << " ";
5721 PrintFuncCtrl(Ops[1]);
5722 out << " ";
5723 PrintOperand(Ops[2]);
5724 out << "\n";
5725 break;
5726 }
5727 case spv::OpSelectionMerge: {
5728 // Ops[0] = Merge Block ID
5729 // Ops[1] = Selection Control
5730 PrintOpcode(Inst);
5731 out << " ";
5732 PrintOperand(Ops[0]);
5733 out << " ";
5734 PrintSelectionControl(Ops[1]);
5735 out << "\n";
5736 break;
5737 }
5738 case spv::OpLoopMerge: {
5739 // Ops[0] = Merge Block ID
5740 // Ops[1] = Continue Target ID
5741 // Ops[2] = Selection Control
5742 PrintOpcode(Inst);
5743 out << " ";
5744 PrintOperand(Ops[0]);
5745 out << " ";
5746 PrintOperand(Ops[1]);
5747 out << " ";
5748 PrintLoopControl(Ops[2]);
5749 out << "\n";
5750 break;
5751 }
5752 case spv::OpImageSampleExplicitLod: {
5753 // Ops[0] = Result Type ID
5754 // Ops[1] = Sampled Image ID
5755 // Ops[2] = Coordinate ID
5756 // Ops[3] = Image Operands Type ID
5757 // Ops[4] ... Ops[n] = Operands ID
5758 PrintResID(Inst);
5759 out << " = ";
5760 PrintOpcode(Inst);
5761 for (uint32_t i = 0; i < 3; i++) {
5762 out << " ";
5763 PrintOperand(Ops[i]);
5764 }
5765 out << " ";
5766 PrintImageOperandsType(Ops[3]);
5767 for (uint32_t i = 4; i < Ops.size(); i++) {
5768 out << " ";
5769 PrintOperand(Ops[i]);
5770 }
5771 out << "\n";
5772 break;
5773 }
5774 case spv::OpVariable: {
5775 // Ops[0] : Result Type ID
5776 // Ops[1] : Storage Class
5777 // Ops[2] ... Ops[n] = Initializer IDs
5778 PrintResID(Inst);
5779 out << " = ";
5780 PrintOpcode(Inst);
5781 out << " ";
5782 PrintOperand(Ops[0]);
5783 out << " ";
5784 PrintStorageClass(Ops[1]);
5785 for (uint32_t i = 2; i < Ops.size(); i++) {
5786 out << " ";
5787 PrintOperand(Ops[i]);
5788 }
5789 out << "\n";
5790 break;
5791 }
5792 case spv::OpExtInst: {
5793 // Ops[0] = Result Type ID
5794 // Ops[1] = Set ID (OpExtInstImport ID)
5795 // Ops[2] = Instruction Number (Literal Number)
5796 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5797 PrintResID(Inst);
5798 out << " = ";
5799 PrintOpcode(Inst);
5800 out << " ";
5801 PrintOperand(Ops[0]);
5802 out << " ";
5803 PrintOperand(Ops[1]);
5804 out << " ";
5805 PrintExtInst(Ops[2]);
5806 for (uint32_t i = 3; i < Ops.size(); i++) {
5807 out << " ";
5808 PrintOperand(Ops[i]);
5809 }
5810 out << "\n";
5811 break;
5812 }
5813 case spv::OpCopyMemory: {
5814 // Ops[0] = Addressing Model
5815 // Ops[1] = Memory Model
5816 PrintOpcode(Inst);
5817 out << " ";
5818 PrintOperand(Ops[0]);
5819 out << " ";
5820 PrintOperand(Ops[1]);
5821 out << " ";
5822 PrintMemoryAccess(Ops[2]);
5823 out << " ";
5824 PrintOperand(Ops[3]);
5825 out << "\n";
5826 break;
5827 }
5828 case spv::OpExtension:
5829 case spv::OpControlBarrier:
5830 case spv::OpMemoryBarrier:
5831 case spv::OpBranch:
5832 case spv::OpBranchConditional:
5833 case spv::OpStore:
5834 case spv::OpImageWrite:
5835 case spv::OpReturnValue:
5836 case spv::OpReturn:
5837 case spv::OpFunctionEnd: {
5838 PrintOpcode(Inst);
5839 for (uint32_t i = 0; i < Ops.size(); i++) {
5840 out << " ";
5841 PrintOperand(Ops[i]);
5842 }
5843 out << "\n";
5844 break;
5845 }
5846 case spv::OpExtInstImport:
5847 case spv::OpTypeRuntimeArray:
5848 case spv::OpTypeStruct:
5849 case spv::OpTypeSampler:
5850 case spv::OpTypeSampledImage:
5851 case spv::OpTypeInt:
5852 case spv::OpTypeFloat:
5853 case spv::OpTypeArray:
5854 case spv::OpTypeVector:
5855 case spv::OpTypeBool:
5856 case spv::OpTypeVoid:
5857 case spv::OpTypeFunction:
5858 case spv::OpFunctionParameter:
5859 case spv::OpLabel:
5860 case spv::OpPhi:
5861 case spv::OpLoad:
5862 case spv::OpSelect:
5863 case spv::OpAccessChain:
5864 case spv::OpPtrAccessChain:
5865 case spv::OpInBoundsAccessChain:
5866 case spv::OpUConvert:
5867 case spv::OpSConvert:
5868 case spv::OpConvertFToU:
5869 case spv::OpConvertFToS:
5870 case spv::OpConvertUToF:
5871 case spv::OpConvertSToF:
5872 case spv::OpFConvert:
5873 case spv::OpConvertPtrToU:
5874 case spv::OpConvertUToPtr:
5875 case spv::OpBitcast:
5876 case spv::OpIAdd:
5877 case spv::OpFAdd:
5878 case spv::OpISub:
5879 case spv::OpFSub:
5880 case spv::OpIMul:
5881 case spv::OpFMul:
5882 case spv::OpUDiv:
5883 case spv::OpSDiv:
5884 case spv::OpFDiv:
5885 case spv::OpUMod:
5886 case spv::OpSRem:
5887 case spv::OpFRem:
5888 case spv::OpBitwiseOr:
5889 case spv::OpBitwiseXor:
5890 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005891 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005892 case spv::OpShiftLeftLogical:
5893 case spv::OpShiftRightLogical:
5894 case spv::OpShiftRightArithmetic:
5895 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005896 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005897 case spv::OpCompositeExtract:
5898 case spv::OpVectorExtractDynamic:
5899 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005900 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005901 case spv::OpVectorInsertDynamic:
5902 case spv::OpVectorShuffle:
5903 case spv::OpIEqual:
5904 case spv::OpINotEqual:
5905 case spv::OpUGreaterThan:
5906 case spv::OpUGreaterThanEqual:
5907 case spv::OpULessThan:
5908 case spv::OpULessThanEqual:
5909 case spv::OpSGreaterThan:
5910 case spv::OpSGreaterThanEqual:
5911 case spv::OpSLessThan:
5912 case spv::OpSLessThanEqual:
5913 case spv::OpFOrdEqual:
5914 case spv::OpFOrdGreaterThan:
5915 case spv::OpFOrdGreaterThanEqual:
5916 case spv::OpFOrdLessThan:
5917 case spv::OpFOrdLessThanEqual:
5918 case spv::OpFOrdNotEqual:
5919 case spv::OpFUnordEqual:
5920 case spv::OpFUnordGreaterThan:
5921 case spv::OpFUnordGreaterThanEqual:
5922 case spv::OpFUnordLessThan:
5923 case spv::OpFUnordLessThanEqual:
5924 case spv::OpFUnordNotEqual:
5925 case spv::OpSampledImage:
5926 case spv::OpFunctionCall:
5927 case spv::OpConstantTrue:
5928 case spv::OpConstantFalse:
5929 case spv::OpConstant:
5930 case spv::OpSpecConstant:
5931 case spv::OpConstantComposite:
5932 case spv::OpSpecConstantComposite:
5933 case spv::OpConstantNull:
5934 case spv::OpLogicalOr:
5935 case spv::OpLogicalAnd:
5936 case spv::OpLogicalNot:
5937 case spv::OpLogicalNotEqual:
5938 case spv::OpUndef:
5939 case spv::OpIsInf:
5940 case spv::OpIsNan:
5941 case spv::OpAny:
5942 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005943 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005944 case spv::OpAtomicIAdd:
5945 case spv::OpAtomicISub:
5946 case spv::OpAtomicExchange:
5947 case spv::OpAtomicIIncrement:
5948 case spv::OpAtomicIDecrement:
5949 case spv::OpAtomicCompareExchange:
5950 case spv::OpAtomicUMin:
5951 case spv::OpAtomicSMin:
5952 case spv::OpAtomicUMax:
5953 case spv::OpAtomicSMax:
5954 case spv::OpAtomicAnd:
5955 case spv::OpAtomicOr:
5956 case spv::OpAtomicXor:
5957 case spv::OpDot: {
5958 PrintResID(Inst);
5959 out << " = ";
5960 PrintOpcode(Inst);
5961 for (uint32_t i = 0; i < Ops.size(); i++) {
5962 out << " ";
5963 PrintOperand(Ops[i]);
5964 }
5965 out << "\n";
5966 break;
5967 }
5968 }
5969 }
5970}
5971
5972void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005973 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005974}
5975
5976void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5977 WriteOneWord(Inst->getResultID());
5978}
5979
5980void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5981 // High 16 bit : Word Count
5982 // Low 16 bit : Opcode
5983 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005984 const uint32_t count = Inst->getWordCount();
5985 if (count > 65535) {
5986 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5987 llvm_unreachable("Word count too high");
5988 }
David Neto22f144c2017-06-12 14:26:21 -04005989 Word |= Inst->getWordCount() << 16;
5990 WriteOneWord(Word);
5991}
5992
5993void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5994 SPIRVOperandType OpTy = Op->getType();
5995 switch (OpTy) {
5996 default: {
5997 llvm_unreachable("Unsupported SPIRV Operand Type???");
5998 break;
5999 }
6000 case SPIRVOperandType::NUMBERID: {
6001 WriteOneWord(Op->getNumID());
6002 break;
6003 }
6004 case SPIRVOperandType::LITERAL_STRING: {
6005 std::string Str = Op->getLiteralStr();
6006 const char *Data = Str.c_str();
6007 size_t WordSize = Str.size() / 4;
6008 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6009 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6010 }
6011
6012 uint32_t Remainder = Str.size() % 4;
6013 uint32_t LastWord = 0;
6014 if (Remainder) {
6015 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6016 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6017 }
6018 }
6019
6020 WriteOneWord(LastWord);
6021 break;
6022 }
6023 case SPIRVOperandType::LITERAL_INTEGER:
6024 case SPIRVOperandType::LITERAL_FLOAT: {
6025 auto LiteralNum = Op->getLiteralNum();
6026 // TODO: Handle LiteranNum carefully.
6027 for (auto Word : LiteralNum) {
6028 WriteOneWord(Word);
6029 }
6030 break;
6031 }
6032 }
6033}
6034
6035void SPIRVProducerPass::WriteSPIRVBinary() {
6036 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6037
6038 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006039 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006040 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6041
6042 switch (Opcode) {
6043 default: {
David Neto5c22a252018-03-15 16:07:41 -04006044 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006045 llvm_unreachable("Unsupported SPIRV instruction");
6046 break;
6047 }
6048 case spv::OpCapability:
6049 case spv::OpExtension:
6050 case spv::OpMemoryModel:
6051 case spv::OpEntryPoint:
6052 case spv::OpExecutionMode:
6053 case spv::OpSource:
6054 case spv::OpDecorate:
6055 case spv::OpMemberDecorate:
6056 case spv::OpBranch:
6057 case spv::OpBranchConditional:
6058 case spv::OpSelectionMerge:
6059 case spv::OpLoopMerge:
6060 case spv::OpStore:
6061 case spv::OpImageWrite:
6062 case spv::OpReturnValue:
6063 case spv::OpControlBarrier:
6064 case spv::OpMemoryBarrier:
6065 case spv::OpReturn:
6066 case spv::OpFunctionEnd:
6067 case spv::OpCopyMemory: {
6068 WriteWordCountAndOpcode(Inst);
6069 for (uint32_t i = 0; i < Ops.size(); i++) {
6070 WriteOperand(Ops[i]);
6071 }
6072 break;
6073 }
6074 case spv::OpTypeBool:
6075 case spv::OpTypeVoid:
6076 case spv::OpTypeSampler:
6077 case spv::OpLabel:
6078 case spv::OpExtInstImport:
6079 case spv::OpTypePointer:
6080 case spv::OpTypeRuntimeArray:
6081 case spv::OpTypeStruct:
6082 case spv::OpTypeImage:
6083 case spv::OpTypeSampledImage:
6084 case spv::OpTypeInt:
6085 case spv::OpTypeFloat:
6086 case spv::OpTypeArray:
6087 case spv::OpTypeVector:
6088 case spv::OpTypeFunction: {
6089 WriteWordCountAndOpcode(Inst);
6090 WriteResultID(Inst);
6091 for (uint32_t i = 0; i < Ops.size(); i++) {
6092 WriteOperand(Ops[i]);
6093 }
6094 break;
6095 }
6096 case spv::OpFunction:
6097 case spv::OpFunctionParameter:
6098 case spv::OpAccessChain:
6099 case spv::OpPtrAccessChain:
6100 case spv::OpInBoundsAccessChain:
6101 case spv::OpUConvert:
6102 case spv::OpSConvert:
6103 case spv::OpConvertFToU:
6104 case spv::OpConvertFToS:
6105 case spv::OpConvertUToF:
6106 case spv::OpConvertSToF:
6107 case spv::OpFConvert:
6108 case spv::OpConvertPtrToU:
6109 case spv::OpConvertUToPtr:
6110 case spv::OpBitcast:
6111 case spv::OpIAdd:
6112 case spv::OpFAdd:
6113 case spv::OpISub:
6114 case spv::OpFSub:
6115 case spv::OpIMul:
6116 case spv::OpFMul:
6117 case spv::OpUDiv:
6118 case spv::OpSDiv:
6119 case spv::OpFDiv:
6120 case spv::OpUMod:
6121 case spv::OpSRem:
6122 case spv::OpFRem:
6123 case spv::OpBitwiseOr:
6124 case spv::OpBitwiseXor:
6125 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006126 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006127 case spv::OpShiftLeftLogical:
6128 case spv::OpShiftRightLogical:
6129 case spv::OpShiftRightArithmetic:
6130 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006131 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006132 case spv::OpCompositeExtract:
6133 case spv::OpVectorExtractDynamic:
6134 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006135 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006136 case spv::OpVectorInsertDynamic:
6137 case spv::OpVectorShuffle:
6138 case spv::OpIEqual:
6139 case spv::OpINotEqual:
6140 case spv::OpUGreaterThan:
6141 case spv::OpUGreaterThanEqual:
6142 case spv::OpULessThan:
6143 case spv::OpULessThanEqual:
6144 case spv::OpSGreaterThan:
6145 case spv::OpSGreaterThanEqual:
6146 case spv::OpSLessThan:
6147 case spv::OpSLessThanEqual:
6148 case spv::OpFOrdEqual:
6149 case spv::OpFOrdGreaterThan:
6150 case spv::OpFOrdGreaterThanEqual:
6151 case spv::OpFOrdLessThan:
6152 case spv::OpFOrdLessThanEqual:
6153 case spv::OpFOrdNotEqual:
6154 case spv::OpFUnordEqual:
6155 case spv::OpFUnordGreaterThan:
6156 case spv::OpFUnordGreaterThanEqual:
6157 case spv::OpFUnordLessThan:
6158 case spv::OpFUnordLessThanEqual:
6159 case spv::OpFUnordNotEqual:
6160 case spv::OpExtInst:
6161 case spv::OpIsInf:
6162 case spv::OpIsNan:
6163 case spv::OpAny:
6164 case spv::OpAll:
6165 case spv::OpUndef:
6166 case spv::OpConstantNull:
6167 case spv::OpLogicalOr:
6168 case spv::OpLogicalAnd:
6169 case spv::OpLogicalNot:
6170 case spv::OpLogicalNotEqual:
6171 case spv::OpConstantComposite:
6172 case spv::OpSpecConstantComposite:
6173 case spv::OpConstantTrue:
6174 case spv::OpConstantFalse:
6175 case spv::OpConstant:
6176 case spv::OpSpecConstant:
6177 case spv::OpVariable:
6178 case spv::OpFunctionCall:
6179 case spv::OpSampledImage:
6180 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006181 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006182 case spv::OpSelect:
6183 case spv::OpPhi:
6184 case spv::OpLoad:
6185 case spv::OpAtomicIAdd:
6186 case spv::OpAtomicISub:
6187 case spv::OpAtomicExchange:
6188 case spv::OpAtomicIIncrement:
6189 case spv::OpAtomicIDecrement:
6190 case spv::OpAtomicCompareExchange:
6191 case spv::OpAtomicUMin:
6192 case spv::OpAtomicSMin:
6193 case spv::OpAtomicUMax:
6194 case spv::OpAtomicSMax:
6195 case spv::OpAtomicAnd:
6196 case spv::OpAtomicOr:
6197 case spv::OpAtomicXor:
6198 case spv::OpDot: {
6199 WriteWordCountAndOpcode(Inst);
6200 WriteOperand(Ops[0]);
6201 WriteResultID(Inst);
6202 for (uint32_t i = 1; i < Ops.size(); i++) {
6203 WriteOperand(Ops[i]);
6204 }
6205 break;
6206 }
6207 }
6208 }
6209}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006210
alan-bakerb6b09dc2018-11-08 16:59:28 -05006211bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006212 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006213 case Type::HalfTyID:
6214 case Type::FloatTyID:
6215 case Type::DoubleTyID:
6216 case Type::IntegerTyID:
6217 case Type::VectorTyID:
6218 return true;
6219 case Type::PointerTyID: {
6220 const PointerType *pointer_type = cast<PointerType>(type);
6221 if (pointer_type->getPointerAddressSpace() !=
6222 AddressSpace::UniformConstant) {
6223 auto pointee_type = pointer_type->getPointerElementType();
6224 if (pointee_type->isStructTy() &&
6225 cast<StructType>(pointee_type)->isOpaque()) {
6226 // Images and samplers are not nullable.
6227 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006228 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006229 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006230 return true;
6231 }
6232 case Type::ArrayTyID:
6233 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6234 case Type::StructTyID: {
6235 const StructType *struct_type = cast<StructType>(type);
6236 // Images and samplers are not nullable.
6237 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006238 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006239 for (const auto element : struct_type->elements()) {
6240 if (!IsTypeNullable(element))
6241 return false;
6242 }
6243 return true;
6244 }
6245 default:
6246 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006247 }
6248}
Alan Bakerfcda9482018-10-02 17:09:59 -04006249
6250void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6251 if (auto *offsets_md =
6252 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6253 // Metdata is stored as key-value pair operands. The first element of each
6254 // operand is the type and the second is a vector of offsets.
6255 for (const auto *operand : offsets_md->operands()) {
6256 const auto *pair = cast<MDTuple>(operand);
6257 auto *type =
6258 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6259 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6260 std::vector<uint32_t> offsets;
6261 for (const Metadata *offset_md : offset_vector->operands()) {
6262 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006263 offsets.push_back(static_cast<uint32_t>(
6264 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006265 }
6266 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6267 }
6268 }
6269
6270 if (auto *sizes_md =
6271 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6272 // Metadata is stored as key-value pair operands. The first element of each
6273 // operand is the type and the second is a triple of sizes: type size in
6274 // bits, store size and alloc size.
6275 for (const auto *operand : sizes_md->operands()) {
6276 const auto *pair = cast<MDTuple>(operand);
6277 auto *type =
6278 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6279 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6280 uint64_t type_size_in_bits =
6281 cast<ConstantInt>(
6282 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6283 ->getZExtValue();
6284 uint64_t type_store_size =
6285 cast<ConstantInt>(
6286 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6287 ->getZExtValue();
6288 uint64_t type_alloc_size =
6289 cast<ConstantInt>(
6290 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6291 ->getZExtValue();
6292 RemappedUBOTypeSizes.insert(std::make_pair(
6293 type, std::make_tuple(type_size_in_bits, type_store_size,
6294 type_alloc_size)));
6295 }
6296 }
6297}
6298
6299uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6300 const DataLayout &DL) {
6301 auto iter = RemappedUBOTypeSizes.find(type);
6302 if (iter != RemappedUBOTypeSizes.end()) {
6303 return std::get<0>(iter->second);
6304 }
6305
6306 return DL.getTypeSizeInBits(type);
6307}
6308
6309uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6310 auto iter = RemappedUBOTypeSizes.find(type);
6311 if (iter != RemappedUBOTypeSizes.end()) {
6312 return std::get<1>(iter->second);
6313 }
6314
6315 return DL.getTypeStoreSize(type);
6316}
6317
6318uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6319 auto iter = RemappedUBOTypeSizes.find(type);
6320 if (iter != RemappedUBOTypeSizes.end()) {
6321 return std::get<2>(iter->second);
6322 }
6323
6324 return DL.getTypeAllocSize(type);
6325}