blob: 3a74b7cc8e198866eda583781c11d76af9e8b3c3 [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"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
alan-bakerb6b09dc2018-11-08 16:59:28 -050080const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040081
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500127 SPIRVOperandList(const SPIRVOperandList &other) = delete;
128 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500136 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500145 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
alan-bakerb6b09dc2018-11-08 16:59:28 -0500153SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500156SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500159SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500162SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
163SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400164 return new SPIRVOperand(LITERAL_STRING, str);
165}
David Netoc6f3ab22018-04-06 18:02:31 -0400166
David Neto22f144c2017-06-12 14:26:21 -0400167struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400168 // Create an instruction with an opcode and no result ID, and with the given
169 // operands. This computes its own word count.
170 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
171 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
172 Operands(Ops.begin(), Ops.end()) {
173 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400174 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400175 }
176 }
177 // Create an instruction with an opcode and a no-zero result ID, and
178 // with the given operands. This computes its own word count.
179 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400180 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400181 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
182 Operands(Ops.begin(), Ops.end()) {
183 if (ResID == 0) {
184 llvm_unreachable("Result ID of 0 was provided");
185 }
186 for (auto *operand : Ops) {
187 WordCount += operand->GetNumWords();
188 }
189 }
David Neto22f144c2017-06-12 14:26:21 -0400190
David Netoee2660d2018-06-28 16:31:29 -0400191 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400192 uint16_t getOpcode() const { return Opcode; }
193 uint32_t getResultID() const { return ResultID; }
194 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
195
196private:
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t Opcode;
199 uint32_t ResultID;
200 SmallVector<SPIRVOperand *, 4> Operands;
201};
202
203struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400204 typedef DenseMap<Type *, uint32_t> TypeMapType;
205 typedef UniqueVector<Type *> TypeList;
206 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400207 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400208 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
209 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400210 // A vector of tuples, each of which is:
211 // - the LLVM instruction that we will later generate SPIR-V code for
212 // - where the SPIR-V instruction should be inserted
213 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400214 typedef std::vector<
215 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
216 DeferredInstVecType;
217 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
218 GlobalConstFuncMapType;
219
David Neto44795152017-07-13 15:45:28 -0400220 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 raw_pwrite_stream &out,
222 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400223 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
224 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400225 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400226 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400228 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400229 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500230 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0), max_local_spec_id_(0),
231 constant_i32_zero_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400232
233 void getAnalysisUsage(AnalysisUsage &AU) const override {
234 AU.addRequired<DominatorTreeWrapperPass>();
235 AU.addRequired<LoopInfoWrapperPass>();
236 }
237
238 virtual bool runOnModule(Module &module) override;
239
240 // output the SPIR-V header block
241 void outputHeader();
242
243 // patch the SPIR-V header block
244 void patchHeader();
245
246 uint32_t lookupType(Type *Ty) {
247 if (Ty->isPointerTy() &&
248 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
249 auto PointeeTy = Ty->getPointerElementType();
250 if (PointeeTy->isStructTy() &&
251 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
252 Ty = PointeeTy;
253 }
254 }
255
David Neto862b7d82018-06-14 18:48:37 -0400256 auto where = TypeMap.find(Ty);
257 if (where == TypeMap.end()) {
258 if (Ty) {
259 errs() << "Unhandled type " << *Ty << "\n";
260 } else {
261 errs() << "Unhandled type (null)\n";
262 }
David Netoe439d702018-03-23 13:14:08 -0700263 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400264 }
265
David Neto862b7d82018-06-14 18:48:37 -0400266 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400267 }
268 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
269 TypeList &getTypeList() { return Types; };
270 ValueList &getConstantList() { return Constants; };
271 ValueMapType &getValueMap() { return ValueMap; }
272 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
273 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400274 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
275 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
276 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
277 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
278 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500279 bool hasVariablePointers() {
280 return true; /* We use StorageBuffer everywhere */
281 };
David Neto22f144c2017-06-12 14:26:21 -0400282 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500283 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
284 return samplerMap;
285 }
David Neto22f144c2017-06-12 14:26:21 -0400286 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
287 return GlobalConstFuncTypeMap;
288 }
289 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
290 return GlobalConstArgumentSet;
291 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500292 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400293
David Netoc6f3ab22018-04-06 18:02:31 -0400294 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500295 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
296 // *not* be converted to a storage buffer, replace each such global variable
297 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400298 void FindGlobalConstVars(Module &M, const DataLayout &DL);
299 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
300 // ModuleOrderedResourceVars.
301 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400302 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400303 bool FindExtInst(Module &M);
304 void FindTypePerGlobalVar(GlobalVariable &GV);
305 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400306 void FindTypesForSamplerMap(Module &M);
307 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500308 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
309 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400310 void FindType(Type *Ty);
311 void FindConstantPerGlobalVar(GlobalVariable &GV);
312 void FindConstantPerFunc(Function &F);
313 void FindConstant(Value *V);
314 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400315 // Generates instructions for SPIR-V types corresponding to the LLVM types
316 // saved in the |Types| member. A type follows its subtypes. IDs are
317 // allocated sequentially starting with the current value of nextID, and
318 // with a type following its subtypes. Also updates nextID to just beyond
319 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500320 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400321 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400322 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400323 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400324 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400325 // Generate descriptor map entries for resource variables associated with
326 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400329 // Generate OpVariables for %clspv.resource.var.* calls.
330 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400331 void GenerateFuncPrologue(Function &F);
332 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400333 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400334 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
335 spv::Op GetSPIRVCastOpcode(Instruction &I);
336 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
337 void GenerateInstruction(Instruction &I);
338 void GenerateFuncEpilogue();
339 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500340 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400341 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400342 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
343 // have been created.
344 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400345 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400346 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400347 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400348 // Returns the GLSL extended instruction enum that the given function
349 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400350 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400351 // Returns the GLSL extended instruction enum indirectly used by the given
352 // function. That is, to implement the given function, we use an extended
353 // instruction plus one more instruction. If none, then returns the 0 value,
354 // i.e. GLSLstd4580Bad.
355 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
356 // Returns the single GLSL extended instruction used directly or
357 // indirectly by the given function call.
358 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400359 void PrintResID(SPIRVInstruction *Inst);
360 void PrintOpcode(SPIRVInstruction *Inst);
361 void PrintOperand(SPIRVOperand *Op);
362 void PrintCapability(SPIRVOperand *Op);
363 void PrintExtInst(SPIRVOperand *Op);
364 void PrintAddrModel(SPIRVOperand *Op);
365 void PrintMemModel(SPIRVOperand *Op);
366 void PrintExecModel(SPIRVOperand *Op);
367 void PrintExecMode(SPIRVOperand *Op);
368 void PrintSourceLanguage(SPIRVOperand *Op);
369 void PrintFuncCtrl(SPIRVOperand *Op);
370 void PrintStorageClass(SPIRVOperand *Op);
371 void PrintDecoration(SPIRVOperand *Op);
372 void PrintBuiltIn(SPIRVOperand *Op);
373 void PrintSelectionControl(SPIRVOperand *Op);
374 void PrintLoopControl(SPIRVOperand *Op);
375 void PrintDimensionality(SPIRVOperand *Op);
376 void PrintImageFormat(SPIRVOperand *Op);
377 void PrintMemoryAccess(SPIRVOperand *Op);
378 void PrintImageOperandsType(SPIRVOperand *Op);
379 void WriteSPIRVAssembly();
380 void WriteOneWord(uint32_t Word);
381 void WriteResultID(SPIRVInstruction *Inst);
382 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
383 void WriteOperand(SPIRVOperand *Op);
384 void WriteSPIRVBinary();
385
Alan Baker9bf93fb2018-08-28 16:59:26 -0400386 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500387 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400388
Alan Bakerfcda9482018-10-02 17:09:59 -0400389 // Populate UBO remapped type maps.
390 void PopulateUBOTypeMaps(Module &module);
391
392 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
393 // uses the internal map, otherwise it falls back on the data layout.
394 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
395 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
396 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
397
David Neto22f144c2017-06-12 14:26:21 -0400398private:
399 static char ID;
David Neto44795152017-07-13 15:45:28 -0400400 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400401 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400402
403 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
404 // convert to other formats on demand?
405
406 // When emitting a C initialization list, the WriteSPIRVBinary method
407 // will actually write its words to this vector via binaryTempOut.
408 SmallVector<char, 100> binaryTempUnderlyingVector;
409 raw_svector_ostream binaryTempOut;
410
411 // Binary output writes to this stream, which might be |out| or
412 // |binaryTempOut|. It's the latter when we really want to write a C
413 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500414 raw_pwrite_stream* binaryOut;
415 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400416 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400417 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400418 uint64_t patchBoundOffset;
419 uint32_t nextID;
420
David Neto19a1bad2017-08-25 15:01:41 -0400421 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400422 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400423 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400424 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400425 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400426 TypeList Types;
427 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400428 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400429 ValueMapType ValueMap;
430 ValueMapType AllocatedValueMap;
431 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400432
David Neto22f144c2017-06-12 14:26:21 -0400433 EntryPointVecType EntryPointVec;
434 DeferredInstVecType DeferredInstVec;
435 ValueList EntryPointInterfacesVec;
436 uint32_t OpExtInstImportID;
437 std::vector<uint32_t> BuiltinDimensionVec;
438 bool HasVariablePointers;
439 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500440 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700441
442 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700443 // will map F's type to (G, index of the parameter), where in a first phase
444 // G is F's type. During FindTypePerFunc, G will be changed to F's type
445 // but replacing the pointer-to-constant parameter with
446 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700447 // TODO(dneto): This doesn't seem general enough? A function might have
448 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400449 GlobalConstFuncMapType GlobalConstFuncTypeMap;
450 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400451 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700452 // or array types, and which point into transparent memory (StorageBuffer
453 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400454 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700455 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400456
457 // This is truly ugly, but works around what look like driver bugs.
458 // For get_local_size, an earlier part of the flow has created a module-scope
459 // variable in Private address space to hold the value for the workgroup
460 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
461 // When this is present, save the IDs of the initializer value and variable
462 // in these two variables. We only ever do a vector load from it, and
463 // when we see one of those, substitute just the value of the intializer.
464 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700465 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400466 uint32_t WorkgroupSizeValueID;
467 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400468
David Neto862b7d82018-06-14 18:48:37 -0400469 // Bookkeeping for mapping kernel arguments to resource variables.
470 struct ResourceVarInfo {
471 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
472 Function *fn, clspv::ArgKind arg_kind_arg)
473 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
474 var_fn(fn), arg_kind(arg_kind_arg),
475 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
476 const int index; // Index into ResourceVarInfoList
477 const unsigned descriptor_set;
478 const unsigned binding;
479 Function *const var_fn; // The @clspv.resource.var.* function.
480 const clspv::ArgKind arg_kind;
481 const unsigned addr_space; // The LLVM address space
482 // The SPIR-V ID of the OpVariable. Not populated at construction time.
483 uint32_t var_id = 0;
484 };
485 // A list of resource var info. Each one correponds to a module-scope
486 // resource variable we will have to create. Resource var indices are
487 // indices into this vector.
488 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
489 // This is a vector of pointers of all the resource vars, but ordered by
490 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500491 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400492 // Map a function to the ordered list of resource variables it uses, one for
493 // each argument. If an argument does not use a resource variable, it
494 // will have a null pointer entry.
495 using FunctionToResourceVarsMapType =
496 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
497 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
498
499 // What LLVM types map to SPIR-V types needing layout? These are the
500 // arrays and structures supporting storage buffers and uniform buffers.
501 TypeList TypesNeedingLayout;
502 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
503 UniqueVector<StructType *> StructTypesNeedingBlock;
504 // For a call that represents a load from an opaque type (samplers, images),
505 // map it to the variable id it should load from.
506 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700507
Alan Baker202c8c72018-08-13 13:47:44 -0400508 // One larger than the maximum used SpecId for pointer-to-local arguments.
509 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400510 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500511 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400512 LocalArgList LocalArgs;
513 // Information about a pointer-to-local argument.
514 struct LocalArgInfo {
515 // The SPIR-V ID of the array variable.
516 uint32_t variable_id;
517 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500518 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400519 // The ID of the array type.
520 uint32_t array_size_id;
521 // The ID of the array type.
522 uint32_t array_type_id;
523 // The ID of the pointer to the array type.
524 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400525 // The specialization constant ID of the array size.
526 int spec_id;
527 };
Alan Baker202c8c72018-08-13 13:47:44 -0400528 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500529 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400530 // A mapping from SpecId to its LocalArgInfo.
531 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400532 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500533 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400534 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500535 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
536 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400537
538 // The ID of 32-bit integer zero constant. This is only valid after
539 // GenerateSPIRVConstants has run.
540 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400541};
542
543char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400544
alan-bakerb6b09dc2018-11-08 16:59:28 -0500545} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400546
547namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500548ModulePass *createSPIRVProducerPass(
549 raw_pwrite_stream &out,
550 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
551 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
552 bool outputCInitList) {
553 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
554 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400555}
David Netoc2c368d2017-06-30 16:50:17 -0400556} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400557
558bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400559 binaryOut = outputCInitList ? &binaryTempOut : &out;
560
David Neto257c3892018-04-11 13:19:45 -0400561 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
562
Alan Bakerfcda9482018-10-02 17:09:59 -0400563 PopulateUBOTypeMaps(module);
564
David Neto22f144c2017-06-12 14:26:21 -0400565 // SPIR-V always begins with its header information
566 outputHeader();
567
David Netoc6f3ab22018-04-06 18:02:31 -0400568 const DataLayout &DL = module.getDataLayout();
569
David Neto22f144c2017-06-12 14:26:21 -0400570 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400571 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400572
David Neto22f144c2017-06-12 14:26:21 -0400573 // Collect information on global variables too.
574 for (GlobalVariable &GV : module.globals()) {
575 // If the GV is one of our special __spirv_* variables, remove the
576 // initializer as it was only placed there to force LLVM to not throw the
577 // value away.
578 if (GV.getName().startswith("__spirv_")) {
579 GV.setInitializer(nullptr);
580 }
581
582 // Collect types' information from global variable.
583 FindTypePerGlobalVar(GV);
584
585 // Collect constant information from global variable.
586 FindConstantPerGlobalVar(GV);
587
588 // If the variable is an input, entry points need to know about it.
589 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400590 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400591 }
592 }
593
594 // If there are extended instructions, generate OpExtInstImport.
595 if (FindExtInst(module)) {
596 GenerateExtInstImport();
597 }
598
599 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400600 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400601
602 // Generate SPIRV constants.
603 GenerateSPIRVConstants();
604
605 // If we have a sampler map, we might have literal samplers to generate.
606 if (0 < getSamplerMap().size()) {
607 GenerateSamplers(module);
608 }
609
610 // Generate SPIRV variables.
611 for (GlobalVariable &GV : module.globals()) {
612 GenerateGlobalVar(GV);
613 }
David Neto862b7d82018-06-14 18:48:37 -0400614 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400615 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400616
617 // Generate SPIRV instructions for each function.
618 for (Function &F : module) {
619 if (F.isDeclaration()) {
620 continue;
621 }
622
David Neto862b7d82018-06-14 18:48:37 -0400623 GenerateDescriptorMapInfo(DL, F);
624
David Neto22f144c2017-06-12 14:26:21 -0400625 // Generate Function Prologue.
626 GenerateFuncPrologue(F);
627
628 // Generate SPIRV instructions for function body.
629 GenerateFuncBody(F);
630
631 // Generate Function Epilogue.
632 GenerateFuncEpilogue();
633 }
634
635 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400636 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400637
638 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400639 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400640
641 if (outputAsm) {
642 WriteSPIRVAssembly();
643 } else {
644 WriteSPIRVBinary();
645 }
646
647 // We need to patch the SPIR-V header to set bound correctly.
648 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400649
650 if (outputCInitList) {
651 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400652 std::ostringstream os;
653
David Neto57fb0b92017-08-04 15:35:09 -0400654 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400655 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400656 os << ",\n";
657 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400658 first = false;
659 };
660
661 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400662 const std::string str(binaryTempOut.str());
663 for (unsigned i = 0; i < str.size(); i += 4) {
664 const uint32_t a = static_cast<unsigned char>(str[i]);
665 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
666 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
667 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
668 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400669 }
670 os << "}\n";
671 out << os.str();
672 }
673
David Neto22f144c2017-06-12 14:26:21 -0400674 return false;
675}
676
677void SPIRVProducerPass::outputHeader() {
678 if (outputAsm) {
679 // for ASM output the header goes into 5 comments at the beginning of the
680 // file
681 out << "; SPIR-V\n";
682
683 // the major version number is in the 2nd highest byte
684 const uint32_t major = (spv::Version >> 16) & 0xFF;
685
686 // the minor version number is in the 2nd lowest byte
687 const uint32_t minor = (spv::Version >> 8) & 0xFF;
688 out << "; Version: " << major << "." << minor << "\n";
689
690 // use Codeplay's vendor ID
691 out << "; Generator: Codeplay; 0\n";
692
693 out << "; Bound: ";
694
695 // we record where we need to come back to and patch in the bound value
696 patchBoundOffset = out.tell();
697
698 // output one space per digit for the max size of a 32 bit unsigned integer
699 // (which is the maximum ID we could possibly be using)
700 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
701 out << " ";
702 }
703
704 out << "\n";
705
706 out << "; Schema: 0\n";
707 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400708 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500709 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400710 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500711 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400712
713 // use Codeplay's vendor ID
714 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400715 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400716
717 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400718 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400719
720 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400721 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400722
723 // output the schema (reserved for use and must be 0)
724 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400725 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400726 }
727}
728
729void SPIRVProducerPass::patchHeader() {
730 if (outputAsm) {
731 // get the string representation of the max bound used (nextID will be the
732 // max ID used)
733 auto asString = std::to_string(nextID);
734 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
735 } else {
736 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400737 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
738 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400739 }
740}
741
David Netoc6f3ab22018-04-06 18:02:31 -0400742void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400743 // This function generates LLVM IR for function such as global variable for
744 // argument, constant and pointer type for argument access. These information
745 // is artificial one because we need Vulkan SPIR-V output. This function is
746 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400747 LLVMContext &Context = M.getContext();
748
David Neto862b7d82018-06-14 18:48:37 -0400749 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400750
David Neto862b7d82018-06-14 18:48:37 -0400751 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400752
753 bool HasWorkGroupBuiltin = false;
754 for (GlobalVariable &GV : M.globals()) {
755 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
756 if (spv::BuiltInWorkgroupSize == BuiltinType) {
757 HasWorkGroupBuiltin = true;
758 }
759 }
760
David Neto862b7d82018-06-14 18:48:37 -0400761 FindTypesForSamplerMap(M);
762 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400763 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400764
David Neto862b7d82018-06-14 18:48:37 -0400765 // TODO(dneto): Delete the next 3 vars.
766
767 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400768 // Map kernel functions to their ordinal number in the compilation unit.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500769 UniqueVector<Function *> KernelOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400770
771 // Map the global variables created for kernel args to their creation
772 // order.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500773 UniqueVector<GlobalVariable *> KernelArgVarOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400774
David Neto862b7d82018-06-14 18:48:37 -0400775 // For each kernel argument type, record the kernel arg global resource
776 // variables generated for that type, the function in which that variable
777 // was most recently used, and the binding number it took. For
778 // reproducibility, we track things by ordinal number (rather than pointer),
779 // and we use a std::set rather than DenseSet since std::set maintains an
780 // ordering. Each tuple is the ordinals of the kernel function, the binding
781 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400782 //
783 // This table lets us reuse module-scope StorageBuffer variables between
784 // different kernels.
785 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
786 GVarsForType;
787
David Neto862b7d82018-06-14 18:48:37 -0400788 // These function calls need a <2 x i32> as an intermediate result but not
789 // the final result.
790 std::unordered_set<std::string> NeedsIVec2{
791 "_Z15get_image_width14ocl_image2d_ro",
792 "_Z15get_image_width14ocl_image2d_wo",
793 "_Z16get_image_height14ocl_image2d_ro",
794 "_Z16get_image_height14ocl_image2d_wo",
795 };
796
David Neto22f144c2017-06-12 14:26:21 -0400797 for (Function &F : M) {
798 // Handle kernel function first.
799 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
800 continue;
801 }
David Neto26aaf622017-10-23 18:11:53 -0400802 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400803
804 for (BasicBlock &BB : F) {
805 for (Instruction &I : BB) {
806 if (I.getOpcode() == Instruction::ZExt ||
807 I.getOpcode() == Instruction::SExt ||
808 I.getOpcode() == Instruction::UIToFP) {
809 // If there is zext with i1 type, it will be changed to OpSelect. The
810 // OpSelect needs constant 0 and 1 so the constants are added here.
811
812 auto OpTy = I.getOperand(0)->getType();
813
Kévin Petit24272b62018-10-18 19:16:12 +0000814 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400815 if (I.getOpcode() == Instruction::ZExt) {
816 APInt One(32, 1);
817 FindConstant(Constant::getNullValue(I.getType()));
818 FindConstant(Constant::getIntegerValue(I.getType(), One));
819 } else if (I.getOpcode() == Instruction::SExt) {
820 APInt MinusOne(32, UINT64_MAX, true);
821 FindConstant(Constant::getNullValue(I.getType()));
822 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
823 } else {
824 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
825 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
826 }
827 }
828 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400829 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400830
831 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400832 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400833 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400834 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400835 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
836 TypeMapType &OpImageTypeMap = getImageTypeMap();
837 Type *ImageTy =
838 Call->getArgOperand(0)->getType()->getPointerElementType();
839 OpImageTypeMap[ImageTy] = 0;
840
841 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
842 }
David Neto5c22a252018-03-15 16:07:41 -0400843
David Neto862b7d82018-06-14 18:48:37 -0400844 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400845 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
846 }
David Neto22f144c2017-06-12 14:26:21 -0400847 }
848 }
849 }
850
David Neto22f144c2017-06-12 14:26:21 -0400851 if (const MDNode *MD =
852 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
853 // We generate constants if the WorkgroupSize builtin is being used.
854 if (HasWorkGroupBuiltin) {
855 // Collect constant information for work group size.
856 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
857 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
858 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
859 }
860 }
861
David Neto22f144c2017-06-12 14:26:21 -0400862 // Collect types' information from function.
863 FindTypePerFunc(F);
864
865 // Collect constant information from function.
866 FindConstantPerFunc(F);
867 }
868
869 for (Function &F : M) {
870 // Handle non-kernel functions.
871 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
872 continue;
873 }
874
875 for (BasicBlock &BB : F) {
876 for (Instruction &I : BB) {
877 if (I.getOpcode() == Instruction::ZExt ||
878 I.getOpcode() == Instruction::SExt ||
879 I.getOpcode() == Instruction::UIToFP) {
880 // If there is zext with i1 type, it will be changed to OpSelect. The
881 // OpSelect needs constant 0 and 1 so the constants are added here.
882
883 auto OpTy = I.getOperand(0)->getType();
884
Kévin Petit24272b62018-10-18 19:16:12 +0000885 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400886 if (I.getOpcode() == Instruction::ZExt) {
887 APInt One(32, 1);
888 FindConstant(Constant::getNullValue(I.getType()));
889 FindConstant(Constant::getIntegerValue(I.getType(), One));
890 } else if (I.getOpcode() == Instruction::SExt) {
891 APInt MinusOne(32, UINT64_MAX, true);
892 FindConstant(Constant::getNullValue(I.getType()));
893 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
894 } else {
895 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
896 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
897 }
898 }
899 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
900 Function *Callee = Call->getCalledFunction();
901
902 // Handle image type specially.
903 if (Callee->getName().equals(
904 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
905 Callee->getName().equals(
906 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
907 TypeMapType &OpImageTypeMap = getImageTypeMap();
908 Type *ImageTy =
909 Call->getArgOperand(0)->getType()->getPointerElementType();
910 OpImageTypeMap[ImageTy] = 0;
911
912 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
913 }
914 }
915 }
916 }
917
918 if (M.getTypeByName("opencl.image2d_ro_t") ||
919 M.getTypeByName("opencl.image2d_wo_t") ||
920 M.getTypeByName("opencl.image3d_ro_t") ||
921 M.getTypeByName("opencl.image3d_wo_t")) {
922 // Assume Image type's sampled type is float type.
923 FindType(Type::getFloatTy(Context));
924 }
925
926 // Collect types' information from function.
927 FindTypePerFunc(F);
928
929 // Collect constant information from function.
930 FindConstantPerFunc(F);
931 }
932}
933
David Neto862b7d82018-06-14 18:48:37 -0400934void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
935 SmallVector<GlobalVariable *, 8> GVList;
936 SmallVector<GlobalVariable *, 8> DeadGVList;
937 for (GlobalVariable &GV : M.globals()) {
938 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
939 if (GV.use_empty()) {
940 DeadGVList.push_back(&GV);
941 } else {
942 GVList.push_back(&GV);
943 }
944 }
945 }
946
947 // Remove dead global __constant variables.
948 for (auto GV : DeadGVList) {
949 GV->eraseFromParent();
950 }
951 DeadGVList.clear();
952
953 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
954 // For now, we only support a single storage buffer.
955 if (GVList.size() > 0) {
956 assert(GVList.size() == 1);
957 const auto *GV = GVList[0];
958 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400959 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400960 const size_t kConstantMaxSize = 65536;
961 if (constants_byte_size > kConstantMaxSize) {
962 outs() << "Max __constant capacity of " << kConstantMaxSize
963 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
964 llvm_unreachable("Max __constant capacity exceeded");
965 }
966 }
967 } else {
968 // Change global constant variable's address space to ModuleScopePrivate.
969 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
970 for (auto GV : GVList) {
971 // Create new gv with ModuleScopePrivate address space.
972 Type *NewGVTy = GV->getType()->getPointerElementType();
973 GlobalVariable *NewGV = new GlobalVariable(
974 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
975 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
976 NewGV->takeName(GV);
977
978 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
979 SmallVector<User *, 8> CandidateUsers;
980
981 auto record_called_function_type_as_user =
982 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
983 // Find argument index.
984 unsigned index = 0;
985 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
986 if (gv == call->getOperand(i)) {
987 // TODO(dneto): Should we break here?
988 index = i;
989 }
990 }
991
992 // Record function type with global constant.
993 GlobalConstFuncTyMap[call->getFunctionType()] =
994 std::make_pair(call->getFunctionType(), index);
995 };
996
997 for (User *GVU : GVUsers) {
998 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
999 record_called_function_type_as_user(GV, Call);
1000 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1001 // Check GEP users.
1002 for (User *GEPU : GEP->users()) {
1003 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1004 record_called_function_type_as_user(GEP, GEPCall);
1005 }
1006 }
1007 }
1008
1009 CandidateUsers.push_back(GVU);
1010 }
1011
1012 for (User *U : CandidateUsers) {
1013 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001014 if (!isa<Constant>(U)) {
1015 // #254: Can't change operands of a constant, but this shouldn't be
1016 // something that sticks around in the module.
1017 U->replaceUsesOfWith(GV, NewGV);
1018 }
David Neto862b7d82018-06-14 18:48:37 -04001019 }
1020
1021 // Delete original gv.
1022 GV->eraseFromParent();
1023 }
1024 }
1025}
1026
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001027void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001028 ResourceVarInfoList.clear();
1029 FunctionToResourceVarsMap.clear();
1030 ModuleOrderedResourceVars.reset();
1031 // Normally, there is one resource variable per clspv.resource.var.*
1032 // function, since that is unique'd by arg type and index. By design,
1033 // we can share these resource variables across kernels because all
1034 // kernels use the same descriptor set.
1035 //
1036 // But if the user requested distinct descriptor sets per kernel, then
1037 // the descriptor allocator has made different (set,binding) pairs for
1038 // the same (type,arg_index) pair. Since we can decorate a resource
1039 // variable with only exactly one DescriptorSet and Binding, we are
1040 // forced in this case to make distinct resource variables whenever
1041 // the same clspv.reource.var.X function is seen with disintct
1042 // (set,binding) values.
1043 const bool always_distinct_sets =
1044 clspv::Option::DistinctKernelDescriptorSets();
1045 for (Function &F : M) {
1046 // Rely on the fact the resource var functions have a stable ordering
1047 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001048 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001049 // Find all calls to this function with distinct set and binding pairs.
1050 // Save them in ResourceVarInfoList.
1051
1052 // Determine uniqueness of the (set,binding) pairs only withing this
1053 // one resource-var builtin function.
1054 using SetAndBinding = std::pair<unsigned, unsigned>;
1055 // Maps set and binding to the resource var info.
1056 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1057 bool first_use = true;
1058 for (auto &U : F.uses()) {
1059 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1060 const auto set = unsigned(
1061 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1062 const auto binding = unsigned(
1063 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1064 const auto arg_kind = clspv::ArgKind(
1065 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1066 const auto arg_index = unsigned(
1067 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1068
1069 // Find or make the resource var info for this combination.
1070 ResourceVarInfo *rv = nullptr;
1071 if (always_distinct_sets) {
1072 // Make a new resource var any time we see a different
1073 // (set,binding) pair.
1074 SetAndBinding key{set, binding};
1075 auto where = set_and_binding_map.find(key);
1076 if (where == set_and_binding_map.end()) {
1077 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1078 binding, &F, arg_kind);
1079 ResourceVarInfoList.emplace_back(rv);
1080 set_and_binding_map[key] = rv;
1081 } else {
1082 rv = where->second;
1083 }
1084 } else {
1085 // The default is to make exactly one resource for each
1086 // clspv.resource.var.* function.
1087 if (first_use) {
1088 first_use = false;
1089 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1090 binding, &F, arg_kind);
1091 ResourceVarInfoList.emplace_back(rv);
1092 } else {
1093 rv = ResourceVarInfoList.back().get();
1094 }
1095 }
1096
1097 // Now populate FunctionToResourceVarsMap.
1098 auto &mapping =
1099 FunctionToResourceVarsMap[call->getParent()->getParent()];
1100 while (mapping.size() <= arg_index) {
1101 mapping.push_back(nullptr);
1102 }
1103 mapping[arg_index] = rv;
1104 }
1105 }
1106 }
1107 }
1108
1109 // Populate ModuleOrderedResourceVars.
1110 for (Function &F : M) {
1111 auto where = FunctionToResourceVarsMap.find(&F);
1112 if (where != FunctionToResourceVarsMap.end()) {
1113 for (auto &rv : where->second) {
1114 if (rv != nullptr) {
1115 ModuleOrderedResourceVars.insert(rv);
1116 }
1117 }
1118 }
1119 }
1120 if (ShowResourceVars) {
1121 for (auto *info : ModuleOrderedResourceVars) {
1122 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1123 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1124 << "\n";
1125 }
1126 }
1127}
1128
David Neto22f144c2017-06-12 14:26:21 -04001129bool SPIRVProducerPass::FindExtInst(Module &M) {
1130 LLVMContext &Context = M.getContext();
1131 bool HasExtInst = false;
1132
1133 for (Function &F : M) {
1134 for (BasicBlock &BB : F) {
1135 for (Instruction &I : BB) {
1136 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1137 Function *Callee = Call->getCalledFunction();
1138 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001139 auto callee_name = Callee->getName();
1140 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1141 const glsl::ExtInst IndirectEInst =
1142 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001143
David Neto3fbb4072017-10-16 11:28:14 -04001144 HasExtInst |=
1145 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1146
1147 if (IndirectEInst) {
1148 // Register extra constants if needed.
1149
1150 // Registers a type and constant for computing the result of the
1151 // given instruction. If the result of the instruction is a vector,
1152 // then make a splat vector constant with the same number of
1153 // elements.
1154 auto register_constant = [this, &I](Constant *constant) {
1155 FindType(constant->getType());
1156 FindConstant(constant);
1157 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1158 // Register the splat vector of the value with the same
1159 // width as the result of the instruction.
1160 auto *vec_constant = ConstantVector::getSplat(
1161 static_cast<unsigned>(vectorTy->getNumElements()),
1162 constant);
1163 FindConstant(vec_constant);
1164 FindType(vec_constant->getType());
1165 }
1166 };
1167 switch (IndirectEInst) {
1168 case glsl::ExtInstFindUMsb:
1169 // clz needs OpExtInst and OpISub with constant 31, or splat
1170 // vector of 31. Add it to the constant list here.
1171 register_constant(
1172 ConstantInt::get(Type::getInt32Ty(Context), 31));
1173 break;
1174 case glsl::ExtInstAcos:
1175 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001176 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001177 case glsl::ExtInstAtan2:
1178 // We need 1/pi for acospi, asinpi, atan2pi.
1179 register_constant(
1180 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1181 break;
1182 default:
1183 assert(false && "internally inconsistent");
1184 }
David Neto22f144c2017-06-12 14:26:21 -04001185 }
1186 }
1187 }
1188 }
1189 }
1190
1191 return HasExtInst;
1192}
1193
1194void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1195 // Investigate global variable's type.
1196 FindType(GV.getType());
1197}
1198
1199void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1200 // Investigate function's type.
1201 FunctionType *FTy = F.getFunctionType();
1202
1203 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1204 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001205 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001206 if (GlobalConstFuncTyMap.count(FTy)) {
1207 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1208 SmallVector<Type *, 4> NewFuncParamTys;
1209 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1210 Type *ParamTy = FTy->getParamType(i);
1211 if (i == GVCstArgIdx) {
1212 Type *EleTy = ParamTy->getPointerElementType();
1213 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1214 }
1215
1216 NewFuncParamTys.push_back(ParamTy);
1217 }
1218
1219 FunctionType *NewFTy =
1220 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1221 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1222 FTy = NewFTy;
1223 }
1224
1225 FindType(FTy);
1226 } else {
1227 // As kernel functions do not have parameters, create new function type and
1228 // add it to type map.
1229 SmallVector<Type *, 4> NewFuncParamTys;
1230 FunctionType *NewFTy =
1231 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1232 FindType(NewFTy);
1233 }
1234
1235 // Investigate instructions' type in function body.
1236 for (BasicBlock &BB : F) {
1237 for (Instruction &I : BB) {
1238 if (isa<ShuffleVectorInst>(I)) {
1239 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1240 // Ignore type for mask of shuffle vector instruction.
1241 if (i == 2) {
1242 continue;
1243 }
1244
1245 Value *Op = I.getOperand(i);
1246 if (!isa<MetadataAsValue>(Op)) {
1247 FindType(Op->getType());
1248 }
1249 }
1250
1251 FindType(I.getType());
1252 continue;
1253 }
1254
David Neto862b7d82018-06-14 18:48:37 -04001255 CallInst *Call = dyn_cast<CallInst>(&I);
1256
1257 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001258 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001259 // This is a fake call representing access to a resource variable.
1260 // We handle that elsewhere.
1261 continue;
1262 }
1263
Alan Baker202c8c72018-08-13 13:47:44 -04001264 if (Call && Call->getCalledFunction()->getName().startswith(
1265 clspv::WorkgroupAccessorFunction())) {
1266 // This is a fake call representing access to a workgroup variable.
1267 // We handle that elsewhere.
1268 continue;
1269 }
1270
David Neto22f144c2017-06-12 14:26:21 -04001271 // Work through the operands of the instruction.
1272 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1273 Value *const Op = I.getOperand(i);
1274 // If any of the operands is a constant, find the type!
1275 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1276 FindType(Op->getType());
1277 }
1278 }
1279
1280 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001281 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001282 // Avoid to check call instruction's type.
1283 break;
1284 }
Alan Baker202c8c72018-08-13 13:47:44 -04001285 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1286 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1287 clspv::WorkgroupAccessorFunction())) {
1288 // This is a fake call representing access to a workgroup variable.
1289 // We handle that elsewhere.
1290 continue;
1291 }
1292 }
David Neto22f144c2017-06-12 14:26:21 -04001293 if (!isa<MetadataAsValue>(&Op)) {
1294 FindType(Op->getType());
1295 continue;
1296 }
1297 }
1298
David Neto22f144c2017-06-12 14:26:21 -04001299 // We don't want to track the type of this call as we are going to replace
1300 // it.
David Neto862b7d82018-06-14 18:48:37 -04001301 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001302 Call->getCalledFunction()->getName())) {
1303 continue;
1304 }
1305
1306 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1307 // If gep's base operand has ModuleScopePrivate address space, make gep
1308 // return ModuleScopePrivate address space.
1309 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1310 // Add pointer type with private address space for global constant to
1311 // type list.
1312 Type *EleTy = I.getType()->getPointerElementType();
1313 Type *NewPTy =
1314 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1315
1316 FindType(NewPTy);
1317 continue;
1318 }
1319 }
1320
1321 FindType(I.getType());
1322 }
1323 }
1324}
1325
David Neto862b7d82018-06-14 18:48:37 -04001326void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1327 // If we are using a sampler map, find the type of the sampler.
1328 if (M.getFunction("clspv.sampler.var.literal") ||
1329 0 < getSamplerMap().size()) {
1330 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1331 if (!SamplerStructTy) {
1332 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1333 }
1334
1335 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1336
1337 FindType(SamplerTy);
1338 }
1339}
1340
1341void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1342 // Record types so they are generated.
1343 TypesNeedingLayout.reset();
1344 StructTypesNeedingBlock.reset();
1345
1346 // To match older clspv codegen, generate the float type first if required
1347 // for images.
1348 for (const auto *info : ModuleOrderedResourceVars) {
1349 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1350 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1351 // We need "float" for the sampled component type.
1352 FindType(Type::getFloatTy(M.getContext()));
1353 // We only need to find it once.
1354 break;
1355 }
1356 }
1357
1358 for (const auto *info : ModuleOrderedResourceVars) {
1359 Type *type = info->var_fn->getReturnType();
1360
1361 switch (info->arg_kind) {
1362 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001363 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001364 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1365 StructTypesNeedingBlock.insert(sty);
1366 } else {
1367 errs() << *type << "\n";
1368 llvm_unreachable("Buffer arguments must map to structures!");
1369 }
1370 break;
1371 case clspv::ArgKind::Pod:
1372 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1373 StructTypesNeedingBlock.insert(sty);
1374 } else {
1375 errs() << *type << "\n";
1376 llvm_unreachable("POD arguments must map to structures!");
1377 }
1378 break;
1379 case clspv::ArgKind::ReadOnlyImage:
1380 case clspv::ArgKind::WriteOnlyImage:
1381 case clspv::ArgKind::Sampler:
1382 // Sampler and image types map to the pointee type but
1383 // in the uniform constant address space.
1384 type = PointerType::get(type->getPointerElementType(),
1385 clspv::AddressSpace::UniformConstant);
1386 break;
1387 default:
1388 break;
1389 }
1390
1391 // The converted type is the type of the OpVariable we will generate.
1392 // If the pointee type is an array of size zero, FindType will convert it
1393 // to a runtime array.
1394 FindType(type);
1395 }
1396
1397 // Traverse the arrays and structures underneath each Block, and
1398 // mark them as needing layout.
1399 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1400 StructTypesNeedingBlock.end());
1401 while (!work_list.empty()) {
1402 Type *type = work_list.back();
1403 work_list.pop_back();
1404 TypesNeedingLayout.insert(type);
1405 switch (type->getTypeID()) {
1406 case Type::ArrayTyID:
1407 work_list.push_back(type->getArrayElementType());
1408 if (!Hack_generate_runtime_array_stride_early) {
1409 // Remember this array type for deferred decoration.
1410 TypesNeedingArrayStride.insert(type);
1411 }
1412 break;
1413 case Type::StructTyID:
1414 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1415 work_list.push_back(elem_ty);
1416 }
1417 default:
1418 // This type and its contained types don't get layout.
1419 break;
1420 }
1421 }
1422}
1423
Alan Baker202c8c72018-08-13 13:47:44 -04001424void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1425 // The SpecId assignment for pointer-to-local arguments is recorded in
1426 // module-level metadata. Translate that information into local argument
1427 // information.
1428 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001429 if (!nmd)
1430 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001431 for (auto operand : nmd->operands()) {
1432 MDTuple *tuple = cast<MDTuple>(operand);
1433 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1434 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001435 ConstantAsMetadata *arg_index_md =
1436 cast<ConstantAsMetadata>(tuple->getOperand(1));
1437 int arg_index = static_cast<int>(
1438 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1439 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001440
1441 ConstantAsMetadata *spec_id_md =
1442 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001443 int spec_id = static_cast<int>(
1444 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001445
1446 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1447 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001448 if (LocalSpecIdInfoMap.count(spec_id))
1449 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001450
1451 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1452 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1453 nextID + 1, nextID + 2,
1454 nextID + 3, spec_id};
1455 LocalSpecIdInfoMap[spec_id] = info;
1456 nextID += 4;
1457
1458 // Ensure the types necessary for this argument get generated.
1459 Type *IdxTy = Type::getInt32Ty(M.getContext());
1460 FindConstant(ConstantInt::get(IdxTy, 0));
1461 FindType(IdxTy);
1462 FindType(arg->getType());
1463 }
1464}
1465
David Neto22f144c2017-06-12 14:26:21 -04001466void SPIRVProducerPass::FindType(Type *Ty) {
1467 TypeList &TyList = getTypeList();
1468
1469 if (0 != TyList.idFor(Ty)) {
1470 return;
1471 }
1472
1473 if (Ty->isPointerTy()) {
1474 auto AddrSpace = Ty->getPointerAddressSpace();
1475 if ((AddressSpace::Constant == AddrSpace) ||
1476 (AddressSpace::Global == AddrSpace)) {
1477 auto PointeeTy = Ty->getPointerElementType();
1478
1479 if (PointeeTy->isStructTy() &&
1480 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1481 FindType(PointeeTy);
1482 auto ActualPointerTy =
1483 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1484 FindType(ActualPointerTy);
1485 return;
1486 }
1487 }
1488 }
1489
David Neto862b7d82018-06-14 18:48:37 -04001490 // By convention, LLVM array type with 0 elements will map to
1491 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1492 // has a constant number of elements. We need to support type of the
1493 // constant.
1494 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1495 if (arrayTy->getNumElements() > 0) {
1496 LLVMContext &Context = Ty->getContext();
1497 FindType(Type::getInt32Ty(Context));
1498 }
David Neto22f144c2017-06-12 14:26:21 -04001499 }
1500
1501 for (Type *SubTy : Ty->subtypes()) {
1502 FindType(SubTy);
1503 }
1504
1505 TyList.insert(Ty);
1506}
1507
1508void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1509 // If the global variable has a (non undef) initializer.
1510 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001511 // Generate the constant if it's not the initializer to a module scope
1512 // constant that we will expect in a storage buffer.
1513 const bool module_scope_constant_external_init =
1514 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1515 clspv::Option::ModuleConstantsInStorageBuffer();
1516 if (!module_scope_constant_external_init) {
1517 FindConstant(GV.getInitializer());
1518 }
David Neto22f144c2017-06-12 14:26:21 -04001519 }
1520}
1521
1522void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1523 // Investigate constants in function body.
1524 for (BasicBlock &BB : F) {
1525 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001526 if (auto *call = dyn_cast<CallInst>(&I)) {
1527 auto name = call->getCalledFunction()->getName();
1528 if (name == "clspv.sampler.var.literal") {
1529 // We've handled these constants elsewhere, so skip it.
1530 continue;
1531 }
Alan Baker202c8c72018-08-13 13:47:44 -04001532 if (name.startswith(clspv::ResourceAccessorFunction())) {
1533 continue;
1534 }
1535 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001536 continue;
1537 }
David Neto22f144c2017-06-12 14:26:21 -04001538 }
1539
1540 if (isa<AllocaInst>(I)) {
1541 // Alloca instruction has constant for the number of element. Ignore it.
1542 continue;
1543 } else if (isa<ShuffleVectorInst>(I)) {
1544 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1545 // Ignore constant for mask of shuffle vector instruction.
1546 if (i == 2) {
1547 continue;
1548 }
1549
1550 if (isa<Constant>(I.getOperand(i)) &&
1551 !isa<GlobalValue>(I.getOperand(i))) {
1552 FindConstant(I.getOperand(i));
1553 }
1554 }
1555
1556 continue;
1557 } else if (isa<InsertElementInst>(I)) {
1558 // Handle InsertElement with <4 x i8> specially.
1559 Type *CompositeTy = I.getOperand(0)->getType();
1560 if (is4xi8vec(CompositeTy)) {
1561 LLVMContext &Context = CompositeTy->getContext();
1562 if (isa<Constant>(I.getOperand(0))) {
1563 FindConstant(I.getOperand(0));
1564 }
1565
1566 if (isa<Constant>(I.getOperand(1))) {
1567 FindConstant(I.getOperand(1));
1568 }
1569
1570 // Add mask constant 0xFF.
1571 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1572 FindConstant(CstFF);
1573
1574 // Add shift amount constant.
1575 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1576 uint64_t Idx = CI->getZExtValue();
1577 Constant *CstShiftAmount =
1578 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1579 FindConstant(CstShiftAmount);
1580 }
1581
1582 continue;
1583 }
1584
1585 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1586 // Ignore constant for index of InsertElement instruction.
1587 if (i == 2) {
1588 continue;
1589 }
1590
1591 if (isa<Constant>(I.getOperand(i)) &&
1592 !isa<GlobalValue>(I.getOperand(i))) {
1593 FindConstant(I.getOperand(i));
1594 }
1595 }
1596
1597 continue;
1598 } else if (isa<ExtractElementInst>(I)) {
1599 // Handle ExtractElement with <4 x i8> specially.
1600 Type *CompositeTy = I.getOperand(0)->getType();
1601 if (is4xi8vec(CompositeTy)) {
1602 LLVMContext &Context = CompositeTy->getContext();
1603 if (isa<Constant>(I.getOperand(0))) {
1604 FindConstant(I.getOperand(0));
1605 }
1606
1607 // Add mask constant 0xFF.
1608 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1609 FindConstant(CstFF);
1610
1611 // Add shift amount constant.
1612 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1613 uint64_t Idx = CI->getZExtValue();
1614 Constant *CstShiftAmount =
1615 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1616 FindConstant(CstShiftAmount);
1617 } else {
1618 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1619 FindConstant(Cst8);
1620 }
1621
1622 continue;
1623 }
1624
1625 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1626 // Ignore constant for index of ExtractElement instruction.
1627 if (i == 1) {
1628 continue;
1629 }
1630
1631 if (isa<Constant>(I.getOperand(i)) &&
1632 !isa<GlobalValue>(I.getOperand(i))) {
1633 FindConstant(I.getOperand(i));
1634 }
1635 }
1636
1637 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001638 } else if ((Instruction::Xor == I.getOpcode()) &&
1639 I.getType()->isIntegerTy(1)) {
1640 // We special case for Xor where the type is i1 and one of the arguments
1641 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1642 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001643 bool foundConstantTrue = false;
1644 for (Use &Op : I.operands()) {
1645 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1646 auto CI = cast<ConstantInt>(Op);
1647
1648 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001649 // If we already found the true constant, we might (probably only
1650 // on -O0) have an OpLogicalNot which is taking a constant
1651 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001652 FindConstant(Op);
1653 } else {
1654 foundConstantTrue = true;
1655 }
1656 }
1657 }
1658
1659 continue;
David Netod2de94a2017-08-28 17:27:47 -04001660 } else if (isa<TruncInst>(I)) {
1661 // For truncation to i8 we mask against 255.
1662 Type *ToTy = I.getType();
1663 if (8u == ToTy->getPrimitiveSizeInBits()) {
1664 LLVMContext &Context = ToTy->getContext();
1665 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1666 FindConstant(Cst255);
1667 }
1668 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001669 } else if (isa<AtomicRMWInst>(I)) {
1670 LLVMContext &Context = I.getContext();
1671
1672 FindConstant(
1673 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1674 FindConstant(ConstantInt::get(
1675 Type::getInt32Ty(Context),
1676 spv::MemorySemanticsUniformMemoryMask |
1677 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001678 }
1679
1680 for (Use &Op : I.operands()) {
1681 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1682 FindConstant(Op);
1683 }
1684 }
1685 }
1686 }
1687}
1688
1689void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001690 ValueList &CstList = getConstantList();
1691
David Netofb9a7972017-08-25 17:08:24 -04001692 // If V is already tracked, ignore it.
1693 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001694 return;
1695 }
1696
David Neto862b7d82018-06-14 18:48:37 -04001697 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1698 return;
1699 }
1700
David Neto22f144c2017-06-12 14:26:21 -04001701 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001702 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001703
1704 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001705 if (is4xi8vec(CstTy)) {
1706 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001707 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001708 }
1709 }
1710
1711 if (Cst->getNumOperands()) {
1712 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1713 ++I) {
1714 FindConstant(*I);
1715 }
1716
David Netofb9a7972017-08-25 17:08:24 -04001717 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001718 return;
1719 } else if (const ConstantDataSequential *CDS =
1720 dyn_cast<ConstantDataSequential>(Cst)) {
1721 // Add constants for each element to constant list.
1722 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1723 Constant *EleCst = CDS->getElementAsConstant(i);
1724 FindConstant(EleCst);
1725 }
1726 }
1727
1728 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001729 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001730 }
1731}
1732
1733spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1734 switch (AddrSpace) {
1735 default:
1736 llvm_unreachable("Unsupported OpenCL address space");
1737 case AddressSpace::Private:
1738 return spv::StorageClassFunction;
1739 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001740 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001741 case AddressSpace::Constant:
1742 return clspv::Option::ConstantArgsInUniformBuffer()
1743 ? spv::StorageClassUniform
1744 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001745 case AddressSpace::Input:
1746 return spv::StorageClassInput;
1747 case AddressSpace::Local:
1748 return spv::StorageClassWorkgroup;
1749 case AddressSpace::UniformConstant:
1750 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001751 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001752 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001753 case AddressSpace::ModuleScopePrivate:
1754 return spv::StorageClassPrivate;
1755 }
1756}
1757
David Neto862b7d82018-06-14 18:48:37 -04001758spv::StorageClass
1759SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1760 switch (arg_kind) {
1761 case clspv::ArgKind::Buffer:
1762 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001763 case clspv::ArgKind::BufferUBO:
1764 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001765 case clspv::ArgKind::Pod:
1766 return clspv::Option::PodArgsInUniformBuffer()
1767 ? spv::StorageClassUniform
1768 : spv::StorageClassStorageBuffer;
1769 case clspv::ArgKind::Local:
1770 return spv::StorageClassWorkgroup;
1771 case clspv::ArgKind::ReadOnlyImage:
1772 case clspv::ArgKind::WriteOnlyImage:
1773 case clspv::ArgKind::Sampler:
1774 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001775 default:
1776 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001777 }
1778}
1779
David Neto22f144c2017-06-12 14:26:21 -04001780spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1781 return StringSwitch<spv::BuiltIn>(Name)
1782 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1783 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1784 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1785 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1786 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1787 .Default(spv::BuiltInMax);
1788}
1789
1790void SPIRVProducerPass::GenerateExtInstImport() {
1791 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1792 uint32_t &ExtInstImportID = getOpExtInstImportID();
1793
1794 //
1795 // Generate OpExtInstImport.
1796 //
1797 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001798 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001799 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1800 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001801}
1802
alan-bakerb6b09dc2018-11-08 16:59:28 -05001803void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1804 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001805 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1806 ValueMapType &VMap = getValueMap();
1807 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001808 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001809
1810 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1811 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1812 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1813
1814 for (Type *Ty : getTypeList()) {
1815 // Update TypeMap with nextID for reference later.
1816 TypeMap[Ty] = nextID;
1817
1818 switch (Ty->getTypeID()) {
1819 default: {
1820 Ty->print(errs());
1821 llvm_unreachable("Unsupported type???");
1822 break;
1823 }
1824 case Type::MetadataTyID:
1825 case Type::LabelTyID: {
1826 // Ignore these types.
1827 break;
1828 }
1829 case Type::PointerTyID: {
1830 PointerType *PTy = cast<PointerType>(Ty);
1831 unsigned AddrSpace = PTy->getAddressSpace();
1832
1833 // For the purposes of our Vulkan SPIR-V type system, constant and global
1834 // are conflated.
1835 bool UseExistingOpTypePointer = false;
1836 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001837 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1838 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001839 // Check to see if we already created this type (for instance, if we
1840 // had a constant <type>* and a global <type>*, the type would be
1841 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001842 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1843 if (0 < TypeMap.count(GlobalTy)) {
1844 TypeMap[PTy] = TypeMap[GlobalTy];
1845 UseExistingOpTypePointer = true;
1846 break;
1847 }
David Neto22f144c2017-06-12 14:26:21 -04001848 }
1849 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001850 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1851 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001852
alan-bakerb6b09dc2018-11-08 16:59:28 -05001853 // Check to see if we already created this type (for instance, if we
1854 // had a constant <type>* and a global <type>*, the type would be
1855 // created by one of these types, and shared by both).
1856 auto ConstantTy =
1857 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001858 if (0 < TypeMap.count(ConstantTy)) {
1859 TypeMap[PTy] = TypeMap[ConstantTy];
1860 UseExistingOpTypePointer = true;
1861 }
David Neto22f144c2017-06-12 14:26:21 -04001862 }
1863 }
1864
David Neto862b7d82018-06-14 18:48:37 -04001865 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001866
David Neto862b7d82018-06-14 18:48:37 -04001867 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001868 //
1869 // Generate OpTypePointer.
1870 //
1871
1872 // OpTypePointer
1873 // Ops[0] = Storage Class
1874 // Ops[1] = Element Type ID
1875 SPIRVOperandList Ops;
1876
David Neto257c3892018-04-11 13:19:45 -04001877 Ops << MkNum(GetStorageClass(AddrSpace))
1878 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001879
David Neto87846742018-04-11 17:36:22 -04001880 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001881 SPIRVInstList.push_back(Inst);
1882 }
David Neto22f144c2017-06-12 14:26:21 -04001883 break;
1884 }
1885 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001886 StructType *STy = cast<StructType>(Ty);
1887
1888 // Handle sampler type.
1889 if (STy->isOpaque()) {
1890 if (STy->getName().equals("opencl.sampler_t")) {
1891 //
1892 // Generate OpTypeSampler
1893 //
1894 // Empty Ops.
1895 SPIRVOperandList Ops;
1896
David Neto87846742018-04-11 17:36:22 -04001897 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001898 SPIRVInstList.push_back(Inst);
1899 break;
1900 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1901 STy->getName().equals("opencl.image2d_wo_t") ||
1902 STy->getName().equals("opencl.image3d_ro_t") ||
1903 STy->getName().equals("opencl.image3d_wo_t")) {
1904 //
1905 // Generate OpTypeImage
1906 //
1907 // Ops[0] = Sampled Type ID
1908 // Ops[1] = Dim ID
1909 // Ops[2] = Depth (Literal Number)
1910 // Ops[3] = Arrayed (Literal Number)
1911 // Ops[4] = MS (Literal Number)
1912 // Ops[5] = Sampled (Literal Number)
1913 // Ops[6] = Image Format ID
1914 //
1915 SPIRVOperandList Ops;
1916
1917 // TODO: Changed Sampled Type according to situations.
1918 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001919 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001920
1921 spv::Dim DimID = spv::Dim2D;
1922 if (STy->getName().equals("opencl.image3d_ro_t") ||
1923 STy->getName().equals("opencl.image3d_wo_t")) {
1924 DimID = spv::Dim3D;
1925 }
David Neto257c3892018-04-11 13:19:45 -04001926 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001927
1928 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001929 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001930
1931 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001932 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001933
1934 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001935 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001936
1937 // TODO: Set up Sampled.
1938 //
1939 // From Spec
1940 //
1941 // 0 indicates this is only known at run time, not at compile time
1942 // 1 indicates will be used with sampler
1943 // 2 indicates will be used without a sampler (a storage image)
1944 uint32_t Sampled = 1;
1945 if (STy->getName().equals("opencl.image2d_wo_t") ||
1946 STy->getName().equals("opencl.image3d_wo_t")) {
1947 Sampled = 2;
1948 }
David Neto257c3892018-04-11 13:19:45 -04001949 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001950
1951 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001952 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001953
David Neto87846742018-04-11 17:36:22 -04001954 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001955 SPIRVInstList.push_back(Inst);
1956 break;
1957 }
1958 }
1959
1960 //
1961 // Generate OpTypeStruct
1962 //
1963 // Ops[0] ... Ops[n] = Member IDs
1964 SPIRVOperandList Ops;
1965
1966 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001967 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001968 }
1969
David Neto22f144c2017-06-12 14:26:21 -04001970 uint32_t STyID = nextID;
1971
alan-bakerb6b09dc2018-11-08 16:59:28 -05001972 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001973 SPIRVInstList.push_back(Inst);
1974
1975 // Generate OpMemberDecorate.
1976 auto DecoInsertPoint =
1977 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1978 [](SPIRVInstruction *Inst) -> bool {
1979 return Inst->getOpcode() != spv::OpDecorate &&
1980 Inst->getOpcode() != spv::OpMemberDecorate &&
1981 Inst->getOpcode() != spv::OpExtInstImport;
1982 });
1983
David Netoc463b372017-08-10 15:32:21 -04001984 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001985 // Search for the correct offsets if this type was remapped.
1986 std::vector<uint32_t> *offsets = nullptr;
1987 auto iter = RemappedUBOTypeOffsets.find(STy);
1988 if (iter != RemappedUBOTypeOffsets.end()) {
1989 offsets = &iter->second;
1990 }
David Netoc463b372017-08-10 15:32:21 -04001991
David Neto862b7d82018-06-14 18:48:37 -04001992 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001993 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1994 MemberIdx++) {
1995 // Ops[0] = Structure Type ID
1996 // Ops[1] = Member Index(Literal Number)
1997 // Ops[2] = Decoration (Offset)
1998 // Ops[3] = Byte Offset (Literal Number)
1999 Ops.clear();
2000
David Neto257c3892018-04-11 13:19:45 -04002001 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002002
alan-bakerb6b09dc2018-11-08 16:59:28 -05002003 auto ByteOffset =
2004 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002005 if (offsets) {
2006 ByteOffset = (*offsets)[MemberIdx];
2007 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002008 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002009 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002010 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002011
David Neto87846742018-04-11 17:36:22 -04002012 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002013 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002014 }
2015
2016 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002017 if (StructTypesNeedingBlock.idFor(STy)) {
2018 Ops.clear();
2019 // Use Block decorations with StorageBuffer storage class.
2020 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002021
David Neto862b7d82018-06-14 18:48:37 -04002022 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2023 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002024 }
2025 break;
2026 }
2027 case Type::IntegerTyID: {
2028 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2029
2030 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002031 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002032 SPIRVInstList.push_back(Inst);
2033 } else {
2034 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002035 // No matter what LLVM type is requested first, always alias the
2036 // second one's SPIR-V type to be the same as the one we generated
2037 // first.
Neil Henning39672102017-09-29 14:33:13 +01002038 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002039 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002040 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002041 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002042 } else if (BitWidth == 32) {
2043 aliasToWidth = 8;
2044 }
2045 if (aliasToWidth) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002046 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
David Neto391aeb12017-08-26 15:51:58 -04002047 auto where = TypeMap.find(otherType);
2048 if (where == TypeMap.end()) {
2049 // Go ahead and make it, but also map the other type to it.
2050 TypeMap[otherType] = nextID;
2051 } else {
2052 // Alias this SPIR-V type the existing type.
2053 TypeMap[Ty] = where->second;
2054 break;
2055 }
David Neto22f144c2017-06-12 14:26:21 -04002056 }
2057
David Neto257c3892018-04-11 13:19:45 -04002058 SPIRVOperandList Ops;
2059 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002060
2061 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002062 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002063 }
2064 break;
2065 }
2066 case Type::HalfTyID:
2067 case Type::FloatTyID:
2068 case Type::DoubleTyID: {
2069 SPIRVOperand *WidthOp = new SPIRVOperand(
2070 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2071
2072 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002073 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002074 break;
2075 }
2076 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002077 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002078 const uint64_t Length = ArrTy->getArrayNumElements();
2079 if (Length == 0) {
2080 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002081
David Neto862b7d82018-06-14 18:48:37 -04002082 // Only generate the type once.
2083 // TODO(dneto): Can it ever be generated more than once?
2084 // Doesn't LLVM type uniqueness guarantee we'll only see this
2085 // once?
2086 Type *EleTy = ArrTy->getArrayElementType();
2087 if (OpRuntimeTyMap.count(EleTy) == 0) {
2088 uint32_t OpTypeRuntimeArrayID = nextID;
2089 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 //
2092 // Generate OpTypeRuntimeArray.
2093 //
David Neto22f144c2017-06-12 14:26:21 -04002094
David Neto862b7d82018-06-14 18:48:37 -04002095 // OpTypeRuntimeArray
2096 // Ops[0] = Element Type ID
2097 SPIRVOperandList Ops;
2098 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002099
David Neto862b7d82018-06-14 18:48:37 -04002100 SPIRVInstList.push_back(
2101 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002102
David Neto862b7d82018-06-14 18:48:37 -04002103 if (Hack_generate_runtime_array_stride_early) {
2104 // Generate OpDecorate.
2105 auto DecoInsertPoint = std::find_if(
2106 SPIRVInstList.begin(), SPIRVInstList.end(),
2107 [](SPIRVInstruction *Inst) -> bool {
2108 return Inst->getOpcode() != spv::OpDecorate &&
2109 Inst->getOpcode() != spv::OpMemberDecorate &&
2110 Inst->getOpcode() != spv::OpExtInstImport;
2111 });
David Neto22f144c2017-06-12 14:26:21 -04002112
David Neto862b7d82018-06-14 18:48:37 -04002113 // Ops[0] = Target ID
2114 // Ops[1] = Decoration (ArrayStride)
2115 // Ops[2] = Stride Number(Literal Number)
2116 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002117
David Neto862b7d82018-06-14 18:48:37 -04002118 Ops << MkId(OpTypeRuntimeArrayID)
2119 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002120 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002121
David Neto862b7d82018-06-14 18:48:37 -04002122 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2123 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2124 }
2125 }
David Neto22f144c2017-06-12 14:26:21 -04002126
David Neto862b7d82018-06-14 18:48:37 -04002127 } else {
David Neto22f144c2017-06-12 14:26:21 -04002128
David Neto862b7d82018-06-14 18:48:37 -04002129 //
2130 // Generate OpConstant and OpTypeArray.
2131 //
2132
2133 //
2134 // Generate OpConstant for array length.
2135 //
2136 // Ops[0] = Result Type ID
2137 // Ops[1] .. Ops[n] = Values LiteralNumber
2138 SPIRVOperandList Ops;
2139
2140 Type *LengthTy = Type::getInt32Ty(Context);
2141 uint32_t ResTyID = lookupType(LengthTy);
2142 Ops << MkId(ResTyID);
2143
2144 assert(Length < UINT32_MAX);
2145 Ops << MkNum(static_cast<uint32_t>(Length));
2146
2147 // Add constant for length to constant list.
2148 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2149 AllocatedVMap[CstLength] = nextID;
2150 VMap[CstLength] = nextID;
2151 uint32_t LengthID = nextID;
2152
2153 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2154 SPIRVInstList.push_back(CstInst);
2155
2156 // Remember to generate ArrayStride later
2157 getTypesNeedingArrayStride().insert(Ty);
2158
2159 //
2160 // Generate OpTypeArray.
2161 //
2162 // Ops[0] = Element Type ID
2163 // Ops[1] = Array Length Constant ID
2164 Ops.clear();
2165
2166 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2167 Ops << MkId(EleTyID) << MkId(LengthID);
2168
2169 // Update TypeMap with nextID.
2170 TypeMap[Ty] = nextID;
2171
2172 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2173 SPIRVInstList.push_back(ArrayInst);
2174 }
David Neto22f144c2017-06-12 14:26:21 -04002175 break;
2176 }
2177 case Type::VectorTyID: {
2178 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002179 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2180 if (Ty->getVectorNumElements() == 4) {
2181 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2182 break;
2183 } else {
2184 Ty->print(errs());
2185 llvm_unreachable("Support above i8 vector type");
2186 }
2187 }
2188
2189 // Ops[0] = Component Type ID
2190 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002191 SPIRVOperandList Ops;
2192 Ops << MkId(lookupType(Ty->getVectorElementType()))
2193 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002194
alan-bakerb6b09dc2018-11-08 16:59:28 -05002195 SPIRVInstruction *inst =
2196 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002197 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002198 break;
2199 }
2200 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002201 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002202 SPIRVInstList.push_back(Inst);
2203 break;
2204 }
2205 case Type::FunctionTyID: {
2206 // Generate SPIRV instruction for function type.
2207 FunctionType *FTy = cast<FunctionType>(Ty);
2208
2209 // Ops[0] = Return Type ID
2210 // Ops[1] ... Ops[n] = Parameter Type IDs
2211 SPIRVOperandList Ops;
2212
2213 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002214 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002215
2216 // Find SPIRV instructions for parameter types
2217 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2218 // Find SPIRV instruction for parameter type.
2219 auto ParamTy = FTy->getParamType(k);
2220 if (ParamTy->isPointerTy()) {
2221 auto PointeeTy = ParamTy->getPointerElementType();
2222 if (PointeeTy->isStructTy() &&
2223 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2224 ParamTy = PointeeTy;
2225 }
2226 }
2227
David Netoc6f3ab22018-04-06 18:02:31 -04002228 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002229 }
2230
David Neto87846742018-04-11 17:36:22 -04002231 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002232 SPIRVInstList.push_back(Inst);
2233 break;
2234 }
2235 }
2236 }
2237
2238 // Generate OpTypeSampledImage.
2239 TypeMapType &OpImageTypeMap = getImageTypeMap();
2240 for (auto &ImageType : OpImageTypeMap) {
2241 //
2242 // Generate OpTypeSampledImage.
2243 //
2244 // Ops[0] = Image Type ID
2245 //
2246 SPIRVOperandList Ops;
2247
2248 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002249 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002250
2251 // Update OpImageTypeMap.
2252 ImageType.second = nextID;
2253
David Neto87846742018-04-11 17:36:22 -04002254 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002255 SPIRVInstList.push_back(Inst);
2256 }
David Netoc6f3ab22018-04-06 18:02:31 -04002257
2258 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002259 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2260 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002261 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002262
2263 // Generate the spec constant.
2264 SPIRVOperandList Ops;
2265 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002266 SPIRVInstList.push_back(
2267 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002268
2269 // Generate the array type.
2270 Ops.clear();
2271 // The element type must have been created.
2272 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2273 assert(elem_ty_id);
2274 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2275
2276 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002277 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002278
2279 Ops.clear();
2280 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002281 SPIRVInstList.push_back(new SPIRVInstruction(
2282 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002283 }
David Neto22f144c2017-06-12 14:26:21 -04002284}
2285
2286void SPIRVProducerPass::GenerateSPIRVConstants() {
2287 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2288 ValueMapType &VMap = getValueMap();
2289 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2290 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002291 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002292
2293 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002294 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002295 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002296
2297 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002298 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002299 continue;
2300 }
2301
David Netofb9a7972017-08-25 17:08:24 -04002302 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002303 VMap[Cst] = nextID;
2304
2305 //
2306 // Generate OpConstant.
2307 //
2308
2309 // Ops[0] = Result Type ID
2310 // Ops[1] .. Ops[n] = Values LiteralNumber
2311 SPIRVOperandList Ops;
2312
David Neto257c3892018-04-11 13:19:45 -04002313 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002314
2315 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002316 spv::Op Opcode = spv::OpNop;
2317
2318 if (isa<UndefValue>(Cst)) {
2319 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002320 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002321 if (hack_undef && IsTypeNullable(Cst->getType())) {
2322 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002323 }
David Neto22f144c2017-06-12 14:26:21 -04002324 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2325 unsigned BitWidth = CI->getBitWidth();
2326 if (BitWidth == 1) {
2327 // If the bitwidth of constant is 1, generate OpConstantTrue or
2328 // OpConstantFalse.
2329 if (CI->getZExtValue()) {
2330 // Ops[0] = Result Type ID
2331 Opcode = spv::OpConstantTrue;
2332 } else {
2333 // Ops[0] = Result Type ID
2334 Opcode = spv::OpConstantFalse;
2335 }
David Neto22f144c2017-06-12 14:26:21 -04002336 } else {
2337 auto V = CI->getZExtValue();
2338 LiteralNum.push_back(V & 0xFFFFFFFF);
2339
2340 if (BitWidth > 32) {
2341 LiteralNum.push_back(V >> 32);
2342 }
2343
2344 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002345
David Neto257c3892018-04-11 13:19:45 -04002346 Ops << MkInteger(LiteralNum);
2347
2348 if (BitWidth == 32 && V == 0) {
2349 constant_i32_zero_id_ = nextID;
2350 }
David Neto22f144c2017-06-12 14:26:21 -04002351 }
2352 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2353 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2354 Type *CFPTy = CFP->getType();
2355 if (CFPTy->isFloatTy()) {
2356 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2357 } else {
2358 CFPTy->print(errs());
2359 llvm_unreachable("Implement this ConstantFP Type");
2360 }
2361
2362 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002363
David Neto257c3892018-04-11 13:19:45 -04002364 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002365 } else if (isa<ConstantDataSequential>(Cst) &&
2366 cast<ConstantDataSequential>(Cst)->isString()) {
2367 Cst->print(errs());
2368 llvm_unreachable("Implement this Constant");
2369
2370 } else if (const ConstantDataSequential *CDS =
2371 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002372 // Let's convert <4 x i8> constant to int constant specially.
2373 // This case occurs when all the values are specified as constant
2374 // ints.
2375 Type *CstTy = Cst->getType();
2376 if (is4xi8vec(CstTy)) {
2377 LLVMContext &Context = CstTy->getContext();
2378
2379 //
2380 // Generate OpConstant with OpTypeInt 32 0.
2381 //
Neil Henning39672102017-09-29 14:33:13 +01002382 uint32_t IntValue = 0;
2383 for (unsigned k = 0; k < 4; k++) {
2384 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002385 IntValue = (IntValue << 8) | (Val & 0xffu);
2386 }
2387
2388 Type *i32 = Type::getInt32Ty(Context);
2389 Constant *CstInt = ConstantInt::get(i32, IntValue);
2390 // If this constant is already registered on VMap, use it.
2391 if (VMap.count(CstInt)) {
2392 uint32_t CstID = VMap[CstInt];
2393 VMap[Cst] = CstID;
2394 continue;
2395 }
2396
David Neto257c3892018-04-11 13:19:45 -04002397 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002398
David Neto87846742018-04-11 17:36:22 -04002399 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002400 SPIRVInstList.push_back(CstInst);
2401
2402 continue;
2403 }
2404
2405 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002406 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2407 Constant *EleCst = CDS->getElementAsConstant(k);
2408 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002409 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002410 }
2411
2412 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002413 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2414 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002415 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002416 Type *CstTy = Cst->getType();
2417 if (is4xi8vec(CstTy)) {
2418 LLVMContext &Context = CstTy->getContext();
2419
2420 //
2421 // Generate OpConstant with OpTypeInt 32 0.
2422 //
Neil Henning39672102017-09-29 14:33:13 +01002423 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002424 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2425 I != E; ++I) {
2426 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002427 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002428 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2429 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002430 }
David Neto49351ac2017-08-26 17:32:20 -04002431 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002432 }
2433
David Neto49351ac2017-08-26 17:32:20 -04002434 Type *i32 = Type::getInt32Ty(Context);
2435 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002436 // If this constant is already registered on VMap, use it.
2437 if (VMap.count(CstInt)) {
2438 uint32_t CstID = VMap[CstInt];
2439 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002440 continue;
David Neto22f144c2017-06-12 14:26:21 -04002441 }
2442
David Neto257c3892018-04-11 13:19:45 -04002443 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002444
David Neto87846742018-04-11 17:36:22 -04002445 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002446 SPIRVInstList.push_back(CstInst);
2447
David Neto19a1bad2017-08-25 15:01:41 -04002448 continue;
David Neto22f144c2017-06-12 14:26:21 -04002449 }
2450
2451 // We use a constant composite in SPIR-V for our constant aggregate in
2452 // LLVM.
2453 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002454
2455 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2456 // Look up the ID of the element of this aggregate (which we will
2457 // previously have created a constant for).
2458 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2459
2460 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002461 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002462 }
2463 } else if (Cst->isNullValue()) {
2464 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002465 } else {
2466 Cst->print(errs());
2467 llvm_unreachable("Unsupported Constant???");
2468 }
2469
David Neto87846742018-04-11 17:36:22 -04002470 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002471 SPIRVInstList.push_back(CstInst);
2472 }
2473}
2474
2475void SPIRVProducerPass::GenerateSamplers(Module &M) {
2476 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002477
alan-bakerb6b09dc2018-11-08 16:59:28 -05002478 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002479 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002480 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002481 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2482 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002483
David Neto862b7d82018-06-14 18:48:37 -04002484 // We might have samplers in the sampler map that are not used
2485 // in the translation unit. We need to allocate variables
2486 // for them and bindings too.
2487 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002488
alan-bakerb6b09dc2018-11-08 16:59:28 -05002489 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2490 if (!var_fn)
2491 return;
David Neto862b7d82018-06-14 18:48:37 -04002492 for (auto user : var_fn->users()) {
2493 // Populate SamplerLiteralToDescriptorSetMap and
2494 // SamplerLiteralToBindingMap.
2495 //
2496 // Look for calls like
2497 // call %opencl.sampler_t addrspace(2)*
2498 // @clspv.sampler.var.literal(
2499 // i32 descriptor,
2500 // i32 binding,
2501 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002502 if (auto *call = dyn_cast<CallInst>(user)) {
2503 const size_t index_into_sampler_map = static_cast<size_t>(
2504 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002505 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002506 errs() << "Out of bounds index to sampler map: "
2507 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002508 llvm_unreachable("bad sampler init: out of bounds");
2509 }
2510
2511 auto sampler_value = sampler_map[index_into_sampler_map].first;
2512 const auto descriptor_set = static_cast<unsigned>(
2513 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2514 const auto binding = static_cast<unsigned>(
2515 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2516
2517 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2518 SamplerLiteralToBindingMap[sampler_value] = binding;
2519 used_bindings.insert(binding);
2520 }
2521 }
2522
2523 unsigned index = 0;
2524 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002525 // Generate OpVariable.
2526 //
2527 // GIDOps[0] : Result Type ID
2528 // GIDOps[1] : Storage Class
2529 SPIRVOperandList Ops;
2530
David Neto257c3892018-04-11 13:19:45 -04002531 Ops << MkId(lookupType(SamplerTy))
2532 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002533
David Neto862b7d82018-06-14 18:48:37 -04002534 auto sampler_var_id = nextID++;
2535 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002536 SPIRVInstList.push_back(Inst);
2537
David Neto862b7d82018-06-14 18:48:37 -04002538 SamplerMapIndexToIDMap[index] = sampler_var_id;
2539 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002540
2541 // Find Insert Point for OpDecorate.
2542 auto DecoInsertPoint =
2543 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2544 [](SPIRVInstruction *Inst) -> bool {
2545 return Inst->getOpcode() != spv::OpDecorate &&
2546 Inst->getOpcode() != spv::OpMemberDecorate &&
2547 Inst->getOpcode() != spv::OpExtInstImport;
2548 });
2549
2550 // Ops[0] = Target ID
2551 // Ops[1] = Decoration (DescriptorSet)
2552 // Ops[2] = LiteralNumber according to Decoration
2553 Ops.clear();
2554
David Neto862b7d82018-06-14 18:48:37 -04002555 unsigned descriptor_set;
2556 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002557 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2558 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002559 // This sampler is not actually used. Find the next one.
2560 for (binding = 0; used_bindings.count(binding); binding++)
2561 ;
2562 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2563 used_bindings.insert(binding);
2564 } else {
2565 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2566 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2567 }
2568
2569 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2570 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002571
alan-bakerf5e5f692018-11-27 08:33:24 -05002572 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2573 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002574
David Neto87846742018-04-11 17:36:22 -04002575 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002576 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2577
2578 // Ops[0] = Target ID
2579 // Ops[1] = Decoration (Binding)
2580 // Ops[2] = LiteralNumber according to Decoration
2581 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002582 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2583 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002584
David Neto87846742018-04-11 17:36:22 -04002585 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002586 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002587
2588 index++;
David Neto22f144c2017-06-12 14:26:21 -04002589 }
David Neto862b7d82018-06-14 18:48:37 -04002590}
David Neto22f144c2017-06-12 14:26:21 -04002591
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002592void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002593 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2594 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002595
David Neto862b7d82018-06-14 18:48:37 -04002596 // Generate variables. Make one for each of resource var info object.
2597 for (auto *info : ModuleOrderedResourceVars) {
2598 Type *type = info->var_fn->getReturnType();
2599 // Remap the address space for opaque types.
2600 switch (info->arg_kind) {
2601 case clspv::ArgKind::Sampler:
2602 case clspv::ArgKind::ReadOnlyImage:
2603 case clspv::ArgKind::WriteOnlyImage:
2604 type = PointerType::get(type->getPointerElementType(),
2605 clspv::AddressSpace::UniformConstant);
2606 break;
2607 default:
2608 break;
2609 }
David Neto22f144c2017-06-12 14:26:21 -04002610
David Neto862b7d82018-06-14 18:48:37 -04002611 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002612
David Neto862b7d82018-06-14 18:48:37 -04002613 const auto type_id = lookupType(type);
2614 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2615 SPIRVOperandList Ops;
2616 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002617
David Neto862b7d82018-06-14 18:48:37 -04002618 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2619 SPIRVInstList.push_back(Inst);
2620
2621 // Map calls to the variable-builtin-function.
2622 for (auto &U : info->var_fn->uses()) {
2623 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2624 const auto set = unsigned(
2625 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2626 const auto binding = unsigned(
2627 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2628 if (set == info->descriptor_set && binding == info->binding) {
2629 switch (info->arg_kind) {
2630 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002631 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002632 case clspv::ArgKind::Pod:
2633 // The call maps to the variable directly.
2634 VMap[call] = info->var_id;
2635 break;
2636 case clspv::ArgKind::Sampler:
2637 case clspv::ArgKind::ReadOnlyImage:
2638 case clspv::ArgKind::WriteOnlyImage:
2639 // The call maps to a load we generate later.
2640 ResourceVarDeferredLoadCalls[call] = info->var_id;
2641 break;
2642 default:
2643 llvm_unreachable("Unhandled arg kind");
2644 }
2645 }
David Neto22f144c2017-06-12 14:26:21 -04002646 }
David Neto862b7d82018-06-14 18:48:37 -04002647 }
2648 }
David Neto22f144c2017-06-12 14:26:21 -04002649
David Neto862b7d82018-06-14 18:48:37 -04002650 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002651
David Neto862b7d82018-06-14 18:48:37 -04002652 // Find Insert Point for OpDecorate.
2653 auto DecoInsertPoint =
2654 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2655 [](SPIRVInstruction *Inst) -> bool {
2656 return Inst->getOpcode() != spv::OpDecorate &&
2657 Inst->getOpcode() != spv::OpMemberDecorate &&
2658 Inst->getOpcode() != spv::OpExtInstImport;
2659 });
2660
2661 SPIRVOperandList Ops;
2662 for (auto *info : ModuleOrderedResourceVars) {
2663 // Decorate with DescriptorSet and Binding.
2664 Ops.clear();
2665 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2666 << MkNum(info->descriptor_set);
2667 SPIRVInstList.insert(DecoInsertPoint,
2668 new SPIRVInstruction(spv::OpDecorate, Ops));
2669
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2672 << MkNum(info->binding);
2673 SPIRVInstList.insert(DecoInsertPoint,
2674 new SPIRVInstruction(spv::OpDecorate, Ops));
2675
2676 // Generate NonWritable and NonReadable
2677 switch (info->arg_kind) {
2678 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002679 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002680 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2681 clspv::AddressSpace::Constant) {
2682 Ops.clear();
2683 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2684 SPIRVInstList.insert(DecoInsertPoint,
2685 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002686 }
David Neto862b7d82018-06-14 18:48:37 -04002687 break;
2688 case clspv::ArgKind::ReadOnlyImage:
2689 Ops.clear();
2690 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2691 SPIRVInstList.insert(DecoInsertPoint,
2692 new SPIRVInstruction(spv::OpDecorate, Ops));
2693 break;
2694 case clspv::ArgKind::WriteOnlyImage:
2695 Ops.clear();
2696 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2697 SPIRVInstList.insert(DecoInsertPoint,
2698 new SPIRVInstruction(spv::OpDecorate, Ops));
2699 break;
2700 default:
2701 break;
David Neto22f144c2017-06-12 14:26:21 -04002702 }
2703 }
2704}
2705
2706void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002707 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002708 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2709 ValueMapType &VMap = getValueMap();
2710 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002711 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002712
2713 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2714 Type *Ty = GV.getType();
2715 PointerType *PTy = cast<PointerType>(Ty);
2716
2717 uint32_t InitializerID = 0;
2718
2719 // Workgroup size is handled differently (it goes into a constant)
2720 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2721 std::vector<bool> HasMDVec;
2722 uint32_t PrevXDimCst = 0xFFFFFFFF;
2723 uint32_t PrevYDimCst = 0xFFFFFFFF;
2724 uint32_t PrevZDimCst = 0xFFFFFFFF;
2725 for (Function &Func : *GV.getParent()) {
2726 if (Func.isDeclaration()) {
2727 continue;
2728 }
2729
2730 // We only need to check kernels.
2731 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2732 continue;
2733 }
2734
2735 if (const MDNode *MD =
2736 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2737 uint32_t CurXDimCst = static_cast<uint32_t>(
2738 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2739 uint32_t CurYDimCst = static_cast<uint32_t>(
2740 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2741 uint32_t CurZDimCst = static_cast<uint32_t>(
2742 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2743
2744 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2745 PrevZDimCst == 0xFFFFFFFF) {
2746 PrevXDimCst = CurXDimCst;
2747 PrevYDimCst = CurYDimCst;
2748 PrevZDimCst = CurZDimCst;
2749 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2750 CurZDimCst != PrevZDimCst) {
2751 llvm_unreachable(
2752 "reqd_work_group_size must be the same across all kernels");
2753 } else {
2754 continue;
2755 }
2756
2757 //
2758 // Generate OpConstantComposite.
2759 //
2760 // Ops[0] : Result Type ID
2761 // Ops[1] : Constant size for x dimension.
2762 // Ops[2] : Constant size for y dimension.
2763 // Ops[3] : Constant size for z dimension.
2764 SPIRVOperandList Ops;
2765
2766 uint32_t XDimCstID =
2767 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2768 uint32_t YDimCstID =
2769 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2770 uint32_t ZDimCstID =
2771 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2772
2773 InitializerID = nextID;
2774
David Neto257c3892018-04-11 13:19:45 -04002775 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2776 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002777
David Neto87846742018-04-11 17:36:22 -04002778 auto *Inst =
2779 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002780 SPIRVInstList.push_back(Inst);
2781
2782 HasMDVec.push_back(true);
2783 } else {
2784 HasMDVec.push_back(false);
2785 }
2786 }
2787
2788 // Check all kernels have same definitions for work_group_size.
2789 bool HasMD = false;
2790 if (!HasMDVec.empty()) {
2791 HasMD = HasMDVec[0];
2792 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2793 if (HasMD != HasMDVec[i]) {
2794 llvm_unreachable(
2795 "Kernels should have consistent work group size definition");
2796 }
2797 }
2798 }
2799
2800 // If all kernels do not have metadata for reqd_work_group_size, generate
2801 // OpSpecConstants for x/y/z dimension.
2802 if (!HasMD) {
2803 //
2804 // Generate OpSpecConstants for x/y/z dimension.
2805 //
2806 // Ops[0] : Result Type ID
2807 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2808 uint32_t XDimCstID = 0;
2809 uint32_t YDimCstID = 0;
2810 uint32_t ZDimCstID = 0;
2811
David Neto22f144c2017-06-12 14:26:21 -04002812 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002813 uint32_t result_type_id =
2814 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002815
David Neto257c3892018-04-11 13:19:45 -04002816 // X Dimension
2817 Ops << MkId(result_type_id) << MkNum(1);
2818 XDimCstID = nextID++;
2819 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002820 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002821
2822 // Y Dimension
2823 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002824 Ops << MkId(result_type_id) << MkNum(1);
2825 YDimCstID = nextID++;
2826 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002827 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002828
2829 // Z Dimension
2830 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002831 Ops << MkId(result_type_id) << MkNum(1);
2832 ZDimCstID = nextID++;
2833 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002834 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002835
David Neto257c3892018-04-11 13:19:45 -04002836 BuiltinDimVec.push_back(XDimCstID);
2837 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002838 BuiltinDimVec.push_back(ZDimCstID);
2839
David Neto22f144c2017-06-12 14:26:21 -04002840 //
2841 // Generate OpSpecConstantComposite.
2842 //
2843 // Ops[0] : Result Type ID
2844 // Ops[1] : Constant size for x dimension.
2845 // Ops[2] : Constant size for y dimension.
2846 // Ops[3] : Constant size for z dimension.
2847 InitializerID = nextID;
2848
2849 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002850 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2851 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002852
David Neto87846742018-04-11 17:36:22 -04002853 auto *Inst =
2854 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002855 SPIRVInstList.push_back(Inst);
2856 }
2857 }
2858
David Neto22f144c2017-06-12 14:26:21 -04002859 VMap[&GV] = nextID;
2860
2861 //
2862 // Generate OpVariable.
2863 //
2864 // GIDOps[0] : Result Type ID
2865 // GIDOps[1] : Storage Class
2866 SPIRVOperandList Ops;
2867
David Neto85082642018-03-24 06:55:20 -07002868 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002869 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002870
David Neto85082642018-03-24 06:55:20 -07002871 if (GV.hasInitializer()) {
2872 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002873 }
2874
David Neto85082642018-03-24 06:55:20 -07002875 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002876 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002877 clspv::Option::ModuleConstantsInStorageBuffer();
2878
2879 if (0 != InitializerID) {
2880 if (!module_scope_constant_external_init) {
2881 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002882 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002883 }
2884 }
2885 const uint32_t var_id = nextID++;
2886
David Neto87846742018-04-11 17:36:22 -04002887 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002888 SPIRVInstList.push_back(Inst);
2889
2890 // If we have a builtin.
2891 if (spv::BuiltInMax != BuiltinType) {
2892 // Find Insert Point for OpDecorate.
2893 auto DecoInsertPoint =
2894 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2895 [](SPIRVInstruction *Inst) -> bool {
2896 return Inst->getOpcode() != spv::OpDecorate &&
2897 Inst->getOpcode() != spv::OpMemberDecorate &&
2898 Inst->getOpcode() != spv::OpExtInstImport;
2899 });
2900 //
2901 // Generate OpDecorate.
2902 //
2903 // DOps[0] = Target ID
2904 // DOps[1] = Decoration (Builtin)
2905 // DOps[2] = BuiltIn ID
2906 uint32_t ResultID;
2907
2908 // WorkgroupSize is different, we decorate the constant composite that has
2909 // its value, rather than the variable that we use to access the value.
2910 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2911 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002912 // Save both the value and variable IDs for later.
2913 WorkgroupSizeValueID = InitializerID;
2914 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002915 } else {
2916 ResultID = VMap[&GV];
2917 }
2918
2919 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002920 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2921 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002922
David Neto87846742018-04-11 17:36:22 -04002923 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002924 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002925 } else if (module_scope_constant_external_init) {
2926 // This module scope constant is initialized from a storage buffer with data
2927 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002928 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002929
David Neto862b7d82018-06-14 18:48:37 -04002930 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002931 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2932 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002933 std::string hexbytes;
2934 llvm::raw_string_ostream str(hexbytes);
2935 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2936 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2937 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002938
2939 // Find Insert Point for OpDecorate.
2940 auto DecoInsertPoint =
2941 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2942 [](SPIRVInstruction *Inst) -> bool {
2943 return Inst->getOpcode() != spv::OpDecorate &&
2944 Inst->getOpcode() != spv::OpMemberDecorate &&
2945 Inst->getOpcode() != spv::OpExtInstImport;
2946 });
2947
David Neto257c3892018-04-11 13:19:45 -04002948 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002949 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002950 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2951 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002952 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002953
2954 // OpDecorate %var DescriptorSet <descriptor_set>
2955 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002956 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2957 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002958 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002959 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002960 }
2961}
2962
David Netoc6f3ab22018-04-06 18:02:31 -04002963void SPIRVProducerPass::GenerateWorkgroupVars() {
2964 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002965 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2966 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002967 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002968
2969 // Generate OpVariable.
2970 //
2971 // GIDOps[0] : Result Type ID
2972 // GIDOps[1] : Storage Class
2973 SPIRVOperandList Ops;
2974 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2975
2976 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002977 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002978 }
2979}
2980
David Neto862b7d82018-06-14 18:48:37 -04002981void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2982 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002983 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2984 return;
2985 }
David Neto862b7d82018-06-14 18:48:37 -04002986 // Gather the list of resources that are used by this function's arguments.
2987 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2988
alan-bakerf5e5f692018-11-27 08:33:24 -05002989 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2990 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002991 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002992 std::string kind =
2993 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2994 ? "pod_ubo"
2995 : argKind;
2996 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002997 };
2998
2999 auto *fty = F.getType()->getPointerElementType();
3000 auto *func_ty = dyn_cast<FunctionType>(fty);
3001
3002 // If we've clustereed POD arguments, then argument details are in metadata.
3003 // If an argument maps to a resource variable, then get descriptor set and
3004 // binding from the resoure variable. Other info comes from the metadata.
3005 const auto *arg_map = F.getMetadata("kernel_arg_map");
3006 if (arg_map) {
3007 for (const auto &arg : arg_map->operands()) {
3008 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003009 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003010 const auto name =
3011 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3012 const auto old_index =
3013 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3014 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003015 const size_t new_index = static_cast<size_t>(
3016 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003017 const auto offset =
3018 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003019 const auto arg_size =
3020 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003021 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003022 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003023 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003024 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003025
3026 uint32_t descriptor_set = 0;
3027 uint32_t binding = 0;
3028 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3029 F.getName(),
3030 name,
3031 static_cast<uint32_t>(old_index),
3032 argKind,
3033 static_cast<uint32_t>(spec_id),
3034 // This will be set below for pointer-to-local args.
3035 0,
3036 static_cast<uint32_t>(offset),
3037 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003038 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003039 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3040 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3041 DL));
David Neto862b7d82018-06-14 18:48:37 -04003042 } else {
3043 auto *info = resource_var_at_index[new_index];
3044 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003045 descriptor_set = info->descriptor_set;
3046 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003047 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003048 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003049 }
3050 } else {
3051 // There is no argument map.
3052 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003053 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003054
3055 SmallVector<Argument *, 4> arguments;
3056 for (auto &arg : F.args()) {
3057 arguments.push_back(&arg);
3058 }
3059
3060 unsigned arg_index = 0;
3061 for (auto *info : resource_var_at_index) {
3062 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003063 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003064 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003065 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003066 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003067 }
3068
alan-bakerf5e5f692018-11-27 08:33:24 -05003069 // Local pointer arguments are unused in this case. Offset is always zero.
3070 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3071 F.getName(), arg->getName(),
3072 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3073 0, 0,
3074 0, arg_size};
3075 descriptorMapEntries->emplace_back(std::move(kernel_data),
3076 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003077 }
3078 arg_index++;
3079 }
3080 // Generate mappings for pointer-to-local arguments.
3081 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3082 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003083 auto where = LocalArgSpecIds.find(arg);
3084 if (where != LocalArgSpecIds.end()) {
3085 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003086 // Pod arguments members are unused in this case.
3087 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3088 F.getName(),
3089 arg->getName(),
3090 arg_index,
3091 ArgKind::Local,
3092 static_cast<uint32_t>(local_arg_info.spec_id),
3093 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3094 0,
3095 0};
3096 // Pointer-to-local arguments do not utilize descriptor set and binding.
3097 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003098 }
3099 }
3100 }
3101}
3102
David Neto22f144c2017-06-12 14:26:21 -04003103void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3104 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3105 ValueMapType &VMap = getValueMap();
3106 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003107 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3108 auto &GlobalConstArgSet = getGlobalConstArgSet();
3109
3110 FunctionType *FTy = F.getFunctionType();
3111
3112 //
David Neto22f144c2017-06-12 14:26:21 -04003113 // Generate OPFunction.
3114 //
3115
3116 // FOps[0] : Result Type ID
3117 // FOps[1] : Function Control
3118 // FOps[2] : Function Type ID
3119 SPIRVOperandList FOps;
3120
3121 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003122 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003123
3124 // Check function attributes for SPIRV Function Control.
3125 uint32_t FuncControl = spv::FunctionControlMaskNone;
3126 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3127 FuncControl |= spv::FunctionControlInlineMask;
3128 }
3129 if (F.hasFnAttribute(Attribute::NoInline)) {
3130 FuncControl |= spv::FunctionControlDontInlineMask;
3131 }
3132 // TODO: Check llvm attribute for Function Control Pure.
3133 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3134 FuncControl |= spv::FunctionControlPureMask;
3135 }
3136 // TODO: Check llvm attribute for Function Control Const.
3137 if (F.hasFnAttribute(Attribute::ReadNone)) {
3138 FuncControl |= spv::FunctionControlConstMask;
3139 }
3140
David Neto257c3892018-04-11 13:19:45 -04003141 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003142
3143 uint32_t FTyID;
3144 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3145 SmallVector<Type *, 4> NewFuncParamTys;
3146 FunctionType *NewFTy =
3147 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3148 FTyID = lookupType(NewFTy);
3149 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003150 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003151 if (GlobalConstFuncTyMap.count(FTy)) {
3152 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3153 } else {
3154 FTyID = lookupType(FTy);
3155 }
3156 }
3157
David Neto257c3892018-04-11 13:19:45 -04003158 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003159
3160 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3161 EntryPoints.push_back(std::make_pair(&F, nextID));
3162 }
3163
3164 VMap[&F] = nextID;
3165
David Neto482550a2018-03-24 05:21:07 -07003166 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003167 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3168 }
David Neto22f144c2017-06-12 14:26:21 -04003169 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003170 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003171 SPIRVInstList.push_back(FuncInst);
3172
3173 //
3174 // Generate OpFunctionParameter for Normal function.
3175 //
3176
3177 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3178 // Iterate Argument for name instead of param type from function type.
3179 unsigned ArgIdx = 0;
3180 for (Argument &Arg : F.args()) {
3181 VMap[&Arg] = nextID;
3182
3183 // ParamOps[0] : Result Type ID
3184 SPIRVOperandList ParamOps;
3185
3186 // Find SPIRV instruction for parameter type.
3187 uint32_t ParamTyID = lookupType(Arg.getType());
3188 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3189 if (GlobalConstFuncTyMap.count(FTy)) {
3190 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3191 Type *EleTy = PTy->getPointerElementType();
3192 Type *ArgTy =
3193 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3194 ParamTyID = lookupType(ArgTy);
3195 GlobalConstArgSet.insert(&Arg);
3196 }
3197 }
3198 }
David Neto257c3892018-04-11 13:19:45 -04003199 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003200
3201 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003202 auto *ParamInst =
3203 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003204 SPIRVInstList.push_back(ParamInst);
3205
3206 ArgIdx++;
3207 }
3208 }
3209}
3210
alan-bakerb6b09dc2018-11-08 16:59:28 -05003211void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003212 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3213 EntryPointVecType &EntryPoints = getEntryPointVec();
3214 ValueMapType &VMap = getValueMap();
3215 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3216 uint32_t &ExtInstImportID = getOpExtInstImportID();
3217 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3218
3219 // Set up insert point.
3220 auto InsertPoint = SPIRVInstList.begin();
3221
3222 //
3223 // Generate OpCapability
3224 //
3225 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3226
3227 // Ops[0] = Capability
3228 SPIRVOperandList Ops;
3229
David Neto87846742018-04-11 17:36:22 -04003230 auto *CapInst =
3231 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003232 SPIRVInstList.insert(InsertPoint, CapInst);
3233
3234 for (Type *Ty : getTypeList()) {
3235 // Find the i16 type.
3236 if (Ty->isIntegerTy(16)) {
3237 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003238 SPIRVInstList.insert(InsertPoint,
3239 new SPIRVInstruction(spv::OpCapability,
3240 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003241 } else if (Ty->isIntegerTy(64)) {
3242 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003243 SPIRVInstList.insert(InsertPoint,
3244 new SPIRVInstruction(spv::OpCapability,
3245 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003246 } else if (Ty->isHalfTy()) {
3247 // Generate OpCapability for half type.
3248 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003249 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3250 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003251 } else if (Ty->isDoubleTy()) {
3252 // Generate OpCapability for double type.
3253 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003254 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3255 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003256 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3257 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003258 if (STy->getName().equals("opencl.image2d_wo_t") ||
3259 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003260 // Generate OpCapability for write only image type.
3261 SPIRVInstList.insert(
3262 InsertPoint,
3263 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003264 spv::OpCapability,
3265 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003266 }
3267 }
3268 }
3269 }
3270
David Neto5c22a252018-03-15 16:07:41 -04003271 { // OpCapability ImageQuery
3272 bool hasImageQuery = false;
3273 for (const char *imageQuery : {
3274 "_Z15get_image_width14ocl_image2d_ro",
3275 "_Z15get_image_width14ocl_image2d_wo",
3276 "_Z16get_image_height14ocl_image2d_ro",
3277 "_Z16get_image_height14ocl_image2d_wo",
3278 }) {
3279 if (module.getFunction(imageQuery)) {
3280 hasImageQuery = true;
3281 break;
3282 }
3283 }
3284 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003285 auto *ImageQueryCapInst = new SPIRVInstruction(
3286 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003287 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3288 }
3289 }
3290
David Neto22f144c2017-06-12 14:26:21 -04003291 if (hasVariablePointers()) {
3292 //
3293 // Generate OpCapability and OpExtension
3294 //
3295
3296 //
3297 // Generate OpCapability.
3298 //
3299 // Ops[0] = Capability
3300 //
3301 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003302 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003303
David Neto87846742018-04-11 17:36:22 -04003304 SPIRVInstList.insert(InsertPoint,
3305 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003306
3307 //
3308 // Generate OpExtension.
3309 //
3310 // Ops[0] = Name (Literal String)
3311 //
David Netoa772fd12017-08-04 14:17:33 -04003312 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3313 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003314
David Neto87846742018-04-11 17:36:22 -04003315 auto *ExtensionInst =
3316 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003317 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003318 }
David Neto22f144c2017-06-12 14:26:21 -04003319 }
3320
3321 if (ExtInstImportID) {
3322 ++InsertPoint;
3323 }
3324
3325 //
3326 // Generate OpMemoryModel
3327 //
3328 // Memory model for Vulkan will always be GLSL450.
3329
3330 // Ops[0] = Addressing Model
3331 // Ops[1] = Memory Model
3332 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003333 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003334
David Neto87846742018-04-11 17:36:22 -04003335 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003336 SPIRVInstList.insert(InsertPoint, MemModelInst);
3337
3338 //
3339 // Generate OpEntryPoint
3340 //
3341 for (auto EntryPoint : EntryPoints) {
3342 // Ops[0] = Execution Model
3343 // Ops[1] = EntryPoint ID
3344 // Ops[2] = Name (Literal String)
3345 // ...
3346 //
3347 // TODO: Do we need to consider Interface ID for forward references???
3348 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003349 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003350 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3351 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003352
David Neto22f144c2017-06-12 14:26:21 -04003353 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003354 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003355 }
3356
David Neto87846742018-04-11 17:36:22 -04003357 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003358 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3359 }
3360
3361 for (auto EntryPoint : EntryPoints) {
3362 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3363 ->getMetadata("reqd_work_group_size")) {
3364
3365 if (!BuiltinDimVec.empty()) {
3366 llvm_unreachable(
3367 "Kernels should have consistent work group size definition");
3368 }
3369
3370 //
3371 // Generate OpExecutionMode
3372 //
3373
3374 // Ops[0] = Entry Point ID
3375 // Ops[1] = Execution Mode
3376 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3377 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003378 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003379
3380 uint32_t XDim = static_cast<uint32_t>(
3381 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3382 uint32_t YDim = static_cast<uint32_t>(
3383 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3384 uint32_t ZDim = static_cast<uint32_t>(
3385 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3386
David Neto257c3892018-04-11 13:19:45 -04003387 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003388
David Neto87846742018-04-11 17:36:22 -04003389 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003390 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3391 }
3392 }
3393
3394 //
3395 // Generate OpSource.
3396 //
3397 // Ops[0] = SourceLanguage ID
3398 // Ops[1] = Version (LiteralNum)
3399 //
3400 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003401 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003402
David Neto87846742018-04-11 17:36:22 -04003403 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003404 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3405
3406 if (!BuiltinDimVec.empty()) {
3407 //
3408 // Generate OpDecorates for x/y/z dimension.
3409 //
3410 // Ops[0] = Target ID
3411 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003412 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003413
3414 // X Dimension
3415 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003416 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003417 SPIRVInstList.insert(InsertPoint,
3418 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003419
3420 // Y Dimension
3421 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003422 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003423 SPIRVInstList.insert(InsertPoint,
3424 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003425
3426 // Z Dimension
3427 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003428 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003429 SPIRVInstList.insert(InsertPoint,
3430 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003431 }
3432}
3433
David Netob6e2e062018-04-25 10:32:06 -04003434void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3435 // Work around a driver bug. Initializers on Private variables might not
3436 // work. So the start of the kernel should store the initializer value to the
3437 // variables. Yes, *every* entry point pays this cost if *any* entry point
3438 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3439 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003440 // TODO(dneto): Remove this at some point once fixed drivers are widely
3441 // available.
David Netob6e2e062018-04-25 10:32:06 -04003442 if (WorkgroupSizeVarID) {
3443 assert(WorkgroupSizeValueID);
3444
3445 SPIRVOperandList Ops;
3446 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3447
3448 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3449 getSPIRVInstList().push_back(Inst);
3450 }
3451}
3452
David Neto22f144c2017-06-12 14:26:21 -04003453void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3454 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3455 ValueMapType &VMap = getValueMap();
3456
David Netob6e2e062018-04-25 10:32:06 -04003457 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003458
3459 for (BasicBlock &BB : F) {
3460 // Register BasicBlock to ValueMap.
3461 VMap[&BB] = nextID;
3462
3463 //
3464 // Generate OpLabel for Basic Block.
3465 //
3466 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003467 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003468 SPIRVInstList.push_back(Inst);
3469
David Neto6dcd4712017-06-23 11:06:47 -04003470 // OpVariable instructions must come first.
3471 for (Instruction &I : BB) {
3472 if (isa<AllocaInst>(I)) {
3473 GenerateInstruction(I);
3474 }
3475 }
3476
David Neto22f144c2017-06-12 14:26:21 -04003477 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003478 if (clspv::Option::HackInitializers()) {
3479 GenerateEntryPointInitialStores();
3480 }
David Neto22f144c2017-06-12 14:26:21 -04003481 }
3482
3483 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003484 if (!isa<AllocaInst>(I)) {
3485 GenerateInstruction(I);
3486 }
David Neto22f144c2017-06-12 14:26:21 -04003487 }
3488 }
3489}
3490
3491spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3492 const std::map<CmpInst::Predicate, spv::Op> Map = {
3493 {CmpInst::ICMP_EQ, spv::OpIEqual},
3494 {CmpInst::ICMP_NE, spv::OpINotEqual},
3495 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3496 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3497 {CmpInst::ICMP_ULT, spv::OpULessThan},
3498 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3499 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3500 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3501 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3502 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3503 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3504 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3505 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3506 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3507 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3508 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3509 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3510 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3511 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3512 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3513 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3514 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3515
3516 assert(0 != Map.count(I->getPredicate()));
3517
3518 return Map.at(I->getPredicate());
3519}
3520
3521spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3522 const std::map<unsigned, spv::Op> Map{
3523 {Instruction::Trunc, spv::OpUConvert},
3524 {Instruction::ZExt, spv::OpUConvert},
3525 {Instruction::SExt, spv::OpSConvert},
3526 {Instruction::FPToUI, spv::OpConvertFToU},
3527 {Instruction::FPToSI, spv::OpConvertFToS},
3528 {Instruction::UIToFP, spv::OpConvertUToF},
3529 {Instruction::SIToFP, spv::OpConvertSToF},
3530 {Instruction::FPTrunc, spv::OpFConvert},
3531 {Instruction::FPExt, spv::OpFConvert},
3532 {Instruction::BitCast, spv::OpBitcast}};
3533
3534 assert(0 != Map.count(I.getOpcode()));
3535
3536 return Map.at(I.getOpcode());
3537}
3538
3539spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003540 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003541 switch (I.getOpcode()) {
3542 default:
3543 break;
3544 case Instruction::Or:
3545 return spv::OpLogicalOr;
3546 case Instruction::And:
3547 return spv::OpLogicalAnd;
3548 case Instruction::Xor:
3549 return spv::OpLogicalNotEqual;
3550 }
3551 }
3552
alan-bakerb6b09dc2018-11-08 16:59:28 -05003553 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003554 {Instruction::Add, spv::OpIAdd},
3555 {Instruction::FAdd, spv::OpFAdd},
3556 {Instruction::Sub, spv::OpISub},
3557 {Instruction::FSub, spv::OpFSub},
3558 {Instruction::Mul, spv::OpIMul},
3559 {Instruction::FMul, spv::OpFMul},
3560 {Instruction::UDiv, spv::OpUDiv},
3561 {Instruction::SDiv, spv::OpSDiv},
3562 {Instruction::FDiv, spv::OpFDiv},
3563 {Instruction::URem, spv::OpUMod},
3564 {Instruction::SRem, spv::OpSRem},
3565 {Instruction::FRem, spv::OpFRem},
3566 {Instruction::Or, spv::OpBitwiseOr},
3567 {Instruction::Xor, spv::OpBitwiseXor},
3568 {Instruction::And, spv::OpBitwiseAnd},
3569 {Instruction::Shl, spv::OpShiftLeftLogical},
3570 {Instruction::LShr, spv::OpShiftRightLogical},
3571 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3572
3573 assert(0 != Map.count(I.getOpcode()));
3574
3575 return Map.at(I.getOpcode());
3576}
3577
3578void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3579 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3580 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003581 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3582 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3583
3584 // Register Instruction to ValueMap.
3585 if (0 == VMap[&I]) {
3586 VMap[&I] = nextID;
3587 }
3588
3589 switch (I.getOpcode()) {
3590 default: {
3591 if (Instruction::isCast(I.getOpcode())) {
3592 //
3593 // Generate SPIRV instructions for cast operators.
3594 //
3595
David Netod2de94a2017-08-28 17:27:47 -04003596 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003597 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003598 auto toI8 = Ty == Type::getInt8Ty(Context);
3599 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003600 // Handle zext, sext and uitofp with i1 type specially.
3601 if ((I.getOpcode() == Instruction::ZExt ||
3602 I.getOpcode() == Instruction::SExt ||
3603 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003604 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003605 //
3606 // Generate OpSelect.
3607 //
3608
3609 // Ops[0] = Result Type ID
3610 // Ops[1] = Condition ID
3611 // Ops[2] = True Constant ID
3612 // Ops[3] = False Constant ID
3613 SPIRVOperandList Ops;
3614
David Neto257c3892018-04-11 13:19:45 -04003615 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003616
David Neto22f144c2017-06-12 14:26:21 -04003617 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003618 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003619
3620 uint32_t TrueID = 0;
3621 if (I.getOpcode() == Instruction::ZExt) {
3622 APInt One(32, 1);
3623 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3624 } else if (I.getOpcode() == Instruction::SExt) {
3625 APInt MinusOne(32, UINT64_MAX, true);
3626 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3627 } else {
3628 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3629 }
David Neto257c3892018-04-11 13:19:45 -04003630 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003631
3632 uint32_t FalseID = 0;
3633 if (I.getOpcode() == Instruction::ZExt) {
3634 FalseID = VMap[Constant::getNullValue(I.getType())];
3635 } else if (I.getOpcode() == Instruction::SExt) {
3636 FalseID = VMap[Constant::getNullValue(I.getType())];
3637 } else {
3638 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3639 }
David Neto257c3892018-04-11 13:19:45 -04003640 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003641
David Neto87846742018-04-11 17:36:22 -04003642 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003643 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003644 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3645 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3646 // 8 bits.
3647 // Before:
3648 // %result = trunc i32 %a to i8
3649 // After
3650 // %result = OpBitwiseAnd %uint %a %uint_255
3651
3652 SPIRVOperandList Ops;
3653
David Neto257c3892018-04-11 13:19:45 -04003654 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003655
3656 Type *UintTy = Type::getInt32Ty(Context);
3657 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003658 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003659
David Neto87846742018-04-11 17:36:22 -04003660 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003661 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003662 } else {
3663 // Ops[0] = Result Type ID
3664 // Ops[1] = Source Value ID
3665 SPIRVOperandList Ops;
3666
David Neto257c3892018-04-11 13:19:45 -04003667 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003668
David Neto87846742018-04-11 17:36:22 -04003669 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003670 SPIRVInstList.push_back(Inst);
3671 }
3672 } else if (isa<BinaryOperator>(I)) {
3673 //
3674 // Generate SPIRV instructions for binary operators.
3675 //
3676
3677 // Handle xor with i1 type specially.
3678 if (I.getOpcode() == Instruction::Xor &&
3679 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003680 ((isa<ConstantInt>(I.getOperand(0)) &&
3681 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3682 (isa<ConstantInt>(I.getOperand(1)) &&
3683 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003684 //
3685 // Generate OpLogicalNot.
3686 //
3687 // Ops[0] = Result Type ID
3688 // Ops[1] = Operand
3689 SPIRVOperandList Ops;
3690
David Neto257c3892018-04-11 13:19:45 -04003691 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003692
3693 Value *CondV = I.getOperand(0);
3694 if (isa<Constant>(I.getOperand(0))) {
3695 CondV = I.getOperand(1);
3696 }
David Neto257c3892018-04-11 13:19:45 -04003697 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003698
David Neto87846742018-04-11 17:36:22 -04003699 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003700 SPIRVInstList.push_back(Inst);
3701 } else {
3702 // Ops[0] = Result Type ID
3703 // Ops[1] = Operand 0
3704 // Ops[2] = Operand 1
3705 SPIRVOperandList Ops;
3706
David Neto257c3892018-04-11 13:19:45 -04003707 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3708 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003709
David Neto87846742018-04-11 17:36:22 -04003710 auto *Inst =
3711 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003712 SPIRVInstList.push_back(Inst);
3713 }
3714 } else {
3715 I.print(errs());
3716 llvm_unreachable("Unsupported instruction???");
3717 }
3718 break;
3719 }
3720 case Instruction::GetElementPtr: {
3721 auto &GlobalConstArgSet = getGlobalConstArgSet();
3722
3723 //
3724 // Generate OpAccessChain.
3725 //
3726 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3727
3728 //
3729 // Generate OpAccessChain.
3730 //
3731
3732 // Ops[0] = Result Type ID
3733 // Ops[1] = Base ID
3734 // Ops[2] ... Ops[n] = Indexes ID
3735 SPIRVOperandList Ops;
3736
alan-bakerb6b09dc2018-11-08 16:59:28 -05003737 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003738 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3739 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3740 // Use pointer type with private address space for global constant.
3741 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003742 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003743 }
David Neto257c3892018-04-11 13:19:45 -04003744
3745 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003746
David Neto862b7d82018-06-14 18:48:37 -04003747 // Generate the base pointer.
3748 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003749
David Neto862b7d82018-06-14 18:48:37 -04003750 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003751
3752 //
3753 // Follows below rules for gep.
3754 //
David Neto862b7d82018-06-14 18:48:37 -04003755 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3756 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003757 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3758 // first index.
3759 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3760 // use gep's first index.
3761 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3762 // gep's first index.
3763 //
3764 spv::Op Opcode = spv::OpAccessChain;
3765 unsigned offset = 0;
3766 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003767 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003768 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003769 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003770 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003771 }
David Neto862b7d82018-06-14 18:48:37 -04003772 } else {
David Neto22f144c2017-06-12 14:26:21 -04003773 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003774 }
3775
3776 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003777 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003778 // Do we need to generate ArrayStride? Check against the GEP result type
3779 // rather than the pointer type of the base because when indexing into
3780 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3781 // for something else in the SPIR-V.
3782 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
Alan Bakerfcda9482018-10-02 17:09:59 -04003783 switch (GetStorageClass(ResultType->getAddressSpace())) {
3784 case spv::StorageClassStorageBuffer:
3785 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003786 // Save the need to generate an ArrayStride decoration. But defer
3787 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003788 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003789 break;
3790 default:
3791 break;
David Neto1a1a0582017-07-07 12:01:44 -04003792 }
David Neto22f144c2017-06-12 14:26:21 -04003793 }
3794
3795 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003796 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003797 }
3798
David Neto87846742018-04-11 17:36:22 -04003799 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003800 SPIRVInstList.push_back(Inst);
3801 break;
3802 }
3803 case Instruction::ExtractValue: {
3804 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3805 // Ops[0] = Result Type ID
3806 // Ops[1] = Composite ID
3807 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3808 SPIRVOperandList Ops;
3809
David Neto257c3892018-04-11 13:19:45 -04003810 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003811
3812 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003813 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003814
3815 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003816 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003817 }
3818
David Neto87846742018-04-11 17:36:22 -04003819 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003820 SPIRVInstList.push_back(Inst);
3821 break;
3822 }
3823 case Instruction::InsertValue: {
3824 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3825 // Ops[0] = Result Type ID
3826 // Ops[1] = Object ID
3827 // Ops[2] = Composite ID
3828 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3829 SPIRVOperandList Ops;
3830
3831 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003832 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003833
3834 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003835 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003836
3837 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003838 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003839
3840 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003841 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003842 }
3843
David Neto87846742018-04-11 17:36:22 -04003844 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003845 SPIRVInstList.push_back(Inst);
3846 break;
3847 }
3848 case Instruction::Select: {
3849 //
3850 // Generate OpSelect.
3851 //
3852
3853 // Ops[0] = Result Type ID
3854 // Ops[1] = Condition ID
3855 // Ops[2] = True Constant ID
3856 // Ops[3] = False Constant ID
3857 SPIRVOperandList Ops;
3858
3859 // Find SPIRV instruction for parameter type.
3860 auto Ty = I.getType();
3861 if (Ty->isPointerTy()) {
3862 auto PointeeTy = Ty->getPointerElementType();
3863 if (PointeeTy->isStructTy() &&
3864 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3865 Ty = PointeeTy;
3866 }
3867 }
3868
David Neto257c3892018-04-11 13:19:45 -04003869 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3870 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003871
David Neto87846742018-04-11 17:36:22 -04003872 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003873 SPIRVInstList.push_back(Inst);
3874 break;
3875 }
3876 case Instruction::ExtractElement: {
3877 // Handle <4 x i8> type manually.
3878 Type *CompositeTy = I.getOperand(0)->getType();
3879 if (is4xi8vec(CompositeTy)) {
3880 //
3881 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3882 // <4 x i8>.
3883 //
3884
3885 //
3886 // Generate OpShiftRightLogical
3887 //
3888 // Ops[0] = Result Type ID
3889 // Ops[1] = Operand 0
3890 // Ops[2] = Operand 1
3891 //
3892 SPIRVOperandList Ops;
3893
David Neto257c3892018-04-11 13:19:45 -04003894 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003895
3896 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003897 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003898
3899 uint32_t Op1ID = 0;
3900 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3901 // Handle constant index.
3902 uint64_t Idx = CI->getZExtValue();
3903 Value *ShiftAmount =
3904 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3905 Op1ID = VMap[ShiftAmount];
3906 } else {
3907 // Handle variable index.
3908 SPIRVOperandList TmpOps;
3909
David Neto257c3892018-04-11 13:19:45 -04003910 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3911 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003912
3913 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003914 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003915
3916 Op1ID = nextID;
3917
David Neto87846742018-04-11 17:36:22 -04003918 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003919 SPIRVInstList.push_back(TmpInst);
3920 }
David Neto257c3892018-04-11 13:19:45 -04003921 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003922
3923 uint32_t ShiftID = nextID;
3924
David Neto87846742018-04-11 17:36:22 -04003925 auto *Inst =
3926 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003927 SPIRVInstList.push_back(Inst);
3928
3929 //
3930 // Generate OpBitwiseAnd
3931 //
3932 // Ops[0] = Result Type ID
3933 // Ops[1] = Operand 0
3934 // Ops[2] = Operand 1
3935 //
3936 Ops.clear();
3937
David Neto257c3892018-04-11 13:19:45 -04003938 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003939
3940 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003941 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003942
David Neto9b2d6252017-09-06 15:47:37 -04003943 // Reset mapping for this value to the result of the bitwise and.
3944 VMap[&I] = nextID;
3945
David Neto87846742018-04-11 17:36:22 -04003946 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003947 SPIRVInstList.push_back(Inst);
3948 break;
3949 }
3950
3951 // Ops[0] = Result Type ID
3952 // Ops[1] = Composite ID
3953 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3954 SPIRVOperandList Ops;
3955
David Neto257c3892018-04-11 13:19:45 -04003956 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003957
3958 spv::Op Opcode = spv::OpCompositeExtract;
3959 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003960 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003961 } else {
David Neto257c3892018-04-11 13:19:45 -04003962 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003963 Opcode = spv::OpVectorExtractDynamic;
3964 }
3965
David Neto87846742018-04-11 17:36:22 -04003966 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003967 SPIRVInstList.push_back(Inst);
3968 break;
3969 }
3970 case Instruction::InsertElement: {
3971 // Handle <4 x i8> type manually.
3972 Type *CompositeTy = I.getOperand(0)->getType();
3973 if (is4xi8vec(CompositeTy)) {
3974 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3975 uint32_t CstFFID = VMap[CstFF];
3976
3977 uint32_t ShiftAmountID = 0;
3978 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3979 // Handle constant index.
3980 uint64_t Idx = CI->getZExtValue();
3981 Value *ShiftAmount =
3982 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3983 ShiftAmountID = VMap[ShiftAmount];
3984 } else {
3985 // Handle variable index.
3986 SPIRVOperandList TmpOps;
3987
David Neto257c3892018-04-11 13:19:45 -04003988 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3989 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003990
3991 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003992 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003993
3994 ShiftAmountID = nextID;
3995
David Neto87846742018-04-11 17:36:22 -04003996 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003997 SPIRVInstList.push_back(TmpInst);
3998 }
3999
4000 //
4001 // Generate mask operations.
4002 //
4003
4004 // ShiftLeft mask according to index of insertelement.
4005 SPIRVOperandList Ops;
4006
David Neto257c3892018-04-11 13:19:45 -04004007 const uint32_t ResTyID = lookupType(CompositeTy);
4008 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004009
4010 uint32_t MaskID = nextID;
4011
David Neto87846742018-04-11 17:36:22 -04004012 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004013 SPIRVInstList.push_back(Inst);
4014
4015 // Inverse mask.
4016 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004017 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004018
4019 uint32_t InvMaskID = nextID;
4020
David Neto87846742018-04-11 17:36:22 -04004021 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004022 SPIRVInstList.push_back(Inst);
4023
4024 // Apply mask.
4025 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004026 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004027
4028 uint32_t OrgValID = nextID;
4029
David Neto87846742018-04-11 17:36:22 -04004030 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004031 SPIRVInstList.push_back(Inst);
4032
4033 // Create correct value according to index of insertelement.
4034 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004035 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4036 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004037
4038 uint32_t InsertValID = nextID;
4039
David Neto87846742018-04-11 17:36:22 -04004040 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004041 SPIRVInstList.push_back(Inst);
4042
4043 // Insert value to original value.
4044 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004045 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004046
David Netoa394f392017-08-26 20:45:29 -04004047 VMap[&I] = nextID;
4048
David Neto87846742018-04-11 17:36:22 -04004049 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004050 SPIRVInstList.push_back(Inst);
4051
4052 break;
4053 }
4054
David Neto22f144c2017-06-12 14:26:21 -04004055 SPIRVOperandList Ops;
4056
James Priced26efea2018-06-09 23:28:32 +01004057 // Ops[0] = Result Type ID
4058 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004059
4060 spv::Op Opcode = spv::OpCompositeInsert;
4061 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004062 const auto value = CI->getZExtValue();
4063 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004064 // Ops[1] = Object ID
4065 // Ops[2] = Composite ID
4066 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004067 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004068 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004069 } else {
James Priced26efea2018-06-09 23:28:32 +01004070 // Ops[1] = Composite ID
4071 // Ops[2] = Object ID
4072 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004073 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004074 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004075 Opcode = spv::OpVectorInsertDynamic;
4076 }
4077
David Neto87846742018-04-11 17:36:22 -04004078 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004079 SPIRVInstList.push_back(Inst);
4080 break;
4081 }
4082 case Instruction::ShuffleVector: {
4083 // Ops[0] = Result Type ID
4084 // Ops[1] = Vector 1 ID
4085 // Ops[2] = Vector 2 ID
4086 // Ops[3] ... Ops[n] = Components (Literal Number)
4087 SPIRVOperandList Ops;
4088
David Neto257c3892018-04-11 13:19:45 -04004089 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4090 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004091
4092 uint64_t NumElements = 0;
4093 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4094 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4095
4096 if (Cst->isNullValue()) {
4097 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004098 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004099 }
4100 } else if (const ConstantDataSequential *CDS =
4101 dyn_cast<ConstantDataSequential>(Cst)) {
4102 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4103 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004104 const auto value = CDS->getElementAsInteger(i);
4105 assert(value <= UINT32_MAX);
4106 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004107 }
4108 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4109 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4110 auto Op = CV->getOperand(i);
4111
4112 uint32_t literal = 0;
4113
4114 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4115 literal = static_cast<uint32_t>(CI->getZExtValue());
4116 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4117 literal = 0xFFFFFFFFu;
4118 } else {
4119 Op->print(errs());
4120 llvm_unreachable("Unsupported element in ConstantVector!");
4121 }
4122
David Neto257c3892018-04-11 13:19:45 -04004123 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004124 }
4125 } else {
4126 Cst->print(errs());
4127 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4128 }
4129 }
4130
David Neto87846742018-04-11 17:36:22 -04004131 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004132 SPIRVInstList.push_back(Inst);
4133 break;
4134 }
4135 case Instruction::ICmp:
4136 case Instruction::FCmp: {
4137 CmpInst *CmpI = cast<CmpInst>(&I);
4138
David Netod4ca2e62017-07-06 18:47:35 -04004139 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004140 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004141 if (isa<PointerType>(ArgTy)) {
4142 CmpI->print(errs());
4143 std::string name = I.getParent()->getParent()->getName();
4144 errs()
4145 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4146 << "in function " << name << "\n";
4147 llvm_unreachable("Pointer equality check is invalid");
4148 break;
4149 }
4150
David Neto257c3892018-04-11 13:19:45 -04004151 // Ops[0] = Result Type ID
4152 // Ops[1] = Operand 1 ID
4153 // Ops[2] = Operand 2 ID
4154 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004155
David Neto257c3892018-04-11 13:19:45 -04004156 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4157 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004158
4159 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004160 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004161 SPIRVInstList.push_back(Inst);
4162 break;
4163 }
4164 case Instruction::Br: {
4165 // Branch instrucion is deferred because it needs label's ID. Record slot's
4166 // location on SPIRVInstructionList.
4167 DeferredInsts.push_back(
4168 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4169 break;
4170 }
4171 case Instruction::Switch: {
4172 I.print(errs());
4173 llvm_unreachable("Unsupported instruction???");
4174 break;
4175 }
4176 case Instruction::IndirectBr: {
4177 I.print(errs());
4178 llvm_unreachable("Unsupported instruction???");
4179 break;
4180 }
4181 case Instruction::PHI: {
4182 // Branch instrucion is deferred because it needs label's ID. Record slot's
4183 // location on SPIRVInstructionList.
4184 DeferredInsts.push_back(
4185 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4186 break;
4187 }
4188 case Instruction::Alloca: {
4189 //
4190 // Generate OpVariable.
4191 //
4192 // Ops[0] : Result Type ID
4193 // Ops[1] : Storage Class
4194 SPIRVOperandList Ops;
4195
David Neto257c3892018-04-11 13:19:45 -04004196 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004197
David Neto87846742018-04-11 17:36:22 -04004198 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004199 SPIRVInstList.push_back(Inst);
4200 break;
4201 }
4202 case Instruction::Load: {
4203 LoadInst *LD = cast<LoadInst>(&I);
4204 //
4205 // Generate OpLoad.
4206 //
4207
David Neto0a2f98d2017-09-15 19:38:40 -04004208 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004209 uint32_t PointerID = VMap[LD->getPointerOperand()];
4210
4211 // This is a hack to work around what looks like a driver bug.
4212 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004213 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4214 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004215 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004216 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004217 // Generate a bitwise-and of the original value with itself.
4218 // We should have been able to get away with just an OpCopyObject,
4219 // but we need something more complex to get past certain driver bugs.
4220 // This is ridiculous, but necessary.
4221 // TODO(dneto): Revisit this once drivers fix their bugs.
4222
4223 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004224 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4225 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004226
David Neto87846742018-04-11 17:36:22 -04004227 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004228 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004229 break;
4230 }
4231
4232 // This is the normal path. Generate a load.
4233
David Neto22f144c2017-06-12 14:26:21 -04004234 // Ops[0] = Result Type ID
4235 // Ops[1] = Pointer ID
4236 // Ops[2] ... Ops[n] = Optional Memory Access
4237 //
4238 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004239
David Neto22f144c2017-06-12 14:26:21 -04004240 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004241 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004242
David Neto87846742018-04-11 17:36:22 -04004243 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004244 SPIRVInstList.push_back(Inst);
4245 break;
4246 }
4247 case Instruction::Store: {
4248 StoreInst *ST = cast<StoreInst>(&I);
4249 //
4250 // Generate OpStore.
4251 //
4252
4253 // Ops[0] = Pointer ID
4254 // Ops[1] = Object ID
4255 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4256 //
4257 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004258 SPIRVOperandList Ops;
4259 Ops << MkId(VMap[ST->getPointerOperand()])
4260 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004261
David Neto87846742018-04-11 17:36:22 -04004262 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004263 SPIRVInstList.push_back(Inst);
4264 break;
4265 }
4266 case Instruction::AtomicCmpXchg: {
4267 I.print(errs());
4268 llvm_unreachable("Unsupported instruction???");
4269 break;
4270 }
4271 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004272 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4273
4274 spv::Op opcode;
4275
4276 switch (AtomicRMW->getOperation()) {
4277 default:
4278 I.print(errs());
4279 llvm_unreachable("Unsupported instruction???");
4280 case llvm::AtomicRMWInst::Add:
4281 opcode = spv::OpAtomicIAdd;
4282 break;
4283 case llvm::AtomicRMWInst::Sub:
4284 opcode = spv::OpAtomicISub;
4285 break;
4286 case llvm::AtomicRMWInst::Xchg:
4287 opcode = spv::OpAtomicExchange;
4288 break;
4289 case llvm::AtomicRMWInst::Min:
4290 opcode = spv::OpAtomicSMin;
4291 break;
4292 case llvm::AtomicRMWInst::Max:
4293 opcode = spv::OpAtomicSMax;
4294 break;
4295 case llvm::AtomicRMWInst::UMin:
4296 opcode = spv::OpAtomicUMin;
4297 break;
4298 case llvm::AtomicRMWInst::UMax:
4299 opcode = spv::OpAtomicUMax;
4300 break;
4301 case llvm::AtomicRMWInst::And:
4302 opcode = spv::OpAtomicAnd;
4303 break;
4304 case llvm::AtomicRMWInst::Or:
4305 opcode = spv::OpAtomicOr;
4306 break;
4307 case llvm::AtomicRMWInst::Xor:
4308 opcode = spv::OpAtomicXor;
4309 break;
4310 }
4311
4312 //
4313 // Generate OpAtomic*.
4314 //
4315 SPIRVOperandList Ops;
4316
David Neto257c3892018-04-11 13:19:45 -04004317 Ops << MkId(lookupType(I.getType()))
4318 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004319
4320 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004321 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004322 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004323
4324 const auto ConstantMemorySemantics = ConstantInt::get(
4325 IntTy, spv::MemorySemanticsUniformMemoryMask |
4326 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004327 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004328
David Neto257c3892018-04-11 13:19:45 -04004329 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004330
4331 VMap[&I] = nextID;
4332
David Neto87846742018-04-11 17:36:22 -04004333 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004334 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004335 break;
4336 }
4337 case Instruction::Fence: {
4338 I.print(errs());
4339 llvm_unreachable("Unsupported instruction???");
4340 break;
4341 }
4342 case Instruction::Call: {
4343 CallInst *Call = dyn_cast<CallInst>(&I);
4344 Function *Callee = Call->getCalledFunction();
4345
Alan Baker202c8c72018-08-13 13:47:44 -04004346 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004347 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4348 // Generate an OpLoad
4349 SPIRVOperandList Ops;
4350 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004351
David Neto862b7d82018-06-14 18:48:37 -04004352 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4353 << MkId(ResourceVarDeferredLoadCalls[Call]);
4354
4355 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4356 SPIRVInstList.push_back(Inst);
4357 VMap[Call] = load_id;
4358 break;
4359
4360 } else {
4361 // This maps to an OpVariable we've already generated.
4362 // No code is generated for the call.
4363 }
4364 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004365 } else if (Callee->getName().startswith(
4366 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004367 // Don't codegen an instruction here, but instead map this call directly
4368 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004369 int spec_id = static_cast<int>(
4370 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004371 const auto &info = LocalSpecIdInfoMap[spec_id];
4372 VMap[Call] = info.variable_id;
4373 break;
David Neto862b7d82018-06-14 18:48:37 -04004374 }
4375
4376 // Sampler initializers become a load of the corresponding sampler.
4377
4378 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4379 // Map this to a load from the variable.
4380 const auto index_into_sampler_map =
4381 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4382
4383 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004384 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004385 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004386
David Neto257c3892018-04-11 13:19:45 -04004387 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004388 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4389 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004390
David Neto862b7d82018-06-14 18:48:37 -04004391 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004392 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004393 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004394 break;
4395 }
4396
4397 if (Callee->getName().startswith("spirv.atomic")) {
4398 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4399 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4400 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4401 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4402 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4403 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4404 .Case("spirv.atomic_compare_exchange",
4405 spv::OpAtomicCompareExchange)
4406 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4407 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4408 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4409 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4410 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4411 .Case("spirv.atomic_or", spv::OpAtomicOr)
4412 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4413 .Default(spv::OpNop);
4414
4415 //
4416 // Generate OpAtomic*.
4417 //
4418 SPIRVOperandList Ops;
4419
David Neto257c3892018-04-11 13:19:45 -04004420 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004421
4422 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004423 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004424 }
4425
4426 VMap[&I] = nextID;
4427
David Neto87846742018-04-11 17:36:22 -04004428 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004429 SPIRVInstList.push_back(Inst);
4430 break;
4431 }
4432
4433 if (Callee->getName().startswith("_Z3dot")) {
4434 // If the argument is a vector type, generate OpDot
4435 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4436 //
4437 // Generate OpDot.
4438 //
4439 SPIRVOperandList Ops;
4440
David Neto257c3892018-04-11 13:19:45 -04004441 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004442
4443 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004444 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004445 }
4446
4447 VMap[&I] = nextID;
4448
David Neto87846742018-04-11 17:36:22 -04004449 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004450 SPIRVInstList.push_back(Inst);
4451 } else {
4452 //
4453 // Generate OpFMul.
4454 //
4455 SPIRVOperandList Ops;
4456
David Neto257c3892018-04-11 13:19:45 -04004457 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004458
4459 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004460 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004461 }
4462
4463 VMap[&I] = nextID;
4464
David Neto87846742018-04-11 17:36:22 -04004465 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004466 SPIRVInstList.push_back(Inst);
4467 }
4468 break;
4469 }
4470
David Neto8505ebf2017-10-13 18:50:50 -04004471 if (Callee->getName().startswith("_Z4fmod")) {
4472 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4473 // The sign for a non-zero result is taken from x.
4474 // (Try an example.)
4475 // So translate to OpFRem
4476
4477 SPIRVOperandList Ops;
4478
David Neto257c3892018-04-11 13:19:45 -04004479 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004480
4481 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004482 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004483 }
4484
4485 VMap[&I] = nextID;
4486
David Neto87846742018-04-11 17:36:22 -04004487 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004488 SPIRVInstList.push_back(Inst);
4489 break;
4490 }
4491
David Neto22f144c2017-06-12 14:26:21 -04004492 // spirv.store_null.* intrinsics become OpStore's.
4493 if (Callee->getName().startswith("spirv.store_null")) {
4494 //
4495 // Generate OpStore.
4496 //
4497
4498 // Ops[0] = Pointer ID
4499 // Ops[1] = Object ID
4500 // Ops[2] ... Ops[n]
4501 SPIRVOperandList Ops;
4502
4503 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004504 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004505 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004506
David Neto87846742018-04-11 17:36:22 -04004507 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004508
4509 break;
4510 }
4511
4512 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4513 if (Callee->getName().startswith("spirv.copy_memory")) {
4514 //
4515 // Generate OpCopyMemory.
4516 //
4517
4518 // Ops[0] = Dst ID
4519 // Ops[1] = Src ID
4520 // Ops[2] = Memory Access
4521 // Ops[3] = Alignment
4522
4523 auto IsVolatile =
4524 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4525
4526 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4527 : spv::MemoryAccessMaskNone;
4528
4529 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4530
4531 auto Alignment =
4532 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4533
David Neto257c3892018-04-11 13:19:45 -04004534 SPIRVOperandList Ops;
4535 Ops << MkId(VMap[Call->getArgOperand(0)])
4536 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4537 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004538
David Neto87846742018-04-11 17:36:22 -04004539 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004540
4541 SPIRVInstList.push_back(Inst);
4542
4543 break;
4544 }
4545
4546 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4547 // with unit.
4548 if (Callee->getName().equals("_Z3absj") ||
4549 Callee->getName().equals("_Z3absDv2_j") ||
4550 Callee->getName().equals("_Z3absDv3_j") ||
4551 Callee->getName().equals("_Z3absDv4_j")) {
4552 VMap[&I] = VMap[Call->getOperand(0)];
4553 break;
4554 }
4555
4556 // barrier is converted to OpControlBarrier
4557 if (Callee->getName().equals("__spirv_control_barrier")) {
4558 //
4559 // Generate OpControlBarrier.
4560 //
4561 // Ops[0] = Execution Scope ID
4562 // Ops[1] = Memory Scope ID
4563 // Ops[2] = Memory Semantics ID
4564 //
4565 Value *ExecutionScope = Call->getArgOperand(0);
4566 Value *MemoryScope = Call->getArgOperand(1);
4567 Value *MemorySemantics = Call->getArgOperand(2);
4568
David Neto257c3892018-04-11 13:19:45 -04004569 SPIRVOperandList Ops;
4570 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4571 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004572
David Neto87846742018-04-11 17:36:22 -04004573 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004574 break;
4575 }
4576
4577 // memory barrier is converted to OpMemoryBarrier
4578 if (Callee->getName().equals("__spirv_memory_barrier")) {
4579 //
4580 // Generate OpMemoryBarrier.
4581 //
4582 // Ops[0] = Memory Scope ID
4583 // Ops[1] = Memory Semantics ID
4584 //
4585 SPIRVOperandList Ops;
4586
David Neto257c3892018-04-11 13:19:45 -04004587 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4588 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004589
David Neto257c3892018-04-11 13:19:45 -04004590 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004591
David Neto87846742018-04-11 17:36:22 -04004592 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004593 SPIRVInstList.push_back(Inst);
4594 break;
4595 }
4596
4597 // isinf is converted to OpIsInf
4598 if (Callee->getName().equals("__spirv_isinff") ||
4599 Callee->getName().equals("__spirv_isinfDv2_f") ||
4600 Callee->getName().equals("__spirv_isinfDv3_f") ||
4601 Callee->getName().equals("__spirv_isinfDv4_f")) {
4602 //
4603 // Generate OpIsInf.
4604 //
4605 // Ops[0] = Result Type ID
4606 // Ops[1] = X ID
4607 //
4608 SPIRVOperandList Ops;
4609
David Neto257c3892018-04-11 13:19:45 -04004610 Ops << MkId(lookupType(I.getType()))
4611 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004612
4613 VMap[&I] = nextID;
4614
David Neto87846742018-04-11 17:36:22 -04004615 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004616 SPIRVInstList.push_back(Inst);
4617 break;
4618 }
4619
4620 // isnan is converted to OpIsNan
4621 if (Callee->getName().equals("__spirv_isnanf") ||
4622 Callee->getName().equals("__spirv_isnanDv2_f") ||
4623 Callee->getName().equals("__spirv_isnanDv3_f") ||
4624 Callee->getName().equals("__spirv_isnanDv4_f")) {
4625 //
4626 // Generate OpIsInf.
4627 //
4628 // Ops[0] = Result Type ID
4629 // Ops[1] = X ID
4630 //
4631 SPIRVOperandList Ops;
4632
David Neto257c3892018-04-11 13:19:45 -04004633 Ops << MkId(lookupType(I.getType()))
4634 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004635
4636 VMap[&I] = nextID;
4637
David Neto87846742018-04-11 17:36:22 -04004638 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004639 SPIRVInstList.push_back(Inst);
4640 break;
4641 }
4642
4643 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004644 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004645 //
4646 // Generate OpAll.
4647 //
4648 // Ops[0] = Result Type ID
4649 // Ops[1] = Vector ID
4650 //
4651 SPIRVOperandList Ops;
4652
David Neto257c3892018-04-11 13:19:45 -04004653 Ops << MkId(lookupType(I.getType()))
4654 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004655
4656 VMap[&I] = nextID;
4657
David Neto87846742018-04-11 17:36:22 -04004658 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004659 SPIRVInstList.push_back(Inst);
4660 break;
4661 }
4662
4663 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004664 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004665 //
4666 // Generate OpAny.
4667 //
4668 // Ops[0] = Result Type ID
4669 // Ops[1] = Vector ID
4670 //
4671 SPIRVOperandList Ops;
4672
David Neto257c3892018-04-11 13:19:45 -04004673 Ops << MkId(lookupType(I.getType()))
4674 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004675
4676 VMap[&I] = nextID;
4677
David Neto87846742018-04-11 17:36:22 -04004678 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004679 SPIRVInstList.push_back(Inst);
4680 break;
4681 }
4682
4683 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4684 // Additionally, OpTypeSampledImage is generated.
4685 if (Callee->getName().equals(
4686 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4687 Callee->getName().equals(
4688 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4689 //
4690 // Generate OpSampledImage.
4691 //
4692 // Ops[0] = Result Type ID
4693 // Ops[1] = Image ID
4694 // Ops[2] = Sampler ID
4695 //
4696 SPIRVOperandList Ops;
4697
4698 Value *Image = Call->getArgOperand(0);
4699 Value *Sampler = Call->getArgOperand(1);
4700 Value *Coordinate = Call->getArgOperand(2);
4701
4702 TypeMapType &OpImageTypeMap = getImageTypeMap();
4703 Type *ImageTy = Image->getType()->getPointerElementType();
4704 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004705 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004706 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004707
4708 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004709
4710 uint32_t SampledImageID = nextID;
4711
David Neto87846742018-04-11 17:36:22 -04004712 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004713 SPIRVInstList.push_back(Inst);
4714
4715 //
4716 // Generate OpImageSampleExplicitLod.
4717 //
4718 // Ops[0] = Result Type ID
4719 // Ops[1] = Sampled Image ID
4720 // Ops[2] = Coordinate ID
4721 // Ops[3] = Image Operands Type ID
4722 // Ops[4] ... Ops[n] = Operands ID
4723 //
4724 Ops.clear();
4725
David Neto257c3892018-04-11 13:19:45 -04004726 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4727 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004728
4729 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004730 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004731
4732 VMap[&I] = nextID;
4733
David Neto87846742018-04-11 17:36:22 -04004734 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004735 SPIRVInstList.push_back(Inst);
4736 break;
4737 }
4738
4739 // write_imagef is mapped to OpImageWrite.
4740 if (Callee->getName().equals(
4741 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4742 Callee->getName().equals(
4743 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4744 //
4745 // Generate OpImageWrite.
4746 //
4747 // Ops[0] = Image ID
4748 // Ops[1] = Coordinate ID
4749 // Ops[2] = Texel ID
4750 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4751 // Ops[4] ... Ops[n] = (Optional) Operands ID
4752 //
4753 SPIRVOperandList Ops;
4754
4755 Value *Image = Call->getArgOperand(0);
4756 Value *Coordinate = Call->getArgOperand(1);
4757 Value *Texel = Call->getArgOperand(2);
4758
4759 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004760 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004761 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004762 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004763
David Neto87846742018-04-11 17:36:22 -04004764 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004765 SPIRVInstList.push_back(Inst);
4766 break;
4767 }
4768
David Neto5c22a252018-03-15 16:07:41 -04004769 // get_image_width is mapped to OpImageQuerySize
4770 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4771 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4772 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4773 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4774 //
4775 // Generate OpImageQuerySize, then pull out the right component.
4776 // Assume 2D image for now.
4777 //
4778 // Ops[0] = Image ID
4779 //
4780 // %sizes = OpImageQuerySizes %uint2 %im
4781 // %result = OpCompositeExtract %uint %sizes 0-or-1
4782 SPIRVOperandList Ops;
4783
4784 // Implement:
4785 // %sizes = OpImageQuerySizes %uint2 %im
4786 uint32_t SizesTypeID =
4787 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004788 Value *Image = Call->getArgOperand(0);
4789 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004790 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004791
4792 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004793 auto *QueryInst =
4794 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004795 SPIRVInstList.push_back(QueryInst);
4796
4797 // Reset value map entry since we generated an intermediate instruction.
4798 VMap[&I] = nextID;
4799
4800 // Implement:
4801 // %result = OpCompositeExtract %uint %sizes 0-or-1
4802 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004803 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004804
4805 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004806 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004807
David Neto87846742018-04-11 17:36:22 -04004808 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004809 SPIRVInstList.push_back(Inst);
4810 break;
4811 }
4812
David Neto22f144c2017-06-12 14:26:21 -04004813 // Call instrucion is deferred because it needs function's ID. Record
4814 // slot's location on SPIRVInstructionList.
4815 DeferredInsts.push_back(
4816 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4817
David Neto3fbb4072017-10-16 11:28:14 -04004818 // Check whether the implementation of this call uses an extended
4819 // instruction plus one more value-producing instruction. If so, then
4820 // reserve the id for the extra value-producing slot.
4821 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4822 if (EInst != kGlslExtInstBad) {
4823 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004824 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004825 VMap[&I] = nextID;
4826 nextID++;
4827 }
4828 break;
4829 }
4830 case Instruction::Ret: {
4831 unsigned NumOps = I.getNumOperands();
4832 if (NumOps == 0) {
4833 //
4834 // Generate OpReturn.
4835 //
David Neto87846742018-04-11 17:36:22 -04004836 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004837 } else {
4838 //
4839 // Generate OpReturnValue.
4840 //
4841
4842 // Ops[0] = Return Value ID
4843 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004844
4845 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004846
David Neto87846742018-04-11 17:36:22 -04004847 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004848 SPIRVInstList.push_back(Inst);
4849 break;
4850 }
4851 break;
4852 }
4853 }
4854}
4855
4856void SPIRVProducerPass::GenerateFuncEpilogue() {
4857 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4858
4859 //
4860 // Generate OpFunctionEnd
4861 //
4862
David Neto87846742018-04-11 17:36:22 -04004863 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004864 SPIRVInstList.push_back(Inst);
4865}
4866
4867bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4868 LLVMContext &Context = Ty->getContext();
4869 if (Ty->isVectorTy()) {
4870 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4871 Ty->getVectorNumElements() == 4) {
4872 return true;
4873 }
4874 }
4875
4876 return false;
4877}
4878
David Neto257c3892018-04-11 13:19:45 -04004879uint32_t SPIRVProducerPass::GetI32Zero() {
4880 if (0 == constant_i32_zero_id_) {
4881 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4882 "defined in the SPIR-V module");
4883 }
4884 return constant_i32_zero_id_;
4885}
4886
David Neto22f144c2017-06-12 14:26:21 -04004887void SPIRVProducerPass::HandleDeferredInstruction() {
4888 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4889 ValueMapType &VMap = getValueMap();
4890 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4891
4892 for (auto DeferredInst = DeferredInsts.rbegin();
4893 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4894 Value *Inst = std::get<0>(*DeferredInst);
4895 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4896 if (InsertPoint != SPIRVInstList.end()) {
4897 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4898 ++InsertPoint;
4899 }
4900 }
4901
4902 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4903 // Check whether basic block, which has this branch instruction, is loop
4904 // header or not. If it is loop header, generate OpLoopMerge and
4905 // OpBranchConditional.
4906 Function *Func = Br->getParent()->getParent();
4907 DominatorTree &DT =
4908 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4909 const LoopInfo &LI =
4910 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4911
4912 BasicBlock *BrBB = Br->getParent();
4913 if (LI.isLoopHeader(BrBB)) {
4914 Value *ContinueBB = nullptr;
4915 Value *MergeBB = nullptr;
4916
4917 Loop *L = LI.getLoopFor(BrBB);
4918 MergeBB = L->getExitBlock();
4919 if (!MergeBB) {
4920 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4921 // has regions with single entry/exit. As a result, loop should not
4922 // have multiple exits.
4923 llvm_unreachable("Loop has multiple exits???");
4924 }
4925
4926 if (L->isLoopLatch(BrBB)) {
4927 ContinueBB = BrBB;
4928 } else {
4929 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4930 // block.
4931 BasicBlock *Header = L->getHeader();
4932 BasicBlock *Latch = L->getLoopLatch();
4933 for (BasicBlock *BB : L->blocks()) {
4934 if (BB == Header) {
4935 continue;
4936 }
4937
4938 // Check whether block dominates block with back-edge.
4939 if (DT.dominates(BB, Latch)) {
4940 ContinueBB = BB;
4941 }
4942 }
4943
4944 if (!ContinueBB) {
4945 llvm_unreachable("Wrong continue block from loop");
4946 }
4947 }
4948
4949 //
4950 // Generate OpLoopMerge.
4951 //
4952 // Ops[0] = Merge Block ID
4953 // Ops[1] = Continue Target ID
4954 // Ops[2] = Selection Control
4955 SPIRVOperandList Ops;
4956
4957 // StructurizeCFG pass already manipulated CFG. Just use false block of
4958 // branch instruction as merge block.
4959 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004960 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004961 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4962 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004963
David Neto87846742018-04-11 17:36:22 -04004964 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004965 SPIRVInstList.insert(InsertPoint, MergeInst);
4966
4967 } else if (Br->isConditional()) {
4968 bool HasBackEdge = false;
4969
4970 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4971 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4972 HasBackEdge = true;
4973 }
4974 }
4975 if (!HasBackEdge) {
4976 //
4977 // Generate OpSelectionMerge.
4978 //
4979 // Ops[0] = Merge Block ID
4980 // Ops[1] = Selection Control
4981 SPIRVOperandList Ops;
4982
4983 // StructurizeCFG pass already manipulated CFG. Just use false block
4984 // of branch instruction as merge block.
4985 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004986 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004987
David Neto87846742018-04-11 17:36:22 -04004988 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004989 SPIRVInstList.insert(InsertPoint, MergeInst);
4990 }
4991 }
4992
4993 if (Br->isConditional()) {
4994 //
4995 // Generate OpBranchConditional.
4996 //
4997 // Ops[0] = Condition ID
4998 // Ops[1] = True Label ID
4999 // Ops[2] = False Label ID
5000 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5001 SPIRVOperandList Ops;
5002
5003 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005004 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005005 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005006
5007 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005008
David Neto87846742018-04-11 17:36:22 -04005009 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005010 SPIRVInstList.insert(InsertPoint, BrInst);
5011 } else {
5012 //
5013 // Generate OpBranch.
5014 //
5015 // Ops[0] = Target Label ID
5016 SPIRVOperandList Ops;
5017
5018 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005019 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005020
David Neto87846742018-04-11 17:36:22 -04005021 SPIRVInstList.insert(InsertPoint,
5022 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005023 }
5024 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5025 //
5026 // Generate OpPhi.
5027 //
5028 // Ops[0] = Result Type ID
5029 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5030 SPIRVOperandList Ops;
5031
David Neto257c3892018-04-11 13:19:45 -04005032 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005033
David Neto22f144c2017-06-12 14:26:21 -04005034 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5035 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005036 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005037 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005038 }
5039
5040 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005041 InsertPoint,
5042 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005043 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5044 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005045 auto callee_name = Callee->getName();
5046 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005047
5048 if (EInst) {
5049 uint32_t &ExtInstImportID = getOpExtInstImportID();
5050
5051 //
5052 // Generate OpExtInst.
5053 //
5054
5055 // Ops[0] = Result Type ID
5056 // Ops[1] = Set ID (OpExtInstImport ID)
5057 // Ops[2] = Instruction Number (Literal Number)
5058 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5059 SPIRVOperandList Ops;
5060
David Neto862b7d82018-06-14 18:48:37 -04005061 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5062 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005063
David Neto22f144c2017-06-12 14:26:21 -04005064 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5065 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005066 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005067 }
5068
David Neto87846742018-04-11 17:36:22 -04005069 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5070 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005071 SPIRVInstList.insert(InsertPoint, ExtInst);
5072
David Neto3fbb4072017-10-16 11:28:14 -04005073 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5074 if (IndirectExtInst != kGlslExtInstBad) {
5075 // Generate one more instruction that uses the result of the extended
5076 // instruction. Its result id is one more than the id of the
5077 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005078 LLVMContext &Context =
5079 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005080
David Neto3fbb4072017-10-16 11:28:14 -04005081 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5082 &VMap, &SPIRVInstList, &InsertPoint](
5083 spv::Op opcode, Constant *constant) {
5084 //
5085 // Generate instruction like:
5086 // result = opcode constant <extinst-result>
5087 //
5088 // Ops[0] = Result Type ID
5089 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5090 // Ops[2] = Operand 1 ;; the result of the extended instruction
5091 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005092
David Neto3fbb4072017-10-16 11:28:14 -04005093 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005094 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005095
5096 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5097 constant = ConstantVector::getSplat(
5098 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5099 }
David Neto257c3892018-04-11 13:19:45 -04005100 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005101
5102 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005103 InsertPoint, new SPIRVInstruction(
5104 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005105 };
5106
5107 switch (IndirectExtInst) {
5108 case glsl::ExtInstFindUMsb: // Implementing clz
5109 generate_extra_inst(
5110 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5111 break;
5112 case glsl::ExtInstAcos: // Implementing acospi
5113 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005114 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005115 case glsl::ExtInstAtan2: // Implementing atan2pi
5116 generate_extra_inst(
5117 spv::OpFMul,
5118 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5119 break;
5120
5121 default:
5122 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005123 }
David Neto22f144c2017-06-12 14:26:21 -04005124 }
David Neto3fbb4072017-10-16 11:28:14 -04005125
David Neto862b7d82018-06-14 18:48:37 -04005126 } else if (callee_name.equals("_Z8popcounti") ||
5127 callee_name.equals("_Z8popcountj") ||
5128 callee_name.equals("_Z8popcountDv2_i") ||
5129 callee_name.equals("_Z8popcountDv3_i") ||
5130 callee_name.equals("_Z8popcountDv4_i") ||
5131 callee_name.equals("_Z8popcountDv2_j") ||
5132 callee_name.equals("_Z8popcountDv3_j") ||
5133 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005134 //
5135 // Generate OpBitCount
5136 //
5137 // Ops[0] = Result Type ID
5138 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005139 SPIRVOperandList Ops;
5140 Ops << MkId(lookupType(Call->getType()))
5141 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005142
5143 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005144 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005145 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005146
David Neto862b7d82018-06-14 18:48:37 -04005147 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005148
5149 // Generate an OpCompositeConstruct
5150 SPIRVOperandList Ops;
5151
5152 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005153 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005154
5155 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005156 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005157 }
5158
5159 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005160 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5161 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005162
Alan Baker202c8c72018-08-13 13:47:44 -04005163 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5164
5165 // We have already mapped the call's result value to an ID.
5166 // Don't generate any code now.
5167
5168 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005169
5170 // We have already mapped the call's result value to an ID.
5171 // Don't generate any code now.
5172
David Neto22f144c2017-06-12 14:26:21 -04005173 } else {
5174 //
5175 // Generate OpFunctionCall.
5176 //
5177
5178 // Ops[0] = Result Type ID
5179 // Ops[1] = Callee Function ID
5180 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5181 SPIRVOperandList Ops;
5182
David Neto862b7d82018-06-14 18:48:37 -04005183 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005184
5185 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005186 if (CalleeID == 0) {
5187 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005188 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005189 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5190 // causes an infinite loop. Instead, go ahead and generate
5191 // the bad function call. A validator will catch the 0-Id.
5192 // llvm_unreachable("Can't translate function call");
5193 }
David Neto22f144c2017-06-12 14:26:21 -04005194
David Neto257c3892018-04-11 13:19:45 -04005195 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005196
David Neto22f144c2017-06-12 14:26:21 -04005197 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5198 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005199 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005200 }
5201
David Neto87846742018-04-11 17:36:22 -04005202 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5203 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005204 SPIRVInstList.insert(InsertPoint, CallInst);
5205 }
5206 }
5207 }
5208}
5209
David Neto1a1a0582017-07-07 12:01:44 -04005210void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005211 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005212 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005213 }
David Neto1a1a0582017-07-07 12:01:44 -04005214
5215 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005216
5217 // Find an iterator pointing just past the last decoration.
5218 bool seen_decorations = false;
5219 auto DecoInsertPoint =
5220 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5221 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5222 const bool is_decoration =
5223 Inst->getOpcode() == spv::OpDecorate ||
5224 Inst->getOpcode() == spv::OpMemberDecorate;
5225 if (is_decoration) {
5226 seen_decorations = true;
5227 return false;
5228 } else {
5229 return seen_decorations;
5230 }
5231 });
5232
David Netoc6f3ab22018-04-06 18:02:31 -04005233 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5234 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005235 for (auto *type : getTypesNeedingArrayStride()) {
5236 Type *elemTy = nullptr;
5237 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5238 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005239 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005240 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005241 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005242 elemTy = seqTy->getSequentialElementType();
5243 } else {
5244 errs() << "Unhandled strided type " << *type << "\n";
5245 llvm_unreachable("Unhandled strided type");
5246 }
David Neto1a1a0582017-07-07 12:01:44 -04005247
5248 // Ops[0] = Target ID
5249 // Ops[1] = Decoration (ArrayStride)
5250 // Ops[2] = Stride number (Literal Number)
5251 SPIRVOperandList Ops;
5252
David Neto85082642018-03-24 06:55:20 -07005253 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005254 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005255
5256 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5257 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005258
David Neto87846742018-04-11 17:36:22 -04005259 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005260 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5261 }
David Netoc6f3ab22018-04-06 18:02:31 -04005262
5263 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005264 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5265 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005266 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005267 SPIRVOperandList Ops;
5268 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5269 << MkNum(arg_info.spec_id);
5270 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005271 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005272 }
David Neto1a1a0582017-07-07 12:01:44 -04005273}
5274
David Neto22f144c2017-06-12 14:26:21 -04005275glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5276 return StringSwitch<glsl::ExtInst>(Name)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005277 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5278 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5279 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5280 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005281 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5282 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5283 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5284 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005285 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5286 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5287 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5288 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005289 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5290 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5291 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5292 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5293 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5294 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5295 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5296 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5297 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5298 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5299 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5300 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005301 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5302 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5303 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5304 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5305 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5306 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5307 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5308 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005309 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5310 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5311 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5312 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5313 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5314 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5315 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5316 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005317 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5318 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5319 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5320 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5321 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5322 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5323 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5324 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005325 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5326 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5327 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5328 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5329 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005330 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5331 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5332 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5333 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5334 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5335 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5336 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5337 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005338 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5339 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5340 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5341 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5342 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5343 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5344 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5345 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005346 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5347 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5348 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5349 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5350 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5351 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5352 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5353 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005354 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5355 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5356 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5357 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5358 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5359 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5360 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5361 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5362 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5363 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5364 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5365 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5366 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5367 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5368 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5369 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5370 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5371 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5372 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5373 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5374 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5375 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5376 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5377 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5378 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5379 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5380 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5381 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5382 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5383 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5384 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5385 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5386 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5387 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5388 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5389 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5390 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5391 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5392 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5393 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5394 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005395 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005396 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5397 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5398 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5399 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5400 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5401 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5402 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5403 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5404 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5405 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5406 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5407 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5408 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5409 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5410 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5411 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5412 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005413 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005414 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005415 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005416 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005417 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005418 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5419 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005420 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005421 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5422 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5423 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005424 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5425 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5426 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5427 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005428 .Default(kGlslExtInstBad);
5429}
5430
5431glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5432 // Check indirect cases.
5433 return StringSwitch<glsl::ExtInst>(Name)
5434 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5435 // Use exact match on float arg because these need a multiply
5436 // of a constant of the right floating point type.
5437 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5438 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5439 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5440 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5441 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5442 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5443 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5444 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005445 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5446 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5447 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5448 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005449 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5450 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5451 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5452 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5453 .Default(kGlslExtInstBad);
5454}
5455
alan-bakerb6b09dc2018-11-08 16:59:28 -05005456glsl::ExtInst
5457SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005458 auto direct = getExtInstEnum(Name);
5459 if (direct != kGlslExtInstBad)
5460 return direct;
5461 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005462}
5463
5464void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5465 out << "%" << Inst->getResultID();
5466}
5467
5468void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5469 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5470 out << "\t" << spv::getOpName(Opcode);
5471}
5472
5473void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5474 SPIRVOperandType OpTy = Op->getType();
5475 switch (OpTy) {
5476 default: {
5477 llvm_unreachable("Unsupported SPIRV Operand Type???");
5478 break;
5479 }
5480 case SPIRVOperandType::NUMBERID: {
5481 out << "%" << Op->getNumID();
5482 break;
5483 }
5484 case SPIRVOperandType::LITERAL_STRING: {
5485 out << "\"" << Op->getLiteralStr() << "\"";
5486 break;
5487 }
5488 case SPIRVOperandType::LITERAL_INTEGER: {
5489 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005490 auto Words = Op->getLiteralNum();
5491 auto NumWords = Words.size();
5492
5493 if (NumWords == 1) {
5494 out << Words[0];
5495 } else if (NumWords == 2) {
5496 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5497 out << Val;
5498 } else {
5499 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005500 }
5501 break;
5502 }
5503 case SPIRVOperandType::LITERAL_FLOAT: {
5504 // TODO: Handle LiteralNum carefully.
5505 for (auto Word : Op->getLiteralNum()) {
5506 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5507 SmallString<8> Str;
5508 APF.toString(Str, 6, 2);
5509 out << Str;
5510 }
5511 break;
5512 }
5513 }
5514}
5515
5516void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5517 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5518 out << spv::getCapabilityName(Cap);
5519}
5520
5521void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5522 auto LiteralNum = Op->getLiteralNum();
5523 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5524 out << glsl::getExtInstName(Ext);
5525}
5526
5527void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5528 spv::AddressingModel AddrModel =
5529 static_cast<spv::AddressingModel>(Op->getNumID());
5530 out << spv::getAddressingModelName(AddrModel);
5531}
5532
5533void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5534 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5535 out << spv::getMemoryModelName(MemModel);
5536}
5537
5538void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5539 spv::ExecutionModel ExecModel =
5540 static_cast<spv::ExecutionModel>(Op->getNumID());
5541 out << spv::getExecutionModelName(ExecModel);
5542}
5543
5544void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5545 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5546 out << spv::getExecutionModeName(ExecMode);
5547}
5548
5549void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005550 spv::SourceLanguage SourceLang =
5551 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005552 out << spv::getSourceLanguageName(SourceLang);
5553}
5554
5555void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5556 spv::FunctionControlMask FuncCtrl =
5557 static_cast<spv::FunctionControlMask>(Op->getNumID());
5558 out << spv::getFunctionControlName(FuncCtrl);
5559}
5560
5561void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5562 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5563 out << getStorageClassName(StClass);
5564}
5565
5566void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5567 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5568 out << getDecorationName(Deco);
5569}
5570
5571void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5572 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5573 out << getBuiltInName(BIn);
5574}
5575
5576void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5577 spv::SelectionControlMask BIn =
5578 static_cast<spv::SelectionControlMask>(Op->getNumID());
5579 out << getSelectionControlName(BIn);
5580}
5581
5582void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5583 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5584 out << getLoopControlName(BIn);
5585}
5586
5587void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5588 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5589 out << getDimName(DIM);
5590}
5591
5592void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5593 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5594 out << getImageFormatName(Format);
5595}
5596
5597void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5598 out << spv::getMemoryAccessName(
5599 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5600}
5601
5602void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5603 auto LiteralNum = Op->getLiteralNum();
5604 spv::ImageOperandsMask Type =
5605 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5606 out << getImageOperandsName(Type);
5607}
5608
5609void SPIRVProducerPass::WriteSPIRVAssembly() {
5610 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5611
5612 for (auto Inst : SPIRVInstList) {
5613 SPIRVOperandList Ops = Inst->getOperands();
5614 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5615
5616 switch (Opcode) {
5617 default: {
5618 llvm_unreachable("Unsupported SPIRV instruction");
5619 break;
5620 }
5621 case spv::OpCapability: {
5622 // Ops[0] = Capability
5623 PrintOpcode(Inst);
5624 out << " ";
5625 PrintCapability(Ops[0]);
5626 out << "\n";
5627 break;
5628 }
5629 case spv::OpMemoryModel: {
5630 // Ops[0] = Addressing Model
5631 // Ops[1] = Memory Model
5632 PrintOpcode(Inst);
5633 out << " ";
5634 PrintAddrModel(Ops[0]);
5635 out << " ";
5636 PrintMemModel(Ops[1]);
5637 out << "\n";
5638 break;
5639 }
5640 case spv::OpEntryPoint: {
5641 // Ops[0] = Execution Model
5642 // Ops[1] = EntryPoint ID
5643 // Ops[2] = Name (Literal String)
5644 // Ops[3] ... Ops[n] = Interface ID
5645 PrintOpcode(Inst);
5646 out << " ";
5647 PrintExecModel(Ops[0]);
5648 for (uint32_t i = 1; i < Ops.size(); i++) {
5649 out << " ";
5650 PrintOperand(Ops[i]);
5651 }
5652 out << "\n";
5653 break;
5654 }
5655 case spv::OpExecutionMode: {
5656 // Ops[0] = Entry Point ID
5657 // Ops[1] = Execution Mode
5658 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5659 PrintOpcode(Inst);
5660 out << " ";
5661 PrintOperand(Ops[0]);
5662 out << " ";
5663 PrintExecMode(Ops[1]);
5664 for (uint32_t i = 2; i < Ops.size(); i++) {
5665 out << " ";
5666 PrintOperand(Ops[i]);
5667 }
5668 out << "\n";
5669 break;
5670 }
5671 case spv::OpSource: {
5672 // Ops[0] = SourceLanguage ID
5673 // Ops[1] = Version (LiteralNum)
5674 PrintOpcode(Inst);
5675 out << " ";
5676 PrintSourceLanguage(Ops[0]);
5677 out << " ";
5678 PrintOperand(Ops[1]);
5679 out << "\n";
5680 break;
5681 }
5682 case spv::OpDecorate: {
5683 // Ops[0] = Target ID
5684 // Ops[1] = Decoration (Block or BufferBlock)
5685 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5686 PrintOpcode(Inst);
5687 out << " ";
5688 PrintOperand(Ops[0]);
5689 out << " ";
5690 PrintDecoration(Ops[1]);
5691 // Handle BuiltIn OpDecorate specially.
5692 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5693 out << " ";
5694 PrintBuiltIn(Ops[2]);
5695 } else {
5696 for (uint32_t i = 2; i < Ops.size(); i++) {
5697 out << " ";
5698 PrintOperand(Ops[i]);
5699 }
5700 }
5701 out << "\n";
5702 break;
5703 }
5704 case spv::OpMemberDecorate: {
5705 // Ops[0] = Structure Type ID
5706 // Ops[1] = Member Index(Literal Number)
5707 // Ops[2] = Decoration
5708 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5709 PrintOpcode(Inst);
5710 out << " ";
5711 PrintOperand(Ops[0]);
5712 out << " ";
5713 PrintOperand(Ops[1]);
5714 out << " ";
5715 PrintDecoration(Ops[2]);
5716 for (uint32_t i = 3; i < Ops.size(); i++) {
5717 out << " ";
5718 PrintOperand(Ops[i]);
5719 }
5720 out << "\n";
5721 break;
5722 }
5723 case spv::OpTypePointer: {
5724 // Ops[0] = Storage Class
5725 // Ops[1] = Element Type ID
5726 PrintResID(Inst);
5727 out << " = ";
5728 PrintOpcode(Inst);
5729 out << " ";
5730 PrintStorageClass(Ops[0]);
5731 out << " ";
5732 PrintOperand(Ops[1]);
5733 out << "\n";
5734 break;
5735 }
5736 case spv::OpTypeImage: {
5737 // Ops[0] = Sampled Type ID
5738 // Ops[1] = Dim ID
5739 // Ops[2] = Depth (Literal Number)
5740 // Ops[3] = Arrayed (Literal Number)
5741 // Ops[4] = MS (Literal Number)
5742 // Ops[5] = Sampled (Literal Number)
5743 // Ops[6] = Image Format ID
5744 PrintResID(Inst);
5745 out << " = ";
5746 PrintOpcode(Inst);
5747 out << " ";
5748 PrintOperand(Ops[0]);
5749 out << " ";
5750 PrintDimensionality(Ops[1]);
5751 out << " ";
5752 PrintOperand(Ops[2]);
5753 out << " ";
5754 PrintOperand(Ops[3]);
5755 out << " ";
5756 PrintOperand(Ops[4]);
5757 out << " ";
5758 PrintOperand(Ops[5]);
5759 out << " ";
5760 PrintImageFormat(Ops[6]);
5761 out << "\n";
5762 break;
5763 }
5764 case spv::OpFunction: {
5765 // Ops[0] : Result Type ID
5766 // Ops[1] : Function Control
5767 // Ops[2] : Function Type ID
5768 PrintResID(Inst);
5769 out << " = ";
5770 PrintOpcode(Inst);
5771 out << " ";
5772 PrintOperand(Ops[0]);
5773 out << " ";
5774 PrintFuncCtrl(Ops[1]);
5775 out << " ";
5776 PrintOperand(Ops[2]);
5777 out << "\n";
5778 break;
5779 }
5780 case spv::OpSelectionMerge: {
5781 // Ops[0] = Merge Block ID
5782 // Ops[1] = Selection Control
5783 PrintOpcode(Inst);
5784 out << " ";
5785 PrintOperand(Ops[0]);
5786 out << " ";
5787 PrintSelectionControl(Ops[1]);
5788 out << "\n";
5789 break;
5790 }
5791 case spv::OpLoopMerge: {
5792 // Ops[0] = Merge Block ID
5793 // Ops[1] = Continue Target ID
5794 // Ops[2] = Selection Control
5795 PrintOpcode(Inst);
5796 out << " ";
5797 PrintOperand(Ops[0]);
5798 out << " ";
5799 PrintOperand(Ops[1]);
5800 out << " ";
5801 PrintLoopControl(Ops[2]);
5802 out << "\n";
5803 break;
5804 }
5805 case spv::OpImageSampleExplicitLod: {
5806 // Ops[0] = Result Type ID
5807 // Ops[1] = Sampled Image ID
5808 // Ops[2] = Coordinate ID
5809 // Ops[3] = Image Operands Type ID
5810 // Ops[4] ... Ops[n] = Operands ID
5811 PrintResID(Inst);
5812 out << " = ";
5813 PrintOpcode(Inst);
5814 for (uint32_t i = 0; i < 3; i++) {
5815 out << " ";
5816 PrintOperand(Ops[i]);
5817 }
5818 out << " ";
5819 PrintImageOperandsType(Ops[3]);
5820 for (uint32_t i = 4; i < Ops.size(); i++) {
5821 out << " ";
5822 PrintOperand(Ops[i]);
5823 }
5824 out << "\n";
5825 break;
5826 }
5827 case spv::OpVariable: {
5828 // Ops[0] : Result Type ID
5829 // Ops[1] : Storage Class
5830 // Ops[2] ... Ops[n] = Initializer IDs
5831 PrintResID(Inst);
5832 out << " = ";
5833 PrintOpcode(Inst);
5834 out << " ";
5835 PrintOperand(Ops[0]);
5836 out << " ";
5837 PrintStorageClass(Ops[1]);
5838 for (uint32_t i = 2; i < Ops.size(); i++) {
5839 out << " ";
5840 PrintOperand(Ops[i]);
5841 }
5842 out << "\n";
5843 break;
5844 }
5845 case spv::OpExtInst: {
5846 // Ops[0] = Result Type ID
5847 // Ops[1] = Set ID (OpExtInstImport ID)
5848 // Ops[2] = Instruction Number (Literal Number)
5849 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5850 PrintResID(Inst);
5851 out << " = ";
5852 PrintOpcode(Inst);
5853 out << " ";
5854 PrintOperand(Ops[0]);
5855 out << " ";
5856 PrintOperand(Ops[1]);
5857 out << " ";
5858 PrintExtInst(Ops[2]);
5859 for (uint32_t i = 3; i < Ops.size(); i++) {
5860 out << " ";
5861 PrintOperand(Ops[i]);
5862 }
5863 out << "\n";
5864 break;
5865 }
5866 case spv::OpCopyMemory: {
5867 // Ops[0] = Addressing Model
5868 // Ops[1] = Memory Model
5869 PrintOpcode(Inst);
5870 out << " ";
5871 PrintOperand(Ops[0]);
5872 out << " ";
5873 PrintOperand(Ops[1]);
5874 out << " ";
5875 PrintMemoryAccess(Ops[2]);
5876 out << " ";
5877 PrintOperand(Ops[3]);
5878 out << "\n";
5879 break;
5880 }
5881 case spv::OpExtension:
5882 case spv::OpControlBarrier:
5883 case spv::OpMemoryBarrier:
5884 case spv::OpBranch:
5885 case spv::OpBranchConditional:
5886 case spv::OpStore:
5887 case spv::OpImageWrite:
5888 case spv::OpReturnValue:
5889 case spv::OpReturn:
5890 case spv::OpFunctionEnd: {
5891 PrintOpcode(Inst);
5892 for (uint32_t i = 0; i < Ops.size(); i++) {
5893 out << " ";
5894 PrintOperand(Ops[i]);
5895 }
5896 out << "\n";
5897 break;
5898 }
5899 case spv::OpExtInstImport:
5900 case spv::OpTypeRuntimeArray:
5901 case spv::OpTypeStruct:
5902 case spv::OpTypeSampler:
5903 case spv::OpTypeSampledImage:
5904 case spv::OpTypeInt:
5905 case spv::OpTypeFloat:
5906 case spv::OpTypeArray:
5907 case spv::OpTypeVector:
5908 case spv::OpTypeBool:
5909 case spv::OpTypeVoid:
5910 case spv::OpTypeFunction:
5911 case spv::OpFunctionParameter:
5912 case spv::OpLabel:
5913 case spv::OpPhi:
5914 case spv::OpLoad:
5915 case spv::OpSelect:
5916 case spv::OpAccessChain:
5917 case spv::OpPtrAccessChain:
5918 case spv::OpInBoundsAccessChain:
5919 case spv::OpUConvert:
5920 case spv::OpSConvert:
5921 case spv::OpConvertFToU:
5922 case spv::OpConvertFToS:
5923 case spv::OpConvertUToF:
5924 case spv::OpConvertSToF:
5925 case spv::OpFConvert:
5926 case spv::OpConvertPtrToU:
5927 case spv::OpConvertUToPtr:
5928 case spv::OpBitcast:
5929 case spv::OpIAdd:
5930 case spv::OpFAdd:
5931 case spv::OpISub:
5932 case spv::OpFSub:
5933 case spv::OpIMul:
5934 case spv::OpFMul:
5935 case spv::OpUDiv:
5936 case spv::OpSDiv:
5937 case spv::OpFDiv:
5938 case spv::OpUMod:
5939 case spv::OpSRem:
5940 case spv::OpFRem:
5941 case spv::OpBitwiseOr:
5942 case spv::OpBitwiseXor:
5943 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005944 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005945 case spv::OpShiftLeftLogical:
5946 case spv::OpShiftRightLogical:
5947 case spv::OpShiftRightArithmetic:
5948 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005949 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005950 case spv::OpCompositeExtract:
5951 case spv::OpVectorExtractDynamic:
5952 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005953 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005954 case spv::OpVectorInsertDynamic:
5955 case spv::OpVectorShuffle:
5956 case spv::OpIEqual:
5957 case spv::OpINotEqual:
5958 case spv::OpUGreaterThan:
5959 case spv::OpUGreaterThanEqual:
5960 case spv::OpULessThan:
5961 case spv::OpULessThanEqual:
5962 case spv::OpSGreaterThan:
5963 case spv::OpSGreaterThanEqual:
5964 case spv::OpSLessThan:
5965 case spv::OpSLessThanEqual:
5966 case spv::OpFOrdEqual:
5967 case spv::OpFOrdGreaterThan:
5968 case spv::OpFOrdGreaterThanEqual:
5969 case spv::OpFOrdLessThan:
5970 case spv::OpFOrdLessThanEqual:
5971 case spv::OpFOrdNotEqual:
5972 case spv::OpFUnordEqual:
5973 case spv::OpFUnordGreaterThan:
5974 case spv::OpFUnordGreaterThanEqual:
5975 case spv::OpFUnordLessThan:
5976 case spv::OpFUnordLessThanEqual:
5977 case spv::OpFUnordNotEqual:
5978 case spv::OpSampledImage:
5979 case spv::OpFunctionCall:
5980 case spv::OpConstantTrue:
5981 case spv::OpConstantFalse:
5982 case spv::OpConstant:
5983 case spv::OpSpecConstant:
5984 case spv::OpConstantComposite:
5985 case spv::OpSpecConstantComposite:
5986 case spv::OpConstantNull:
5987 case spv::OpLogicalOr:
5988 case spv::OpLogicalAnd:
5989 case spv::OpLogicalNot:
5990 case spv::OpLogicalNotEqual:
5991 case spv::OpUndef:
5992 case spv::OpIsInf:
5993 case spv::OpIsNan:
5994 case spv::OpAny:
5995 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005996 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005997 case spv::OpAtomicIAdd:
5998 case spv::OpAtomicISub:
5999 case spv::OpAtomicExchange:
6000 case spv::OpAtomicIIncrement:
6001 case spv::OpAtomicIDecrement:
6002 case spv::OpAtomicCompareExchange:
6003 case spv::OpAtomicUMin:
6004 case spv::OpAtomicSMin:
6005 case spv::OpAtomicUMax:
6006 case spv::OpAtomicSMax:
6007 case spv::OpAtomicAnd:
6008 case spv::OpAtomicOr:
6009 case spv::OpAtomicXor:
6010 case spv::OpDot: {
6011 PrintResID(Inst);
6012 out << " = ";
6013 PrintOpcode(Inst);
6014 for (uint32_t i = 0; i < Ops.size(); i++) {
6015 out << " ";
6016 PrintOperand(Ops[i]);
6017 }
6018 out << "\n";
6019 break;
6020 }
6021 }
6022 }
6023}
6024
6025void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006026 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006027}
6028
6029void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6030 WriteOneWord(Inst->getResultID());
6031}
6032
6033void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6034 // High 16 bit : Word Count
6035 // Low 16 bit : Opcode
6036 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006037 const uint32_t count = Inst->getWordCount();
6038 if (count > 65535) {
6039 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6040 llvm_unreachable("Word count too high");
6041 }
David Neto22f144c2017-06-12 14:26:21 -04006042 Word |= Inst->getWordCount() << 16;
6043 WriteOneWord(Word);
6044}
6045
6046void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6047 SPIRVOperandType OpTy = Op->getType();
6048 switch (OpTy) {
6049 default: {
6050 llvm_unreachable("Unsupported SPIRV Operand Type???");
6051 break;
6052 }
6053 case SPIRVOperandType::NUMBERID: {
6054 WriteOneWord(Op->getNumID());
6055 break;
6056 }
6057 case SPIRVOperandType::LITERAL_STRING: {
6058 std::string Str = Op->getLiteralStr();
6059 const char *Data = Str.c_str();
6060 size_t WordSize = Str.size() / 4;
6061 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6062 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6063 }
6064
6065 uint32_t Remainder = Str.size() % 4;
6066 uint32_t LastWord = 0;
6067 if (Remainder) {
6068 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6069 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6070 }
6071 }
6072
6073 WriteOneWord(LastWord);
6074 break;
6075 }
6076 case SPIRVOperandType::LITERAL_INTEGER:
6077 case SPIRVOperandType::LITERAL_FLOAT: {
6078 auto LiteralNum = Op->getLiteralNum();
6079 // TODO: Handle LiteranNum carefully.
6080 for (auto Word : LiteralNum) {
6081 WriteOneWord(Word);
6082 }
6083 break;
6084 }
6085 }
6086}
6087
6088void SPIRVProducerPass::WriteSPIRVBinary() {
6089 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6090
6091 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006092 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006093 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6094
6095 switch (Opcode) {
6096 default: {
David Neto5c22a252018-03-15 16:07:41 -04006097 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006098 llvm_unreachable("Unsupported SPIRV instruction");
6099 break;
6100 }
6101 case spv::OpCapability:
6102 case spv::OpExtension:
6103 case spv::OpMemoryModel:
6104 case spv::OpEntryPoint:
6105 case spv::OpExecutionMode:
6106 case spv::OpSource:
6107 case spv::OpDecorate:
6108 case spv::OpMemberDecorate:
6109 case spv::OpBranch:
6110 case spv::OpBranchConditional:
6111 case spv::OpSelectionMerge:
6112 case spv::OpLoopMerge:
6113 case spv::OpStore:
6114 case spv::OpImageWrite:
6115 case spv::OpReturnValue:
6116 case spv::OpControlBarrier:
6117 case spv::OpMemoryBarrier:
6118 case spv::OpReturn:
6119 case spv::OpFunctionEnd:
6120 case spv::OpCopyMemory: {
6121 WriteWordCountAndOpcode(Inst);
6122 for (uint32_t i = 0; i < Ops.size(); i++) {
6123 WriteOperand(Ops[i]);
6124 }
6125 break;
6126 }
6127 case spv::OpTypeBool:
6128 case spv::OpTypeVoid:
6129 case spv::OpTypeSampler:
6130 case spv::OpLabel:
6131 case spv::OpExtInstImport:
6132 case spv::OpTypePointer:
6133 case spv::OpTypeRuntimeArray:
6134 case spv::OpTypeStruct:
6135 case spv::OpTypeImage:
6136 case spv::OpTypeSampledImage:
6137 case spv::OpTypeInt:
6138 case spv::OpTypeFloat:
6139 case spv::OpTypeArray:
6140 case spv::OpTypeVector:
6141 case spv::OpTypeFunction: {
6142 WriteWordCountAndOpcode(Inst);
6143 WriteResultID(Inst);
6144 for (uint32_t i = 0; i < Ops.size(); i++) {
6145 WriteOperand(Ops[i]);
6146 }
6147 break;
6148 }
6149 case spv::OpFunction:
6150 case spv::OpFunctionParameter:
6151 case spv::OpAccessChain:
6152 case spv::OpPtrAccessChain:
6153 case spv::OpInBoundsAccessChain:
6154 case spv::OpUConvert:
6155 case spv::OpSConvert:
6156 case spv::OpConvertFToU:
6157 case spv::OpConvertFToS:
6158 case spv::OpConvertUToF:
6159 case spv::OpConvertSToF:
6160 case spv::OpFConvert:
6161 case spv::OpConvertPtrToU:
6162 case spv::OpConvertUToPtr:
6163 case spv::OpBitcast:
6164 case spv::OpIAdd:
6165 case spv::OpFAdd:
6166 case spv::OpISub:
6167 case spv::OpFSub:
6168 case spv::OpIMul:
6169 case spv::OpFMul:
6170 case spv::OpUDiv:
6171 case spv::OpSDiv:
6172 case spv::OpFDiv:
6173 case spv::OpUMod:
6174 case spv::OpSRem:
6175 case spv::OpFRem:
6176 case spv::OpBitwiseOr:
6177 case spv::OpBitwiseXor:
6178 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006179 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006180 case spv::OpShiftLeftLogical:
6181 case spv::OpShiftRightLogical:
6182 case spv::OpShiftRightArithmetic:
6183 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006184 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006185 case spv::OpCompositeExtract:
6186 case spv::OpVectorExtractDynamic:
6187 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006188 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006189 case spv::OpVectorInsertDynamic:
6190 case spv::OpVectorShuffle:
6191 case spv::OpIEqual:
6192 case spv::OpINotEqual:
6193 case spv::OpUGreaterThan:
6194 case spv::OpUGreaterThanEqual:
6195 case spv::OpULessThan:
6196 case spv::OpULessThanEqual:
6197 case spv::OpSGreaterThan:
6198 case spv::OpSGreaterThanEqual:
6199 case spv::OpSLessThan:
6200 case spv::OpSLessThanEqual:
6201 case spv::OpFOrdEqual:
6202 case spv::OpFOrdGreaterThan:
6203 case spv::OpFOrdGreaterThanEqual:
6204 case spv::OpFOrdLessThan:
6205 case spv::OpFOrdLessThanEqual:
6206 case spv::OpFOrdNotEqual:
6207 case spv::OpFUnordEqual:
6208 case spv::OpFUnordGreaterThan:
6209 case spv::OpFUnordGreaterThanEqual:
6210 case spv::OpFUnordLessThan:
6211 case spv::OpFUnordLessThanEqual:
6212 case spv::OpFUnordNotEqual:
6213 case spv::OpExtInst:
6214 case spv::OpIsInf:
6215 case spv::OpIsNan:
6216 case spv::OpAny:
6217 case spv::OpAll:
6218 case spv::OpUndef:
6219 case spv::OpConstantNull:
6220 case spv::OpLogicalOr:
6221 case spv::OpLogicalAnd:
6222 case spv::OpLogicalNot:
6223 case spv::OpLogicalNotEqual:
6224 case spv::OpConstantComposite:
6225 case spv::OpSpecConstantComposite:
6226 case spv::OpConstantTrue:
6227 case spv::OpConstantFalse:
6228 case spv::OpConstant:
6229 case spv::OpSpecConstant:
6230 case spv::OpVariable:
6231 case spv::OpFunctionCall:
6232 case spv::OpSampledImage:
6233 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006234 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006235 case spv::OpSelect:
6236 case spv::OpPhi:
6237 case spv::OpLoad:
6238 case spv::OpAtomicIAdd:
6239 case spv::OpAtomicISub:
6240 case spv::OpAtomicExchange:
6241 case spv::OpAtomicIIncrement:
6242 case spv::OpAtomicIDecrement:
6243 case spv::OpAtomicCompareExchange:
6244 case spv::OpAtomicUMin:
6245 case spv::OpAtomicSMin:
6246 case spv::OpAtomicUMax:
6247 case spv::OpAtomicSMax:
6248 case spv::OpAtomicAnd:
6249 case spv::OpAtomicOr:
6250 case spv::OpAtomicXor:
6251 case spv::OpDot: {
6252 WriteWordCountAndOpcode(Inst);
6253 WriteOperand(Ops[0]);
6254 WriteResultID(Inst);
6255 for (uint32_t i = 1; i < Ops.size(); i++) {
6256 WriteOperand(Ops[i]);
6257 }
6258 break;
6259 }
6260 }
6261 }
6262}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006263
alan-bakerb6b09dc2018-11-08 16:59:28 -05006264bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006265 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006266 case Type::HalfTyID:
6267 case Type::FloatTyID:
6268 case Type::DoubleTyID:
6269 case Type::IntegerTyID:
6270 case Type::VectorTyID:
6271 return true;
6272 case Type::PointerTyID: {
6273 const PointerType *pointer_type = cast<PointerType>(type);
6274 if (pointer_type->getPointerAddressSpace() !=
6275 AddressSpace::UniformConstant) {
6276 auto pointee_type = pointer_type->getPointerElementType();
6277 if (pointee_type->isStructTy() &&
6278 cast<StructType>(pointee_type)->isOpaque()) {
6279 // Images and samplers are not nullable.
6280 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006281 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006282 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006283 return true;
6284 }
6285 case Type::ArrayTyID:
6286 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6287 case Type::StructTyID: {
6288 const StructType *struct_type = cast<StructType>(type);
6289 // Images and samplers are not nullable.
6290 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006291 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006292 for (const auto element : struct_type->elements()) {
6293 if (!IsTypeNullable(element))
6294 return false;
6295 }
6296 return true;
6297 }
6298 default:
6299 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006300 }
6301}
Alan Bakerfcda9482018-10-02 17:09:59 -04006302
6303void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6304 if (auto *offsets_md =
6305 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6306 // Metdata is stored as key-value pair operands. The first element of each
6307 // operand is the type and the second is a vector of offsets.
6308 for (const auto *operand : offsets_md->operands()) {
6309 const auto *pair = cast<MDTuple>(operand);
6310 auto *type =
6311 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6312 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6313 std::vector<uint32_t> offsets;
6314 for (const Metadata *offset_md : offset_vector->operands()) {
6315 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006316 offsets.push_back(static_cast<uint32_t>(
6317 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006318 }
6319 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6320 }
6321 }
6322
6323 if (auto *sizes_md =
6324 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6325 // Metadata is stored as key-value pair operands. The first element of each
6326 // operand is the type and the second is a triple of sizes: type size in
6327 // bits, store size and alloc size.
6328 for (const auto *operand : sizes_md->operands()) {
6329 const auto *pair = cast<MDTuple>(operand);
6330 auto *type =
6331 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6332 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6333 uint64_t type_size_in_bits =
6334 cast<ConstantInt>(
6335 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6336 ->getZExtValue();
6337 uint64_t type_store_size =
6338 cast<ConstantInt>(
6339 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6340 ->getZExtValue();
6341 uint64_t type_alloc_size =
6342 cast<ConstantInt>(
6343 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6344 ->getZExtValue();
6345 RemappedUBOTypeSizes.insert(std::make_pair(
6346 type, std::make_tuple(type_size_in_bits, type_store_size,
6347 type_alloc_size)));
6348 }
6349 }
6350}
6351
6352uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6353 const DataLayout &DL) {
6354 auto iter = RemappedUBOTypeSizes.find(type);
6355 if (iter != RemappedUBOTypeSizes.end()) {
6356 return std::get<0>(iter->second);
6357 }
6358
6359 return DL.getTypeSizeInBits(type);
6360}
6361
6362uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6363 auto iter = RemappedUBOTypeSizes.find(type);
6364 if (iter != RemappedUBOTypeSizes.end()) {
6365 return std::get<1>(iter->second);
6366 }
6367
6368 return DL.getTypeStoreSize(type);
6369}
6370
6371uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6372 auto iter = RemappedUBOTypeSizes.find(type);
6373 if (iter != RemappedUBOTypeSizes.end()) {
6374 return std::get<2>(iter->second);
6375 }
6376
6377 return DL.getTypeAllocSize(type);
6378}