blob: d0f88152d0acec3789155be1b782c4ff41d96d58 [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.
1014 U->replaceUsesOfWith(GV, NewGV);
1015 }
1016
1017 // Delete original gv.
1018 GV->eraseFromParent();
1019 }
1020 }
1021}
1022
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001023void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001024 ResourceVarInfoList.clear();
1025 FunctionToResourceVarsMap.clear();
1026 ModuleOrderedResourceVars.reset();
1027 // Normally, there is one resource variable per clspv.resource.var.*
1028 // function, since that is unique'd by arg type and index. By design,
1029 // we can share these resource variables across kernels because all
1030 // kernels use the same descriptor set.
1031 //
1032 // But if the user requested distinct descriptor sets per kernel, then
1033 // the descriptor allocator has made different (set,binding) pairs for
1034 // the same (type,arg_index) pair. Since we can decorate a resource
1035 // variable with only exactly one DescriptorSet and Binding, we are
1036 // forced in this case to make distinct resource variables whenever
1037 // the same clspv.reource.var.X function is seen with disintct
1038 // (set,binding) values.
1039 const bool always_distinct_sets =
1040 clspv::Option::DistinctKernelDescriptorSets();
1041 for (Function &F : M) {
1042 // Rely on the fact the resource var functions have a stable ordering
1043 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001044 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001045 // Find all calls to this function with distinct set and binding pairs.
1046 // Save them in ResourceVarInfoList.
1047
1048 // Determine uniqueness of the (set,binding) pairs only withing this
1049 // one resource-var builtin function.
1050 using SetAndBinding = std::pair<unsigned, unsigned>;
1051 // Maps set and binding to the resource var info.
1052 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1053 bool first_use = true;
1054 for (auto &U : F.uses()) {
1055 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1056 const auto set = unsigned(
1057 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1058 const auto binding = unsigned(
1059 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1060 const auto arg_kind = clspv::ArgKind(
1061 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1062 const auto arg_index = unsigned(
1063 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1064
1065 // Find or make the resource var info for this combination.
1066 ResourceVarInfo *rv = nullptr;
1067 if (always_distinct_sets) {
1068 // Make a new resource var any time we see a different
1069 // (set,binding) pair.
1070 SetAndBinding key{set, binding};
1071 auto where = set_and_binding_map.find(key);
1072 if (where == set_and_binding_map.end()) {
1073 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1074 binding, &F, arg_kind);
1075 ResourceVarInfoList.emplace_back(rv);
1076 set_and_binding_map[key] = rv;
1077 } else {
1078 rv = where->second;
1079 }
1080 } else {
1081 // The default is to make exactly one resource for each
1082 // clspv.resource.var.* function.
1083 if (first_use) {
1084 first_use = false;
1085 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1086 binding, &F, arg_kind);
1087 ResourceVarInfoList.emplace_back(rv);
1088 } else {
1089 rv = ResourceVarInfoList.back().get();
1090 }
1091 }
1092
1093 // Now populate FunctionToResourceVarsMap.
1094 auto &mapping =
1095 FunctionToResourceVarsMap[call->getParent()->getParent()];
1096 while (mapping.size() <= arg_index) {
1097 mapping.push_back(nullptr);
1098 }
1099 mapping[arg_index] = rv;
1100 }
1101 }
1102 }
1103 }
1104
1105 // Populate ModuleOrderedResourceVars.
1106 for (Function &F : M) {
1107 auto where = FunctionToResourceVarsMap.find(&F);
1108 if (where != FunctionToResourceVarsMap.end()) {
1109 for (auto &rv : where->second) {
1110 if (rv != nullptr) {
1111 ModuleOrderedResourceVars.insert(rv);
1112 }
1113 }
1114 }
1115 }
1116 if (ShowResourceVars) {
1117 for (auto *info : ModuleOrderedResourceVars) {
1118 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1119 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1120 << "\n";
1121 }
1122 }
1123}
1124
David Neto22f144c2017-06-12 14:26:21 -04001125bool SPIRVProducerPass::FindExtInst(Module &M) {
1126 LLVMContext &Context = M.getContext();
1127 bool HasExtInst = false;
1128
1129 for (Function &F : M) {
1130 for (BasicBlock &BB : F) {
1131 for (Instruction &I : BB) {
1132 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1133 Function *Callee = Call->getCalledFunction();
1134 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001135 auto callee_name = Callee->getName();
1136 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1137 const glsl::ExtInst IndirectEInst =
1138 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001139
David Neto3fbb4072017-10-16 11:28:14 -04001140 HasExtInst |=
1141 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1142
1143 if (IndirectEInst) {
1144 // Register extra constants if needed.
1145
1146 // Registers a type and constant for computing the result of the
1147 // given instruction. If the result of the instruction is a vector,
1148 // then make a splat vector constant with the same number of
1149 // elements.
1150 auto register_constant = [this, &I](Constant *constant) {
1151 FindType(constant->getType());
1152 FindConstant(constant);
1153 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1154 // Register the splat vector of the value with the same
1155 // width as the result of the instruction.
1156 auto *vec_constant = ConstantVector::getSplat(
1157 static_cast<unsigned>(vectorTy->getNumElements()),
1158 constant);
1159 FindConstant(vec_constant);
1160 FindType(vec_constant->getType());
1161 }
1162 };
1163 switch (IndirectEInst) {
1164 case glsl::ExtInstFindUMsb:
1165 // clz needs OpExtInst and OpISub with constant 31, or splat
1166 // vector of 31. Add it to the constant list here.
1167 register_constant(
1168 ConstantInt::get(Type::getInt32Ty(Context), 31));
1169 break;
1170 case glsl::ExtInstAcos:
1171 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001172 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001173 case glsl::ExtInstAtan2:
1174 // We need 1/pi for acospi, asinpi, atan2pi.
1175 register_constant(
1176 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1177 break;
1178 default:
1179 assert(false && "internally inconsistent");
1180 }
David Neto22f144c2017-06-12 14:26:21 -04001181 }
1182 }
1183 }
1184 }
1185 }
1186
1187 return HasExtInst;
1188}
1189
1190void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1191 // Investigate global variable's type.
1192 FindType(GV.getType());
1193}
1194
1195void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1196 // Investigate function's type.
1197 FunctionType *FTy = F.getFunctionType();
1198
1199 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1200 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001201 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001202 if (GlobalConstFuncTyMap.count(FTy)) {
1203 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1204 SmallVector<Type *, 4> NewFuncParamTys;
1205 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1206 Type *ParamTy = FTy->getParamType(i);
1207 if (i == GVCstArgIdx) {
1208 Type *EleTy = ParamTy->getPointerElementType();
1209 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1210 }
1211
1212 NewFuncParamTys.push_back(ParamTy);
1213 }
1214
1215 FunctionType *NewFTy =
1216 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1217 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1218 FTy = NewFTy;
1219 }
1220
1221 FindType(FTy);
1222 } else {
1223 // As kernel functions do not have parameters, create new function type and
1224 // add it to type map.
1225 SmallVector<Type *, 4> NewFuncParamTys;
1226 FunctionType *NewFTy =
1227 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1228 FindType(NewFTy);
1229 }
1230
1231 // Investigate instructions' type in function body.
1232 for (BasicBlock &BB : F) {
1233 for (Instruction &I : BB) {
1234 if (isa<ShuffleVectorInst>(I)) {
1235 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1236 // Ignore type for mask of shuffle vector instruction.
1237 if (i == 2) {
1238 continue;
1239 }
1240
1241 Value *Op = I.getOperand(i);
1242 if (!isa<MetadataAsValue>(Op)) {
1243 FindType(Op->getType());
1244 }
1245 }
1246
1247 FindType(I.getType());
1248 continue;
1249 }
1250
David Neto862b7d82018-06-14 18:48:37 -04001251 CallInst *Call = dyn_cast<CallInst>(&I);
1252
1253 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001254 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001255 // This is a fake call representing access to a resource variable.
1256 // We handle that elsewhere.
1257 continue;
1258 }
1259
Alan Baker202c8c72018-08-13 13:47:44 -04001260 if (Call && Call->getCalledFunction()->getName().startswith(
1261 clspv::WorkgroupAccessorFunction())) {
1262 // This is a fake call representing access to a workgroup variable.
1263 // We handle that elsewhere.
1264 continue;
1265 }
1266
David Neto22f144c2017-06-12 14:26:21 -04001267 // Work through the operands of the instruction.
1268 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1269 Value *const Op = I.getOperand(i);
1270 // If any of the operands is a constant, find the type!
1271 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1272 FindType(Op->getType());
1273 }
1274 }
1275
1276 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001277 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001278 // Avoid to check call instruction's type.
1279 break;
1280 }
Alan Baker202c8c72018-08-13 13:47:44 -04001281 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1282 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1283 clspv::WorkgroupAccessorFunction())) {
1284 // This is a fake call representing access to a workgroup variable.
1285 // We handle that elsewhere.
1286 continue;
1287 }
1288 }
David Neto22f144c2017-06-12 14:26:21 -04001289 if (!isa<MetadataAsValue>(&Op)) {
1290 FindType(Op->getType());
1291 continue;
1292 }
1293 }
1294
David Neto22f144c2017-06-12 14:26:21 -04001295 // We don't want to track the type of this call as we are going to replace
1296 // it.
David Neto862b7d82018-06-14 18:48:37 -04001297 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001298 Call->getCalledFunction()->getName())) {
1299 continue;
1300 }
1301
1302 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1303 // If gep's base operand has ModuleScopePrivate address space, make gep
1304 // return ModuleScopePrivate address space.
1305 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1306 // Add pointer type with private address space for global constant to
1307 // type list.
1308 Type *EleTy = I.getType()->getPointerElementType();
1309 Type *NewPTy =
1310 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1311
1312 FindType(NewPTy);
1313 continue;
1314 }
1315 }
1316
1317 FindType(I.getType());
1318 }
1319 }
1320}
1321
David Neto862b7d82018-06-14 18:48:37 -04001322void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1323 // If we are using a sampler map, find the type of the sampler.
1324 if (M.getFunction("clspv.sampler.var.literal") ||
1325 0 < getSamplerMap().size()) {
1326 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1327 if (!SamplerStructTy) {
1328 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1329 }
1330
1331 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1332
1333 FindType(SamplerTy);
1334 }
1335}
1336
1337void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1338 // Record types so they are generated.
1339 TypesNeedingLayout.reset();
1340 StructTypesNeedingBlock.reset();
1341
1342 // To match older clspv codegen, generate the float type first if required
1343 // for images.
1344 for (const auto *info : ModuleOrderedResourceVars) {
1345 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1346 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1347 // We need "float" for the sampled component type.
1348 FindType(Type::getFloatTy(M.getContext()));
1349 // We only need to find it once.
1350 break;
1351 }
1352 }
1353
1354 for (const auto *info : ModuleOrderedResourceVars) {
1355 Type *type = info->var_fn->getReturnType();
1356
1357 switch (info->arg_kind) {
1358 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001359 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001360 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1361 StructTypesNeedingBlock.insert(sty);
1362 } else {
1363 errs() << *type << "\n";
1364 llvm_unreachable("Buffer arguments must map to structures!");
1365 }
1366 break;
1367 case clspv::ArgKind::Pod:
1368 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1369 StructTypesNeedingBlock.insert(sty);
1370 } else {
1371 errs() << *type << "\n";
1372 llvm_unreachable("POD arguments must map to structures!");
1373 }
1374 break;
1375 case clspv::ArgKind::ReadOnlyImage:
1376 case clspv::ArgKind::WriteOnlyImage:
1377 case clspv::ArgKind::Sampler:
1378 // Sampler and image types map to the pointee type but
1379 // in the uniform constant address space.
1380 type = PointerType::get(type->getPointerElementType(),
1381 clspv::AddressSpace::UniformConstant);
1382 break;
1383 default:
1384 break;
1385 }
1386
1387 // The converted type is the type of the OpVariable we will generate.
1388 // If the pointee type is an array of size zero, FindType will convert it
1389 // to a runtime array.
1390 FindType(type);
1391 }
1392
1393 // Traverse the arrays and structures underneath each Block, and
1394 // mark them as needing layout.
1395 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1396 StructTypesNeedingBlock.end());
1397 while (!work_list.empty()) {
1398 Type *type = work_list.back();
1399 work_list.pop_back();
1400 TypesNeedingLayout.insert(type);
1401 switch (type->getTypeID()) {
1402 case Type::ArrayTyID:
1403 work_list.push_back(type->getArrayElementType());
1404 if (!Hack_generate_runtime_array_stride_early) {
1405 // Remember this array type for deferred decoration.
1406 TypesNeedingArrayStride.insert(type);
1407 }
1408 break;
1409 case Type::StructTyID:
1410 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1411 work_list.push_back(elem_ty);
1412 }
1413 default:
1414 // This type and its contained types don't get layout.
1415 break;
1416 }
1417 }
1418}
1419
Alan Baker202c8c72018-08-13 13:47:44 -04001420void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1421 // The SpecId assignment for pointer-to-local arguments is recorded in
1422 // module-level metadata. Translate that information into local argument
1423 // information.
1424 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001425 if (!nmd)
1426 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001427 for (auto operand : nmd->operands()) {
1428 MDTuple *tuple = cast<MDTuple>(operand);
1429 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1430 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001431 ConstantAsMetadata *arg_index_md =
1432 cast<ConstantAsMetadata>(tuple->getOperand(1));
1433 int arg_index = static_cast<int>(
1434 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1435 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001436
1437 ConstantAsMetadata *spec_id_md =
1438 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001439 int spec_id = static_cast<int>(
1440 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001441
1442 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1443 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001444 if (LocalSpecIdInfoMap.count(spec_id))
1445 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001446
1447 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1448 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1449 nextID + 1, nextID + 2,
1450 nextID + 3, spec_id};
1451 LocalSpecIdInfoMap[spec_id] = info;
1452 nextID += 4;
1453
1454 // Ensure the types necessary for this argument get generated.
1455 Type *IdxTy = Type::getInt32Ty(M.getContext());
1456 FindConstant(ConstantInt::get(IdxTy, 0));
1457 FindType(IdxTy);
1458 FindType(arg->getType());
1459 }
1460}
1461
David Neto22f144c2017-06-12 14:26:21 -04001462void SPIRVProducerPass::FindType(Type *Ty) {
1463 TypeList &TyList = getTypeList();
1464
1465 if (0 != TyList.idFor(Ty)) {
1466 return;
1467 }
1468
1469 if (Ty->isPointerTy()) {
1470 auto AddrSpace = Ty->getPointerAddressSpace();
1471 if ((AddressSpace::Constant == AddrSpace) ||
1472 (AddressSpace::Global == AddrSpace)) {
1473 auto PointeeTy = Ty->getPointerElementType();
1474
1475 if (PointeeTy->isStructTy() &&
1476 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1477 FindType(PointeeTy);
1478 auto ActualPointerTy =
1479 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1480 FindType(ActualPointerTy);
1481 return;
1482 }
1483 }
1484 }
1485
David Neto862b7d82018-06-14 18:48:37 -04001486 // By convention, LLVM array type with 0 elements will map to
1487 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1488 // has a constant number of elements. We need to support type of the
1489 // constant.
1490 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1491 if (arrayTy->getNumElements() > 0) {
1492 LLVMContext &Context = Ty->getContext();
1493 FindType(Type::getInt32Ty(Context));
1494 }
David Neto22f144c2017-06-12 14:26:21 -04001495 }
1496
1497 for (Type *SubTy : Ty->subtypes()) {
1498 FindType(SubTy);
1499 }
1500
1501 TyList.insert(Ty);
1502}
1503
1504void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1505 // If the global variable has a (non undef) initializer.
1506 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001507 // Generate the constant if it's not the initializer to a module scope
1508 // constant that we will expect in a storage buffer.
1509 const bool module_scope_constant_external_init =
1510 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1511 clspv::Option::ModuleConstantsInStorageBuffer();
1512 if (!module_scope_constant_external_init) {
1513 FindConstant(GV.getInitializer());
1514 }
David Neto22f144c2017-06-12 14:26:21 -04001515 }
1516}
1517
1518void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1519 // Investigate constants in function body.
1520 for (BasicBlock &BB : F) {
1521 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001522 if (auto *call = dyn_cast<CallInst>(&I)) {
1523 auto name = call->getCalledFunction()->getName();
1524 if (name == "clspv.sampler.var.literal") {
1525 // We've handled these constants elsewhere, so skip it.
1526 continue;
1527 }
Alan Baker202c8c72018-08-13 13:47:44 -04001528 if (name.startswith(clspv::ResourceAccessorFunction())) {
1529 continue;
1530 }
1531 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001532 continue;
1533 }
David Neto22f144c2017-06-12 14:26:21 -04001534 }
1535
1536 if (isa<AllocaInst>(I)) {
1537 // Alloca instruction has constant for the number of element. Ignore it.
1538 continue;
1539 } else if (isa<ShuffleVectorInst>(I)) {
1540 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1541 // Ignore constant for mask of shuffle vector instruction.
1542 if (i == 2) {
1543 continue;
1544 }
1545
1546 if (isa<Constant>(I.getOperand(i)) &&
1547 !isa<GlobalValue>(I.getOperand(i))) {
1548 FindConstant(I.getOperand(i));
1549 }
1550 }
1551
1552 continue;
1553 } else if (isa<InsertElementInst>(I)) {
1554 // Handle InsertElement with <4 x i8> specially.
1555 Type *CompositeTy = I.getOperand(0)->getType();
1556 if (is4xi8vec(CompositeTy)) {
1557 LLVMContext &Context = CompositeTy->getContext();
1558 if (isa<Constant>(I.getOperand(0))) {
1559 FindConstant(I.getOperand(0));
1560 }
1561
1562 if (isa<Constant>(I.getOperand(1))) {
1563 FindConstant(I.getOperand(1));
1564 }
1565
1566 // Add mask constant 0xFF.
1567 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1568 FindConstant(CstFF);
1569
1570 // Add shift amount constant.
1571 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1572 uint64_t Idx = CI->getZExtValue();
1573 Constant *CstShiftAmount =
1574 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1575 FindConstant(CstShiftAmount);
1576 }
1577
1578 continue;
1579 }
1580
1581 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1582 // Ignore constant for index of InsertElement instruction.
1583 if (i == 2) {
1584 continue;
1585 }
1586
1587 if (isa<Constant>(I.getOperand(i)) &&
1588 !isa<GlobalValue>(I.getOperand(i))) {
1589 FindConstant(I.getOperand(i));
1590 }
1591 }
1592
1593 continue;
1594 } else if (isa<ExtractElementInst>(I)) {
1595 // Handle ExtractElement with <4 x i8> specially.
1596 Type *CompositeTy = I.getOperand(0)->getType();
1597 if (is4xi8vec(CompositeTy)) {
1598 LLVMContext &Context = CompositeTy->getContext();
1599 if (isa<Constant>(I.getOperand(0))) {
1600 FindConstant(I.getOperand(0));
1601 }
1602
1603 // Add mask constant 0xFF.
1604 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1605 FindConstant(CstFF);
1606
1607 // Add shift amount constant.
1608 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1609 uint64_t Idx = CI->getZExtValue();
1610 Constant *CstShiftAmount =
1611 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1612 FindConstant(CstShiftAmount);
1613 } else {
1614 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1615 FindConstant(Cst8);
1616 }
1617
1618 continue;
1619 }
1620
1621 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1622 // Ignore constant for index of ExtractElement instruction.
1623 if (i == 1) {
1624 continue;
1625 }
1626
1627 if (isa<Constant>(I.getOperand(i)) &&
1628 !isa<GlobalValue>(I.getOperand(i))) {
1629 FindConstant(I.getOperand(i));
1630 }
1631 }
1632
1633 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001634 } else if ((Instruction::Xor == I.getOpcode()) &&
1635 I.getType()->isIntegerTy(1)) {
1636 // We special case for Xor where the type is i1 and one of the arguments
1637 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1638 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001639 bool foundConstantTrue = false;
1640 for (Use &Op : I.operands()) {
1641 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1642 auto CI = cast<ConstantInt>(Op);
1643
1644 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001645 // If we already found the true constant, we might (probably only
1646 // on -O0) have an OpLogicalNot which is taking a constant
1647 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001648 FindConstant(Op);
1649 } else {
1650 foundConstantTrue = true;
1651 }
1652 }
1653 }
1654
1655 continue;
David Netod2de94a2017-08-28 17:27:47 -04001656 } else if (isa<TruncInst>(I)) {
1657 // For truncation to i8 we mask against 255.
1658 Type *ToTy = I.getType();
1659 if (8u == ToTy->getPrimitiveSizeInBits()) {
1660 LLVMContext &Context = ToTy->getContext();
1661 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1662 FindConstant(Cst255);
1663 }
1664 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001665 } else if (isa<AtomicRMWInst>(I)) {
1666 LLVMContext &Context = I.getContext();
1667
1668 FindConstant(
1669 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1670 FindConstant(ConstantInt::get(
1671 Type::getInt32Ty(Context),
1672 spv::MemorySemanticsUniformMemoryMask |
1673 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001674 }
1675
1676 for (Use &Op : I.operands()) {
1677 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1678 FindConstant(Op);
1679 }
1680 }
1681 }
1682 }
1683}
1684
1685void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001686 ValueList &CstList = getConstantList();
1687
David Netofb9a7972017-08-25 17:08:24 -04001688 // If V is already tracked, ignore it.
1689 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001690 return;
1691 }
1692
David Neto862b7d82018-06-14 18:48:37 -04001693 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1694 return;
1695 }
1696
David Neto22f144c2017-06-12 14:26:21 -04001697 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001698 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001699
1700 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001701 if (is4xi8vec(CstTy)) {
1702 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001703 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001704 }
1705 }
1706
1707 if (Cst->getNumOperands()) {
1708 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1709 ++I) {
1710 FindConstant(*I);
1711 }
1712
David Netofb9a7972017-08-25 17:08:24 -04001713 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001714 return;
1715 } else if (const ConstantDataSequential *CDS =
1716 dyn_cast<ConstantDataSequential>(Cst)) {
1717 // Add constants for each element to constant list.
1718 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1719 Constant *EleCst = CDS->getElementAsConstant(i);
1720 FindConstant(EleCst);
1721 }
1722 }
1723
1724 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001725 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001726 }
1727}
1728
1729spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1730 switch (AddrSpace) {
1731 default:
1732 llvm_unreachable("Unsupported OpenCL address space");
1733 case AddressSpace::Private:
1734 return spv::StorageClassFunction;
1735 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001736 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001737 case AddressSpace::Constant:
1738 return clspv::Option::ConstantArgsInUniformBuffer()
1739 ? spv::StorageClassUniform
1740 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001741 case AddressSpace::Input:
1742 return spv::StorageClassInput;
1743 case AddressSpace::Local:
1744 return spv::StorageClassWorkgroup;
1745 case AddressSpace::UniformConstant:
1746 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001747 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001748 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001749 case AddressSpace::ModuleScopePrivate:
1750 return spv::StorageClassPrivate;
1751 }
1752}
1753
David Neto862b7d82018-06-14 18:48:37 -04001754spv::StorageClass
1755SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1756 switch (arg_kind) {
1757 case clspv::ArgKind::Buffer:
1758 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001759 case clspv::ArgKind::BufferUBO:
1760 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001761 case clspv::ArgKind::Pod:
1762 return clspv::Option::PodArgsInUniformBuffer()
1763 ? spv::StorageClassUniform
1764 : spv::StorageClassStorageBuffer;
1765 case clspv::ArgKind::Local:
1766 return spv::StorageClassWorkgroup;
1767 case clspv::ArgKind::ReadOnlyImage:
1768 case clspv::ArgKind::WriteOnlyImage:
1769 case clspv::ArgKind::Sampler:
1770 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001771 default:
1772 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001773 }
1774}
1775
David Neto22f144c2017-06-12 14:26:21 -04001776spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1777 return StringSwitch<spv::BuiltIn>(Name)
1778 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1779 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1780 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1781 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1782 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1783 .Default(spv::BuiltInMax);
1784}
1785
1786void SPIRVProducerPass::GenerateExtInstImport() {
1787 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1788 uint32_t &ExtInstImportID = getOpExtInstImportID();
1789
1790 //
1791 // Generate OpExtInstImport.
1792 //
1793 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001794 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001795 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1796 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001797}
1798
alan-bakerb6b09dc2018-11-08 16:59:28 -05001799void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1800 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001801 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1802 ValueMapType &VMap = getValueMap();
1803 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001804 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001805
1806 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1807 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1808 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1809
1810 for (Type *Ty : getTypeList()) {
1811 // Update TypeMap with nextID for reference later.
1812 TypeMap[Ty] = nextID;
1813
1814 switch (Ty->getTypeID()) {
1815 default: {
1816 Ty->print(errs());
1817 llvm_unreachable("Unsupported type???");
1818 break;
1819 }
1820 case Type::MetadataTyID:
1821 case Type::LabelTyID: {
1822 // Ignore these types.
1823 break;
1824 }
1825 case Type::PointerTyID: {
1826 PointerType *PTy = cast<PointerType>(Ty);
1827 unsigned AddrSpace = PTy->getAddressSpace();
1828
1829 // For the purposes of our Vulkan SPIR-V type system, constant and global
1830 // are conflated.
1831 bool UseExistingOpTypePointer = false;
1832 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001833 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1834 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001835 // Check to see if we already created this type (for instance, if we
1836 // had a constant <type>* and a global <type>*, the type would be
1837 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001838 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1839 if (0 < TypeMap.count(GlobalTy)) {
1840 TypeMap[PTy] = TypeMap[GlobalTy];
1841 UseExistingOpTypePointer = true;
1842 break;
1843 }
David Neto22f144c2017-06-12 14:26:21 -04001844 }
1845 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001846 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1847 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001848
alan-bakerb6b09dc2018-11-08 16:59:28 -05001849 // Check to see if we already created this type (for instance, if we
1850 // had a constant <type>* and a global <type>*, the type would be
1851 // created by one of these types, and shared by both).
1852 auto ConstantTy =
1853 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001854 if (0 < TypeMap.count(ConstantTy)) {
1855 TypeMap[PTy] = TypeMap[ConstantTy];
1856 UseExistingOpTypePointer = true;
1857 }
David Neto22f144c2017-06-12 14:26:21 -04001858 }
1859 }
1860
David Neto862b7d82018-06-14 18:48:37 -04001861 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001862
David Neto862b7d82018-06-14 18:48:37 -04001863 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001864 //
1865 // Generate OpTypePointer.
1866 //
1867
1868 // OpTypePointer
1869 // Ops[0] = Storage Class
1870 // Ops[1] = Element Type ID
1871 SPIRVOperandList Ops;
1872
David Neto257c3892018-04-11 13:19:45 -04001873 Ops << MkNum(GetStorageClass(AddrSpace))
1874 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001875
David Neto87846742018-04-11 17:36:22 -04001876 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001877 SPIRVInstList.push_back(Inst);
1878 }
David Neto22f144c2017-06-12 14:26:21 -04001879 break;
1880 }
1881 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001882 StructType *STy = cast<StructType>(Ty);
1883
1884 // Handle sampler type.
1885 if (STy->isOpaque()) {
1886 if (STy->getName().equals("opencl.sampler_t")) {
1887 //
1888 // Generate OpTypeSampler
1889 //
1890 // Empty Ops.
1891 SPIRVOperandList Ops;
1892
David Neto87846742018-04-11 17:36:22 -04001893 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001894 SPIRVInstList.push_back(Inst);
1895 break;
1896 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1897 STy->getName().equals("opencl.image2d_wo_t") ||
1898 STy->getName().equals("opencl.image3d_ro_t") ||
1899 STy->getName().equals("opencl.image3d_wo_t")) {
1900 //
1901 // Generate OpTypeImage
1902 //
1903 // Ops[0] = Sampled Type ID
1904 // Ops[1] = Dim ID
1905 // Ops[2] = Depth (Literal Number)
1906 // Ops[3] = Arrayed (Literal Number)
1907 // Ops[4] = MS (Literal Number)
1908 // Ops[5] = Sampled (Literal Number)
1909 // Ops[6] = Image Format ID
1910 //
1911 SPIRVOperandList Ops;
1912
1913 // TODO: Changed Sampled Type according to situations.
1914 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001915 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001916
1917 spv::Dim DimID = spv::Dim2D;
1918 if (STy->getName().equals("opencl.image3d_ro_t") ||
1919 STy->getName().equals("opencl.image3d_wo_t")) {
1920 DimID = spv::Dim3D;
1921 }
David Neto257c3892018-04-11 13:19:45 -04001922 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001923
1924 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001925 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001926
1927 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001928 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001929
1930 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001931 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001932
1933 // TODO: Set up Sampled.
1934 //
1935 // From Spec
1936 //
1937 // 0 indicates this is only known at run time, not at compile time
1938 // 1 indicates will be used with sampler
1939 // 2 indicates will be used without a sampler (a storage image)
1940 uint32_t Sampled = 1;
1941 if (STy->getName().equals("opencl.image2d_wo_t") ||
1942 STy->getName().equals("opencl.image3d_wo_t")) {
1943 Sampled = 2;
1944 }
David Neto257c3892018-04-11 13:19:45 -04001945 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001946
1947 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001948 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001949
David Neto87846742018-04-11 17:36:22 -04001950 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001951 SPIRVInstList.push_back(Inst);
1952 break;
1953 }
1954 }
1955
1956 //
1957 // Generate OpTypeStruct
1958 //
1959 // Ops[0] ... Ops[n] = Member IDs
1960 SPIRVOperandList Ops;
1961
1962 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001963 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001964 }
1965
David Neto22f144c2017-06-12 14:26:21 -04001966 uint32_t STyID = nextID;
1967
alan-bakerb6b09dc2018-11-08 16:59:28 -05001968 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001969 SPIRVInstList.push_back(Inst);
1970
1971 // Generate OpMemberDecorate.
1972 auto DecoInsertPoint =
1973 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1974 [](SPIRVInstruction *Inst) -> bool {
1975 return Inst->getOpcode() != spv::OpDecorate &&
1976 Inst->getOpcode() != spv::OpMemberDecorate &&
1977 Inst->getOpcode() != spv::OpExtInstImport;
1978 });
1979
David Netoc463b372017-08-10 15:32:21 -04001980 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001981 // Search for the correct offsets if this type was remapped.
1982 std::vector<uint32_t> *offsets = nullptr;
1983 auto iter = RemappedUBOTypeOffsets.find(STy);
1984 if (iter != RemappedUBOTypeOffsets.end()) {
1985 offsets = &iter->second;
1986 }
David Netoc463b372017-08-10 15:32:21 -04001987
David Neto862b7d82018-06-14 18:48:37 -04001988 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001989 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1990 MemberIdx++) {
1991 // Ops[0] = Structure Type ID
1992 // Ops[1] = Member Index(Literal Number)
1993 // Ops[2] = Decoration (Offset)
1994 // Ops[3] = Byte Offset (Literal Number)
1995 Ops.clear();
1996
David Neto257c3892018-04-11 13:19:45 -04001997 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001998
alan-bakerb6b09dc2018-11-08 16:59:28 -05001999 auto ByteOffset =
2000 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002001 if (offsets) {
2002 ByteOffset = (*offsets)[MemberIdx];
2003 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002004 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002005 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002006 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002007
David Neto87846742018-04-11 17:36:22 -04002008 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002009 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002010 }
2011
2012 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002013 if (StructTypesNeedingBlock.idFor(STy)) {
2014 Ops.clear();
2015 // Use Block decorations with StorageBuffer storage class.
2016 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002017
David Neto862b7d82018-06-14 18:48:37 -04002018 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2019 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002020 }
2021 break;
2022 }
2023 case Type::IntegerTyID: {
2024 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2025
2026 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002027 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002028 SPIRVInstList.push_back(Inst);
2029 } else {
2030 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002031 // No matter what LLVM type is requested first, always alias the
2032 // second one's SPIR-V type to be the same as the one we generated
2033 // first.
Neil Henning39672102017-09-29 14:33:13 +01002034 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002035 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002036 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002037 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002038 } else if (BitWidth == 32) {
2039 aliasToWidth = 8;
2040 }
2041 if (aliasToWidth) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002042 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
David Neto391aeb12017-08-26 15:51:58 -04002043 auto where = TypeMap.find(otherType);
2044 if (where == TypeMap.end()) {
2045 // Go ahead and make it, but also map the other type to it.
2046 TypeMap[otherType] = nextID;
2047 } else {
2048 // Alias this SPIR-V type the existing type.
2049 TypeMap[Ty] = where->second;
2050 break;
2051 }
David Neto22f144c2017-06-12 14:26:21 -04002052 }
2053
David Neto257c3892018-04-11 13:19:45 -04002054 SPIRVOperandList Ops;
2055 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002056
2057 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002058 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002059 }
2060 break;
2061 }
2062 case Type::HalfTyID:
2063 case Type::FloatTyID:
2064 case Type::DoubleTyID: {
2065 SPIRVOperand *WidthOp = new SPIRVOperand(
2066 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2067
2068 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002069 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002070 break;
2071 }
2072 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002073 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002074 const uint64_t Length = ArrTy->getArrayNumElements();
2075 if (Length == 0) {
2076 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002077
David Neto862b7d82018-06-14 18:48:37 -04002078 // Only generate the type once.
2079 // TODO(dneto): Can it ever be generated more than once?
2080 // Doesn't LLVM type uniqueness guarantee we'll only see this
2081 // once?
2082 Type *EleTy = ArrTy->getArrayElementType();
2083 if (OpRuntimeTyMap.count(EleTy) == 0) {
2084 uint32_t OpTypeRuntimeArrayID = nextID;
2085 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002086
David Neto862b7d82018-06-14 18:48:37 -04002087 //
2088 // Generate OpTypeRuntimeArray.
2089 //
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 // OpTypeRuntimeArray
2092 // Ops[0] = Element Type ID
2093 SPIRVOperandList Ops;
2094 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002095
David Neto862b7d82018-06-14 18:48:37 -04002096 SPIRVInstList.push_back(
2097 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002098
David Neto862b7d82018-06-14 18:48:37 -04002099 if (Hack_generate_runtime_array_stride_early) {
2100 // Generate OpDecorate.
2101 auto DecoInsertPoint = std::find_if(
2102 SPIRVInstList.begin(), SPIRVInstList.end(),
2103 [](SPIRVInstruction *Inst) -> bool {
2104 return Inst->getOpcode() != spv::OpDecorate &&
2105 Inst->getOpcode() != spv::OpMemberDecorate &&
2106 Inst->getOpcode() != spv::OpExtInstImport;
2107 });
David Neto22f144c2017-06-12 14:26:21 -04002108
David Neto862b7d82018-06-14 18:48:37 -04002109 // Ops[0] = Target ID
2110 // Ops[1] = Decoration (ArrayStride)
2111 // Ops[2] = Stride Number(Literal Number)
2112 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002113
David Neto862b7d82018-06-14 18:48:37 -04002114 Ops << MkId(OpTypeRuntimeArrayID)
2115 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002116 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002117
David Neto862b7d82018-06-14 18:48:37 -04002118 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2119 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2120 }
2121 }
David Neto22f144c2017-06-12 14:26:21 -04002122
David Neto862b7d82018-06-14 18:48:37 -04002123 } else {
David Neto22f144c2017-06-12 14:26:21 -04002124
David Neto862b7d82018-06-14 18:48:37 -04002125 //
2126 // Generate OpConstant and OpTypeArray.
2127 //
2128
2129 //
2130 // Generate OpConstant for array length.
2131 //
2132 // Ops[0] = Result Type ID
2133 // Ops[1] .. Ops[n] = Values LiteralNumber
2134 SPIRVOperandList Ops;
2135
2136 Type *LengthTy = Type::getInt32Ty(Context);
2137 uint32_t ResTyID = lookupType(LengthTy);
2138 Ops << MkId(ResTyID);
2139
2140 assert(Length < UINT32_MAX);
2141 Ops << MkNum(static_cast<uint32_t>(Length));
2142
2143 // Add constant for length to constant list.
2144 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2145 AllocatedVMap[CstLength] = nextID;
2146 VMap[CstLength] = nextID;
2147 uint32_t LengthID = nextID;
2148
2149 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2150 SPIRVInstList.push_back(CstInst);
2151
2152 // Remember to generate ArrayStride later
2153 getTypesNeedingArrayStride().insert(Ty);
2154
2155 //
2156 // Generate OpTypeArray.
2157 //
2158 // Ops[0] = Element Type ID
2159 // Ops[1] = Array Length Constant ID
2160 Ops.clear();
2161
2162 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2163 Ops << MkId(EleTyID) << MkId(LengthID);
2164
2165 // Update TypeMap with nextID.
2166 TypeMap[Ty] = nextID;
2167
2168 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2169 SPIRVInstList.push_back(ArrayInst);
2170 }
David Neto22f144c2017-06-12 14:26:21 -04002171 break;
2172 }
2173 case Type::VectorTyID: {
2174 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002175 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2176 if (Ty->getVectorNumElements() == 4) {
2177 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2178 break;
2179 } else {
2180 Ty->print(errs());
2181 llvm_unreachable("Support above i8 vector type");
2182 }
2183 }
2184
2185 // Ops[0] = Component Type ID
2186 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002187 SPIRVOperandList Ops;
2188 Ops << MkId(lookupType(Ty->getVectorElementType()))
2189 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002190
alan-bakerb6b09dc2018-11-08 16:59:28 -05002191 SPIRVInstruction *inst =
2192 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002193 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002194 break;
2195 }
2196 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002197 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002198 SPIRVInstList.push_back(Inst);
2199 break;
2200 }
2201 case Type::FunctionTyID: {
2202 // Generate SPIRV instruction for function type.
2203 FunctionType *FTy = cast<FunctionType>(Ty);
2204
2205 // Ops[0] = Return Type ID
2206 // Ops[1] ... Ops[n] = Parameter Type IDs
2207 SPIRVOperandList Ops;
2208
2209 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002210 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002211
2212 // Find SPIRV instructions for parameter types
2213 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2214 // Find SPIRV instruction for parameter type.
2215 auto ParamTy = FTy->getParamType(k);
2216 if (ParamTy->isPointerTy()) {
2217 auto PointeeTy = ParamTy->getPointerElementType();
2218 if (PointeeTy->isStructTy() &&
2219 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2220 ParamTy = PointeeTy;
2221 }
2222 }
2223
David Netoc6f3ab22018-04-06 18:02:31 -04002224 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002225 }
2226
David Neto87846742018-04-11 17:36:22 -04002227 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002228 SPIRVInstList.push_back(Inst);
2229 break;
2230 }
2231 }
2232 }
2233
2234 // Generate OpTypeSampledImage.
2235 TypeMapType &OpImageTypeMap = getImageTypeMap();
2236 for (auto &ImageType : OpImageTypeMap) {
2237 //
2238 // Generate OpTypeSampledImage.
2239 //
2240 // Ops[0] = Image Type ID
2241 //
2242 SPIRVOperandList Ops;
2243
2244 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002245 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002246
2247 // Update OpImageTypeMap.
2248 ImageType.second = nextID;
2249
David Neto87846742018-04-11 17:36:22 -04002250 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002251 SPIRVInstList.push_back(Inst);
2252 }
David Netoc6f3ab22018-04-06 18:02:31 -04002253
2254 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002255 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2256 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002257 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002258
2259 // Generate the spec constant.
2260 SPIRVOperandList Ops;
2261 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002262 SPIRVInstList.push_back(
2263 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002264
2265 // Generate the array type.
2266 Ops.clear();
2267 // The element type must have been created.
2268 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2269 assert(elem_ty_id);
2270 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2271
2272 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002273 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002274
2275 Ops.clear();
2276 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002277 SPIRVInstList.push_back(new SPIRVInstruction(
2278 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002279 }
David Neto22f144c2017-06-12 14:26:21 -04002280}
2281
2282void SPIRVProducerPass::GenerateSPIRVConstants() {
2283 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2284 ValueMapType &VMap = getValueMap();
2285 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2286 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002287 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002288
2289 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002290 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002291 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002292
2293 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002294 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002295 continue;
2296 }
2297
David Netofb9a7972017-08-25 17:08:24 -04002298 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002299 VMap[Cst] = nextID;
2300
2301 //
2302 // Generate OpConstant.
2303 //
2304
2305 // Ops[0] = Result Type ID
2306 // Ops[1] .. Ops[n] = Values LiteralNumber
2307 SPIRVOperandList Ops;
2308
David Neto257c3892018-04-11 13:19:45 -04002309 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002310
2311 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002312 spv::Op Opcode = spv::OpNop;
2313
2314 if (isa<UndefValue>(Cst)) {
2315 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002316 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002317 if (hack_undef && IsTypeNullable(Cst->getType())) {
2318 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002319 }
David Neto22f144c2017-06-12 14:26:21 -04002320 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2321 unsigned BitWidth = CI->getBitWidth();
2322 if (BitWidth == 1) {
2323 // If the bitwidth of constant is 1, generate OpConstantTrue or
2324 // OpConstantFalse.
2325 if (CI->getZExtValue()) {
2326 // Ops[0] = Result Type ID
2327 Opcode = spv::OpConstantTrue;
2328 } else {
2329 // Ops[0] = Result Type ID
2330 Opcode = spv::OpConstantFalse;
2331 }
David Neto22f144c2017-06-12 14:26:21 -04002332 } else {
2333 auto V = CI->getZExtValue();
2334 LiteralNum.push_back(V & 0xFFFFFFFF);
2335
2336 if (BitWidth > 32) {
2337 LiteralNum.push_back(V >> 32);
2338 }
2339
2340 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002341
David Neto257c3892018-04-11 13:19:45 -04002342 Ops << MkInteger(LiteralNum);
2343
2344 if (BitWidth == 32 && V == 0) {
2345 constant_i32_zero_id_ = nextID;
2346 }
David Neto22f144c2017-06-12 14:26:21 -04002347 }
2348 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2349 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2350 Type *CFPTy = CFP->getType();
2351 if (CFPTy->isFloatTy()) {
2352 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2353 } else {
2354 CFPTy->print(errs());
2355 llvm_unreachable("Implement this ConstantFP Type");
2356 }
2357
2358 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002359
David Neto257c3892018-04-11 13:19:45 -04002360 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002361 } else if (isa<ConstantDataSequential>(Cst) &&
2362 cast<ConstantDataSequential>(Cst)->isString()) {
2363 Cst->print(errs());
2364 llvm_unreachable("Implement this Constant");
2365
2366 } else if (const ConstantDataSequential *CDS =
2367 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002368 // Let's convert <4 x i8> constant to int constant specially.
2369 // This case occurs when all the values are specified as constant
2370 // ints.
2371 Type *CstTy = Cst->getType();
2372 if (is4xi8vec(CstTy)) {
2373 LLVMContext &Context = CstTy->getContext();
2374
2375 //
2376 // Generate OpConstant with OpTypeInt 32 0.
2377 //
Neil Henning39672102017-09-29 14:33:13 +01002378 uint32_t IntValue = 0;
2379 for (unsigned k = 0; k < 4; k++) {
2380 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002381 IntValue = (IntValue << 8) | (Val & 0xffu);
2382 }
2383
2384 Type *i32 = Type::getInt32Ty(Context);
2385 Constant *CstInt = ConstantInt::get(i32, IntValue);
2386 // If this constant is already registered on VMap, use it.
2387 if (VMap.count(CstInt)) {
2388 uint32_t CstID = VMap[CstInt];
2389 VMap[Cst] = CstID;
2390 continue;
2391 }
2392
David Neto257c3892018-04-11 13:19:45 -04002393 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002394
David Neto87846742018-04-11 17:36:22 -04002395 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002396 SPIRVInstList.push_back(CstInst);
2397
2398 continue;
2399 }
2400
2401 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002402 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2403 Constant *EleCst = CDS->getElementAsConstant(k);
2404 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002405 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002406 }
2407
2408 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002409 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2410 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002411 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002412 Type *CstTy = Cst->getType();
2413 if (is4xi8vec(CstTy)) {
2414 LLVMContext &Context = CstTy->getContext();
2415
2416 //
2417 // Generate OpConstant with OpTypeInt 32 0.
2418 //
Neil Henning39672102017-09-29 14:33:13 +01002419 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002420 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2421 I != E; ++I) {
2422 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002423 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002424 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2425 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002426 }
David Neto49351ac2017-08-26 17:32:20 -04002427 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002428 }
2429
David Neto49351ac2017-08-26 17:32:20 -04002430 Type *i32 = Type::getInt32Ty(Context);
2431 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002432 // If this constant is already registered on VMap, use it.
2433 if (VMap.count(CstInt)) {
2434 uint32_t CstID = VMap[CstInt];
2435 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002436 continue;
David Neto22f144c2017-06-12 14:26:21 -04002437 }
2438
David Neto257c3892018-04-11 13:19:45 -04002439 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002440
David Neto87846742018-04-11 17:36:22 -04002441 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002442 SPIRVInstList.push_back(CstInst);
2443
David Neto19a1bad2017-08-25 15:01:41 -04002444 continue;
David Neto22f144c2017-06-12 14:26:21 -04002445 }
2446
2447 // We use a constant composite in SPIR-V for our constant aggregate in
2448 // LLVM.
2449 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002450
2451 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2452 // Look up the ID of the element of this aggregate (which we will
2453 // previously have created a constant for).
2454 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2455
2456 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002457 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002458 }
2459 } else if (Cst->isNullValue()) {
2460 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002461 } else {
2462 Cst->print(errs());
2463 llvm_unreachable("Unsupported Constant???");
2464 }
2465
David Neto87846742018-04-11 17:36:22 -04002466 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002467 SPIRVInstList.push_back(CstInst);
2468 }
2469}
2470
2471void SPIRVProducerPass::GenerateSamplers(Module &M) {
2472 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002473
alan-bakerb6b09dc2018-11-08 16:59:28 -05002474 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002475 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002476 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002477 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2478 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002479
David Neto862b7d82018-06-14 18:48:37 -04002480 // We might have samplers in the sampler map that are not used
2481 // in the translation unit. We need to allocate variables
2482 // for them and bindings too.
2483 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002484
alan-bakerb6b09dc2018-11-08 16:59:28 -05002485 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2486 if (!var_fn)
2487 return;
David Neto862b7d82018-06-14 18:48:37 -04002488 for (auto user : var_fn->users()) {
2489 // Populate SamplerLiteralToDescriptorSetMap and
2490 // SamplerLiteralToBindingMap.
2491 //
2492 // Look for calls like
2493 // call %opencl.sampler_t addrspace(2)*
2494 // @clspv.sampler.var.literal(
2495 // i32 descriptor,
2496 // i32 binding,
2497 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002498 if (auto *call = dyn_cast<CallInst>(user)) {
2499 const size_t index_into_sampler_map = static_cast<size_t>(
2500 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002501 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002502 errs() << "Out of bounds index to sampler map: "
2503 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002504 llvm_unreachable("bad sampler init: out of bounds");
2505 }
2506
2507 auto sampler_value = sampler_map[index_into_sampler_map].first;
2508 const auto descriptor_set = static_cast<unsigned>(
2509 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2510 const auto binding = static_cast<unsigned>(
2511 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2512
2513 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2514 SamplerLiteralToBindingMap[sampler_value] = binding;
2515 used_bindings.insert(binding);
2516 }
2517 }
2518
2519 unsigned index = 0;
2520 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002521 // Generate OpVariable.
2522 //
2523 // GIDOps[0] : Result Type ID
2524 // GIDOps[1] : Storage Class
2525 SPIRVOperandList Ops;
2526
David Neto257c3892018-04-11 13:19:45 -04002527 Ops << MkId(lookupType(SamplerTy))
2528 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002529
David Neto862b7d82018-06-14 18:48:37 -04002530 auto sampler_var_id = nextID++;
2531 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002532 SPIRVInstList.push_back(Inst);
2533
David Neto862b7d82018-06-14 18:48:37 -04002534 SamplerMapIndexToIDMap[index] = sampler_var_id;
2535 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002536
2537 // Find Insert Point for OpDecorate.
2538 auto DecoInsertPoint =
2539 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2540 [](SPIRVInstruction *Inst) -> bool {
2541 return Inst->getOpcode() != spv::OpDecorate &&
2542 Inst->getOpcode() != spv::OpMemberDecorate &&
2543 Inst->getOpcode() != spv::OpExtInstImport;
2544 });
2545
2546 // Ops[0] = Target ID
2547 // Ops[1] = Decoration (DescriptorSet)
2548 // Ops[2] = LiteralNumber according to Decoration
2549 Ops.clear();
2550
David Neto862b7d82018-06-14 18:48:37 -04002551 unsigned descriptor_set;
2552 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002553 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2554 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002555 // This sampler is not actually used. Find the next one.
2556 for (binding = 0; used_bindings.count(binding); binding++)
2557 ;
2558 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2559 used_bindings.insert(binding);
2560 } else {
2561 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2562 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2563 }
2564
2565 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2566 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002567
alan-bakerf5e5f692018-11-27 08:33:24 -05002568 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2569 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002570
David Neto87846742018-04-11 17:36:22 -04002571 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002572 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2573
2574 // Ops[0] = Target ID
2575 // Ops[1] = Decoration (Binding)
2576 // Ops[2] = LiteralNumber according to Decoration
2577 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002578 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2579 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002580
David Neto87846742018-04-11 17:36:22 -04002581 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002582 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002583
2584 index++;
David Neto22f144c2017-06-12 14:26:21 -04002585 }
David Neto862b7d82018-06-14 18:48:37 -04002586}
David Neto22f144c2017-06-12 14:26:21 -04002587
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002588void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002589 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2590 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002591
David Neto862b7d82018-06-14 18:48:37 -04002592 // Generate variables. Make one for each of resource var info object.
2593 for (auto *info : ModuleOrderedResourceVars) {
2594 Type *type = info->var_fn->getReturnType();
2595 // Remap the address space for opaque types.
2596 switch (info->arg_kind) {
2597 case clspv::ArgKind::Sampler:
2598 case clspv::ArgKind::ReadOnlyImage:
2599 case clspv::ArgKind::WriteOnlyImage:
2600 type = PointerType::get(type->getPointerElementType(),
2601 clspv::AddressSpace::UniformConstant);
2602 break;
2603 default:
2604 break;
2605 }
David Neto22f144c2017-06-12 14:26:21 -04002606
David Neto862b7d82018-06-14 18:48:37 -04002607 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002608
David Neto862b7d82018-06-14 18:48:37 -04002609 const auto type_id = lookupType(type);
2610 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2611 SPIRVOperandList Ops;
2612 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002613
David Neto862b7d82018-06-14 18:48:37 -04002614 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2615 SPIRVInstList.push_back(Inst);
2616
2617 // Map calls to the variable-builtin-function.
2618 for (auto &U : info->var_fn->uses()) {
2619 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2620 const auto set = unsigned(
2621 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2622 const auto binding = unsigned(
2623 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2624 if (set == info->descriptor_set && binding == info->binding) {
2625 switch (info->arg_kind) {
2626 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002627 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002628 case clspv::ArgKind::Pod:
2629 // The call maps to the variable directly.
2630 VMap[call] = info->var_id;
2631 break;
2632 case clspv::ArgKind::Sampler:
2633 case clspv::ArgKind::ReadOnlyImage:
2634 case clspv::ArgKind::WriteOnlyImage:
2635 // The call maps to a load we generate later.
2636 ResourceVarDeferredLoadCalls[call] = info->var_id;
2637 break;
2638 default:
2639 llvm_unreachable("Unhandled arg kind");
2640 }
2641 }
David Neto22f144c2017-06-12 14:26:21 -04002642 }
David Neto862b7d82018-06-14 18:48:37 -04002643 }
2644 }
David Neto22f144c2017-06-12 14:26:21 -04002645
David Neto862b7d82018-06-14 18:48:37 -04002646 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002647
David Neto862b7d82018-06-14 18:48:37 -04002648 // Find Insert Point for OpDecorate.
2649 auto DecoInsertPoint =
2650 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2651 [](SPIRVInstruction *Inst) -> bool {
2652 return Inst->getOpcode() != spv::OpDecorate &&
2653 Inst->getOpcode() != spv::OpMemberDecorate &&
2654 Inst->getOpcode() != spv::OpExtInstImport;
2655 });
2656
2657 SPIRVOperandList Ops;
2658 for (auto *info : ModuleOrderedResourceVars) {
2659 // Decorate with DescriptorSet and Binding.
2660 Ops.clear();
2661 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2662 << MkNum(info->descriptor_set);
2663 SPIRVInstList.insert(DecoInsertPoint,
2664 new SPIRVInstruction(spv::OpDecorate, Ops));
2665
2666 Ops.clear();
2667 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2668 << MkNum(info->binding);
2669 SPIRVInstList.insert(DecoInsertPoint,
2670 new SPIRVInstruction(spv::OpDecorate, Ops));
2671
2672 // Generate NonWritable and NonReadable
2673 switch (info->arg_kind) {
2674 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002675 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002676 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2677 clspv::AddressSpace::Constant) {
2678 Ops.clear();
2679 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2680 SPIRVInstList.insert(DecoInsertPoint,
2681 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002682 }
David Neto862b7d82018-06-14 18:48:37 -04002683 break;
2684 case clspv::ArgKind::ReadOnlyImage:
2685 Ops.clear();
2686 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2687 SPIRVInstList.insert(DecoInsertPoint,
2688 new SPIRVInstruction(spv::OpDecorate, Ops));
2689 break;
2690 case clspv::ArgKind::WriteOnlyImage:
2691 Ops.clear();
2692 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2693 SPIRVInstList.insert(DecoInsertPoint,
2694 new SPIRVInstruction(spv::OpDecorate, Ops));
2695 break;
2696 default:
2697 break;
David Neto22f144c2017-06-12 14:26:21 -04002698 }
2699 }
2700}
2701
2702void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002703 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002704 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2705 ValueMapType &VMap = getValueMap();
2706 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002707 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002708
2709 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2710 Type *Ty = GV.getType();
2711 PointerType *PTy = cast<PointerType>(Ty);
2712
2713 uint32_t InitializerID = 0;
2714
2715 // Workgroup size is handled differently (it goes into a constant)
2716 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2717 std::vector<bool> HasMDVec;
2718 uint32_t PrevXDimCst = 0xFFFFFFFF;
2719 uint32_t PrevYDimCst = 0xFFFFFFFF;
2720 uint32_t PrevZDimCst = 0xFFFFFFFF;
2721 for (Function &Func : *GV.getParent()) {
2722 if (Func.isDeclaration()) {
2723 continue;
2724 }
2725
2726 // We only need to check kernels.
2727 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2728 continue;
2729 }
2730
2731 if (const MDNode *MD =
2732 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2733 uint32_t CurXDimCst = static_cast<uint32_t>(
2734 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2735 uint32_t CurYDimCst = static_cast<uint32_t>(
2736 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2737 uint32_t CurZDimCst = static_cast<uint32_t>(
2738 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2739
2740 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2741 PrevZDimCst == 0xFFFFFFFF) {
2742 PrevXDimCst = CurXDimCst;
2743 PrevYDimCst = CurYDimCst;
2744 PrevZDimCst = CurZDimCst;
2745 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2746 CurZDimCst != PrevZDimCst) {
2747 llvm_unreachable(
2748 "reqd_work_group_size must be the same across all kernels");
2749 } else {
2750 continue;
2751 }
2752
2753 //
2754 // Generate OpConstantComposite.
2755 //
2756 // Ops[0] : Result Type ID
2757 // Ops[1] : Constant size for x dimension.
2758 // Ops[2] : Constant size for y dimension.
2759 // Ops[3] : Constant size for z dimension.
2760 SPIRVOperandList Ops;
2761
2762 uint32_t XDimCstID =
2763 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2764 uint32_t YDimCstID =
2765 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2766 uint32_t ZDimCstID =
2767 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2768
2769 InitializerID = nextID;
2770
David Neto257c3892018-04-11 13:19:45 -04002771 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2772 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002773
David Neto87846742018-04-11 17:36:22 -04002774 auto *Inst =
2775 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002776 SPIRVInstList.push_back(Inst);
2777
2778 HasMDVec.push_back(true);
2779 } else {
2780 HasMDVec.push_back(false);
2781 }
2782 }
2783
2784 // Check all kernels have same definitions for work_group_size.
2785 bool HasMD = false;
2786 if (!HasMDVec.empty()) {
2787 HasMD = HasMDVec[0];
2788 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2789 if (HasMD != HasMDVec[i]) {
2790 llvm_unreachable(
2791 "Kernels should have consistent work group size definition");
2792 }
2793 }
2794 }
2795
2796 // If all kernels do not have metadata for reqd_work_group_size, generate
2797 // OpSpecConstants for x/y/z dimension.
2798 if (!HasMD) {
2799 //
2800 // Generate OpSpecConstants for x/y/z dimension.
2801 //
2802 // Ops[0] : Result Type ID
2803 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2804 uint32_t XDimCstID = 0;
2805 uint32_t YDimCstID = 0;
2806 uint32_t ZDimCstID = 0;
2807
David Neto22f144c2017-06-12 14:26:21 -04002808 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002809 uint32_t result_type_id =
2810 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002811
David Neto257c3892018-04-11 13:19:45 -04002812 // X Dimension
2813 Ops << MkId(result_type_id) << MkNum(1);
2814 XDimCstID = nextID++;
2815 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002816 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002817
2818 // Y Dimension
2819 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002820 Ops << MkId(result_type_id) << MkNum(1);
2821 YDimCstID = nextID++;
2822 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002823 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002824
2825 // Z Dimension
2826 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002827 Ops << MkId(result_type_id) << MkNum(1);
2828 ZDimCstID = nextID++;
2829 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002830 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002831
David Neto257c3892018-04-11 13:19:45 -04002832 BuiltinDimVec.push_back(XDimCstID);
2833 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002834 BuiltinDimVec.push_back(ZDimCstID);
2835
David Neto22f144c2017-06-12 14:26:21 -04002836 //
2837 // Generate OpSpecConstantComposite.
2838 //
2839 // Ops[0] : Result Type ID
2840 // Ops[1] : Constant size for x dimension.
2841 // Ops[2] : Constant size for y dimension.
2842 // Ops[3] : Constant size for z dimension.
2843 InitializerID = nextID;
2844
2845 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002846 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2847 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002848
David Neto87846742018-04-11 17:36:22 -04002849 auto *Inst =
2850 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002851 SPIRVInstList.push_back(Inst);
2852 }
2853 }
2854
David Neto22f144c2017-06-12 14:26:21 -04002855 VMap[&GV] = nextID;
2856
2857 //
2858 // Generate OpVariable.
2859 //
2860 // GIDOps[0] : Result Type ID
2861 // GIDOps[1] : Storage Class
2862 SPIRVOperandList Ops;
2863
David Neto85082642018-03-24 06:55:20 -07002864 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002865 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002866
David Neto85082642018-03-24 06:55:20 -07002867 if (GV.hasInitializer()) {
2868 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002869 }
2870
David Neto85082642018-03-24 06:55:20 -07002871 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002872 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002873 clspv::Option::ModuleConstantsInStorageBuffer();
2874
2875 if (0 != InitializerID) {
2876 if (!module_scope_constant_external_init) {
2877 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002878 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002879 }
2880 }
2881 const uint32_t var_id = nextID++;
2882
David Neto87846742018-04-11 17:36:22 -04002883 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002884 SPIRVInstList.push_back(Inst);
2885
2886 // If we have a builtin.
2887 if (spv::BuiltInMax != BuiltinType) {
2888 // Find Insert Point for OpDecorate.
2889 auto DecoInsertPoint =
2890 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2891 [](SPIRVInstruction *Inst) -> bool {
2892 return Inst->getOpcode() != spv::OpDecorate &&
2893 Inst->getOpcode() != spv::OpMemberDecorate &&
2894 Inst->getOpcode() != spv::OpExtInstImport;
2895 });
2896 //
2897 // Generate OpDecorate.
2898 //
2899 // DOps[0] = Target ID
2900 // DOps[1] = Decoration (Builtin)
2901 // DOps[2] = BuiltIn ID
2902 uint32_t ResultID;
2903
2904 // WorkgroupSize is different, we decorate the constant composite that has
2905 // its value, rather than the variable that we use to access the value.
2906 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2907 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002908 // Save both the value and variable IDs for later.
2909 WorkgroupSizeValueID = InitializerID;
2910 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002911 } else {
2912 ResultID = VMap[&GV];
2913 }
2914
2915 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002916 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2917 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002918
David Neto87846742018-04-11 17:36:22 -04002919 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002920 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002921 } else if (module_scope_constant_external_init) {
2922 // This module scope constant is initialized from a storage buffer with data
2923 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002924 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002925
David Neto862b7d82018-06-14 18:48:37 -04002926 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002927 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2928 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002929 std::string hexbytes;
2930 llvm::raw_string_ostream str(hexbytes);
2931 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2932 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2933 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002934
2935 // Find Insert Point for OpDecorate.
2936 auto DecoInsertPoint =
2937 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2938 [](SPIRVInstruction *Inst) -> bool {
2939 return Inst->getOpcode() != spv::OpDecorate &&
2940 Inst->getOpcode() != spv::OpMemberDecorate &&
2941 Inst->getOpcode() != spv::OpExtInstImport;
2942 });
2943
David Neto257c3892018-04-11 13:19:45 -04002944 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002945 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002946 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2947 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002948 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002949
2950 // OpDecorate %var DescriptorSet <descriptor_set>
2951 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002952 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2953 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002954 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002955 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002956 }
2957}
2958
David Netoc6f3ab22018-04-06 18:02:31 -04002959void SPIRVProducerPass::GenerateWorkgroupVars() {
2960 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002961 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2962 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002963 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002964
2965 // Generate OpVariable.
2966 //
2967 // GIDOps[0] : Result Type ID
2968 // GIDOps[1] : Storage Class
2969 SPIRVOperandList Ops;
2970 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2971
2972 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002973 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002974 }
2975}
2976
David Neto862b7d82018-06-14 18:48:37 -04002977void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2978 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002979 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2980 return;
2981 }
David Neto862b7d82018-06-14 18:48:37 -04002982 // Gather the list of resources that are used by this function's arguments.
2983 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2984
alan-bakerf5e5f692018-11-27 08:33:24 -05002985 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2986 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002987 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002988 std::string kind =
2989 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2990 ? "pod_ubo"
2991 : argKind;
2992 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002993 };
2994
2995 auto *fty = F.getType()->getPointerElementType();
2996 auto *func_ty = dyn_cast<FunctionType>(fty);
2997
2998 // If we've clustereed POD arguments, then argument details are in metadata.
2999 // If an argument maps to a resource variable, then get descriptor set and
3000 // binding from the resoure variable. Other info comes from the metadata.
3001 const auto *arg_map = F.getMetadata("kernel_arg_map");
3002 if (arg_map) {
3003 for (const auto &arg : arg_map->operands()) {
3004 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003005 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003006 const auto name =
3007 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3008 const auto old_index =
3009 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3010 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003011 const size_t new_index = static_cast<size_t>(
3012 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003013 const auto offset =
3014 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003015 const auto arg_size =
3016 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003017 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003018 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003019 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003020 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003021
3022 uint32_t descriptor_set = 0;
3023 uint32_t binding = 0;
3024 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3025 F.getName(),
3026 name,
3027 static_cast<uint32_t>(old_index),
3028 argKind,
3029 static_cast<uint32_t>(spec_id),
3030 // This will be set below for pointer-to-local args.
3031 0,
3032 static_cast<uint32_t>(offset),
3033 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003034 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003035 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3036 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3037 DL));
David Neto862b7d82018-06-14 18:48:37 -04003038 } else {
3039 auto *info = resource_var_at_index[new_index];
3040 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003041 descriptor_set = info->descriptor_set;
3042 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003043 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003044 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003045 }
3046 } else {
3047 // There is no argument map.
3048 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003049 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003050
3051 SmallVector<Argument *, 4> arguments;
3052 for (auto &arg : F.args()) {
3053 arguments.push_back(&arg);
3054 }
3055
3056 unsigned arg_index = 0;
3057 for (auto *info : resource_var_at_index) {
3058 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003059 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003060 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003061 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003062 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003063 }
3064
alan-bakerf5e5f692018-11-27 08:33:24 -05003065 // Local pointer arguments are unused in this case. Offset is always zero.
3066 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3067 F.getName(), arg->getName(),
3068 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3069 0, 0,
3070 0, arg_size};
3071 descriptorMapEntries->emplace_back(std::move(kernel_data),
3072 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003073 }
3074 arg_index++;
3075 }
3076 // Generate mappings for pointer-to-local arguments.
3077 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3078 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003079 auto where = LocalArgSpecIds.find(arg);
3080 if (where != LocalArgSpecIds.end()) {
3081 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003082 // Pod arguments members are unused in this case.
3083 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3084 F.getName(),
3085 arg->getName(),
3086 arg_index,
3087 ArgKind::Local,
3088 static_cast<uint32_t>(local_arg_info.spec_id),
3089 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3090 0,
3091 0};
3092 // Pointer-to-local arguments do not utilize descriptor set and binding.
3093 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003094 }
3095 }
3096 }
3097}
3098
David Neto22f144c2017-06-12 14:26:21 -04003099void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3100 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3101 ValueMapType &VMap = getValueMap();
3102 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003103 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3104 auto &GlobalConstArgSet = getGlobalConstArgSet();
3105
3106 FunctionType *FTy = F.getFunctionType();
3107
3108 //
David Neto22f144c2017-06-12 14:26:21 -04003109 // Generate OPFunction.
3110 //
3111
3112 // FOps[0] : Result Type ID
3113 // FOps[1] : Function Control
3114 // FOps[2] : Function Type ID
3115 SPIRVOperandList FOps;
3116
3117 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003118 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003119
3120 // Check function attributes for SPIRV Function Control.
3121 uint32_t FuncControl = spv::FunctionControlMaskNone;
3122 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3123 FuncControl |= spv::FunctionControlInlineMask;
3124 }
3125 if (F.hasFnAttribute(Attribute::NoInline)) {
3126 FuncControl |= spv::FunctionControlDontInlineMask;
3127 }
3128 // TODO: Check llvm attribute for Function Control Pure.
3129 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3130 FuncControl |= spv::FunctionControlPureMask;
3131 }
3132 // TODO: Check llvm attribute for Function Control Const.
3133 if (F.hasFnAttribute(Attribute::ReadNone)) {
3134 FuncControl |= spv::FunctionControlConstMask;
3135 }
3136
David Neto257c3892018-04-11 13:19:45 -04003137 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003138
3139 uint32_t FTyID;
3140 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3141 SmallVector<Type *, 4> NewFuncParamTys;
3142 FunctionType *NewFTy =
3143 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3144 FTyID = lookupType(NewFTy);
3145 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003146 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003147 if (GlobalConstFuncTyMap.count(FTy)) {
3148 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3149 } else {
3150 FTyID = lookupType(FTy);
3151 }
3152 }
3153
David Neto257c3892018-04-11 13:19:45 -04003154 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003155
3156 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3157 EntryPoints.push_back(std::make_pair(&F, nextID));
3158 }
3159
3160 VMap[&F] = nextID;
3161
David Neto482550a2018-03-24 05:21:07 -07003162 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003163 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3164 }
David Neto22f144c2017-06-12 14:26:21 -04003165 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003166 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003167 SPIRVInstList.push_back(FuncInst);
3168
3169 //
3170 // Generate OpFunctionParameter for Normal function.
3171 //
3172
3173 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3174 // Iterate Argument for name instead of param type from function type.
3175 unsigned ArgIdx = 0;
3176 for (Argument &Arg : F.args()) {
3177 VMap[&Arg] = nextID;
3178
3179 // ParamOps[0] : Result Type ID
3180 SPIRVOperandList ParamOps;
3181
3182 // Find SPIRV instruction for parameter type.
3183 uint32_t ParamTyID = lookupType(Arg.getType());
3184 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3185 if (GlobalConstFuncTyMap.count(FTy)) {
3186 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3187 Type *EleTy = PTy->getPointerElementType();
3188 Type *ArgTy =
3189 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3190 ParamTyID = lookupType(ArgTy);
3191 GlobalConstArgSet.insert(&Arg);
3192 }
3193 }
3194 }
David Neto257c3892018-04-11 13:19:45 -04003195 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003196
3197 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003198 auto *ParamInst =
3199 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003200 SPIRVInstList.push_back(ParamInst);
3201
3202 ArgIdx++;
3203 }
3204 }
3205}
3206
alan-bakerb6b09dc2018-11-08 16:59:28 -05003207void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003208 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3209 EntryPointVecType &EntryPoints = getEntryPointVec();
3210 ValueMapType &VMap = getValueMap();
3211 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3212 uint32_t &ExtInstImportID = getOpExtInstImportID();
3213 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3214
3215 // Set up insert point.
3216 auto InsertPoint = SPIRVInstList.begin();
3217
3218 //
3219 // Generate OpCapability
3220 //
3221 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3222
3223 // Ops[0] = Capability
3224 SPIRVOperandList Ops;
3225
David Neto87846742018-04-11 17:36:22 -04003226 auto *CapInst =
3227 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003228 SPIRVInstList.insert(InsertPoint, CapInst);
3229
3230 for (Type *Ty : getTypeList()) {
3231 // Find the i16 type.
3232 if (Ty->isIntegerTy(16)) {
3233 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003234 SPIRVInstList.insert(InsertPoint,
3235 new SPIRVInstruction(spv::OpCapability,
3236 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003237 } else if (Ty->isIntegerTy(64)) {
3238 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003239 SPIRVInstList.insert(InsertPoint,
3240 new SPIRVInstruction(spv::OpCapability,
3241 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003242 } else if (Ty->isHalfTy()) {
3243 // Generate OpCapability for half type.
3244 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003245 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3246 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003247 } else if (Ty->isDoubleTy()) {
3248 // Generate OpCapability for double type.
3249 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003250 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3251 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003252 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3253 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003254 if (STy->getName().equals("opencl.image2d_wo_t") ||
3255 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003256 // Generate OpCapability for write only image type.
3257 SPIRVInstList.insert(
3258 InsertPoint,
3259 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003260 spv::OpCapability,
3261 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003262 }
3263 }
3264 }
3265 }
3266
David Neto5c22a252018-03-15 16:07:41 -04003267 { // OpCapability ImageQuery
3268 bool hasImageQuery = false;
3269 for (const char *imageQuery : {
3270 "_Z15get_image_width14ocl_image2d_ro",
3271 "_Z15get_image_width14ocl_image2d_wo",
3272 "_Z16get_image_height14ocl_image2d_ro",
3273 "_Z16get_image_height14ocl_image2d_wo",
3274 }) {
3275 if (module.getFunction(imageQuery)) {
3276 hasImageQuery = true;
3277 break;
3278 }
3279 }
3280 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003281 auto *ImageQueryCapInst = new SPIRVInstruction(
3282 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003283 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3284 }
3285 }
3286
David Neto22f144c2017-06-12 14:26:21 -04003287 if (hasVariablePointers()) {
3288 //
3289 // Generate OpCapability and OpExtension
3290 //
3291
3292 //
3293 // Generate OpCapability.
3294 //
3295 // Ops[0] = Capability
3296 //
3297 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003298 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003299
David Neto87846742018-04-11 17:36:22 -04003300 SPIRVInstList.insert(InsertPoint,
3301 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003302
3303 //
3304 // Generate OpExtension.
3305 //
3306 // Ops[0] = Name (Literal String)
3307 //
David Netoa772fd12017-08-04 14:17:33 -04003308 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3309 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003310
David Neto87846742018-04-11 17:36:22 -04003311 auto *ExtensionInst =
3312 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003313 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003314 }
David Neto22f144c2017-06-12 14:26:21 -04003315 }
3316
3317 if (ExtInstImportID) {
3318 ++InsertPoint;
3319 }
3320
3321 //
3322 // Generate OpMemoryModel
3323 //
3324 // Memory model for Vulkan will always be GLSL450.
3325
3326 // Ops[0] = Addressing Model
3327 // Ops[1] = Memory Model
3328 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003329 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003330
David Neto87846742018-04-11 17:36:22 -04003331 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003332 SPIRVInstList.insert(InsertPoint, MemModelInst);
3333
3334 //
3335 // Generate OpEntryPoint
3336 //
3337 for (auto EntryPoint : EntryPoints) {
3338 // Ops[0] = Execution Model
3339 // Ops[1] = EntryPoint ID
3340 // Ops[2] = Name (Literal String)
3341 // ...
3342 //
3343 // TODO: Do we need to consider Interface ID for forward references???
3344 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003345 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003346 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3347 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003348
David Neto22f144c2017-06-12 14:26:21 -04003349 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003350 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003351 }
3352
David Neto87846742018-04-11 17:36:22 -04003353 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003354 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3355 }
3356
3357 for (auto EntryPoint : EntryPoints) {
3358 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3359 ->getMetadata("reqd_work_group_size")) {
3360
3361 if (!BuiltinDimVec.empty()) {
3362 llvm_unreachable(
3363 "Kernels should have consistent work group size definition");
3364 }
3365
3366 //
3367 // Generate OpExecutionMode
3368 //
3369
3370 // Ops[0] = Entry Point ID
3371 // Ops[1] = Execution Mode
3372 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3373 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003374 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003375
3376 uint32_t XDim = static_cast<uint32_t>(
3377 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3378 uint32_t YDim = static_cast<uint32_t>(
3379 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3380 uint32_t ZDim = static_cast<uint32_t>(
3381 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3382
David Neto257c3892018-04-11 13:19:45 -04003383 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003384
David Neto87846742018-04-11 17:36:22 -04003385 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003386 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3387 }
3388 }
3389
3390 //
3391 // Generate OpSource.
3392 //
3393 // Ops[0] = SourceLanguage ID
3394 // Ops[1] = Version (LiteralNum)
3395 //
3396 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003397 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003398
David Neto87846742018-04-11 17:36:22 -04003399 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003400 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3401
3402 if (!BuiltinDimVec.empty()) {
3403 //
3404 // Generate OpDecorates for x/y/z dimension.
3405 //
3406 // Ops[0] = Target ID
3407 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003408 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003409
3410 // X Dimension
3411 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003412 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003413 SPIRVInstList.insert(InsertPoint,
3414 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003415
3416 // Y Dimension
3417 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003418 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003419 SPIRVInstList.insert(InsertPoint,
3420 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003421
3422 // Z Dimension
3423 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003424 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003425 SPIRVInstList.insert(InsertPoint,
3426 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003427 }
3428}
3429
David Netob6e2e062018-04-25 10:32:06 -04003430void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3431 // Work around a driver bug. Initializers on Private variables might not
3432 // work. So the start of the kernel should store the initializer value to the
3433 // variables. Yes, *every* entry point pays this cost if *any* entry point
3434 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3435 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003436 // TODO(dneto): Remove this at some point once fixed drivers are widely
3437 // available.
David Netob6e2e062018-04-25 10:32:06 -04003438 if (WorkgroupSizeVarID) {
3439 assert(WorkgroupSizeValueID);
3440
3441 SPIRVOperandList Ops;
3442 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3443
3444 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3445 getSPIRVInstList().push_back(Inst);
3446 }
3447}
3448
David Neto22f144c2017-06-12 14:26:21 -04003449void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3450 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3451 ValueMapType &VMap = getValueMap();
3452
David Netob6e2e062018-04-25 10:32:06 -04003453 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003454
3455 for (BasicBlock &BB : F) {
3456 // Register BasicBlock to ValueMap.
3457 VMap[&BB] = nextID;
3458
3459 //
3460 // Generate OpLabel for Basic Block.
3461 //
3462 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003463 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003464 SPIRVInstList.push_back(Inst);
3465
David Neto6dcd4712017-06-23 11:06:47 -04003466 // OpVariable instructions must come first.
3467 for (Instruction &I : BB) {
3468 if (isa<AllocaInst>(I)) {
3469 GenerateInstruction(I);
3470 }
3471 }
3472
David Neto22f144c2017-06-12 14:26:21 -04003473 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003474 if (clspv::Option::HackInitializers()) {
3475 GenerateEntryPointInitialStores();
3476 }
David Neto22f144c2017-06-12 14:26:21 -04003477 }
3478
3479 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003480 if (!isa<AllocaInst>(I)) {
3481 GenerateInstruction(I);
3482 }
David Neto22f144c2017-06-12 14:26:21 -04003483 }
3484 }
3485}
3486
3487spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3488 const std::map<CmpInst::Predicate, spv::Op> Map = {
3489 {CmpInst::ICMP_EQ, spv::OpIEqual},
3490 {CmpInst::ICMP_NE, spv::OpINotEqual},
3491 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3492 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3493 {CmpInst::ICMP_ULT, spv::OpULessThan},
3494 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3495 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3496 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3497 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3498 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3499 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3500 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3501 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3502 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3503 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3504 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3505 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3506 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3507 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3508 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3509 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3510 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3511
3512 assert(0 != Map.count(I->getPredicate()));
3513
3514 return Map.at(I->getPredicate());
3515}
3516
3517spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3518 const std::map<unsigned, spv::Op> Map{
3519 {Instruction::Trunc, spv::OpUConvert},
3520 {Instruction::ZExt, spv::OpUConvert},
3521 {Instruction::SExt, spv::OpSConvert},
3522 {Instruction::FPToUI, spv::OpConvertFToU},
3523 {Instruction::FPToSI, spv::OpConvertFToS},
3524 {Instruction::UIToFP, spv::OpConvertUToF},
3525 {Instruction::SIToFP, spv::OpConvertSToF},
3526 {Instruction::FPTrunc, spv::OpFConvert},
3527 {Instruction::FPExt, spv::OpFConvert},
3528 {Instruction::BitCast, spv::OpBitcast}};
3529
3530 assert(0 != Map.count(I.getOpcode()));
3531
3532 return Map.at(I.getOpcode());
3533}
3534
3535spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003536 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003537 switch (I.getOpcode()) {
3538 default:
3539 break;
3540 case Instruction::Or:
3541 return spv::OpLogicalOr;
3542 case Instruction::And:
3543 return spv::OpLogicalAnd;
3544 case Instruction::Xor:
3545 return spv::OpLogicalNotEqual;
3546 }
3547 }
3548
alan-bakerb6b09dc2018-11-08 16:59:28 -05003549 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003550 {Instruction::Add, spv::OpIAdd},
3551 {Instruction::FAdd, spv::OpFAdd},
3552 {Instruction::Sub, spv::OpISub},
3553 {Instruction::FSub, spv::OpFSub},
3554 {Instruction::Mul, spv::OpIMul},
3555 {Instruction::FMul, spv::OpFMul},
3556 {Instruction::UDiv, spv::OpUDiv},
3557 {Instruction::SDiv, spv::OpSDiv},
3558 {Instruction::FDiv, spv::OpFDiv},
3559 {Instruction::URem, spv::OpUMod},
3560 {Instruction::SRem, spv::OpSRem},
3561 {Instruction::FRem, spv::OpFRem},
3562 {Instruction::Or, spv::OpBitwiseOr},
3563 {Instruction::Xor, spv::OpBitwiseXor},
3564 {Instruction::And, spv::OpBitwiseAnd},
3565 {Instruction::Shl, spv::OpShiftLeftLogical},
3566 {Instruction::LShr, spv::OpShiftRightLogical},
3567 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3568
3569 assert(0 != Map.count(I.getOpcode()));
3570
3571 return Map.at(I.getOpcode());
3572}
3573
3574void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3575 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3576 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003577 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3578 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3579
3580 // Register Instruction to ValueMap.
3581 if (0 == VMap[&I]) {
3582 VMap[&I] = nextID;
3583 }
3584
3585 switch (I.getOpcode()) {
3586 default: {
3587 if (Instruction::isCast(I.getOpcode())) {
3588 //
3589 // Generate SPIRV instructions for cast operators.
3590 //
3591
David Netod2de94a2017-08-28 17:27:47 -04003592 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003593 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003594 auto toI8 = Ty == Type::getInt8Ty(Context);
3595 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003596 // Handle zext, sext and uitofp with i1 type specially.
3597 if ((I.getOpcode() == Instruction::ZExt ||
3598 I.getOpcode() == Instruction::SExt ||
3599 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003600 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003601 //
3602 // Generate OpSelect.
3603 //
3604
3605 // Ops[0] = Result Type ID
3606 // Ops[1] = Condition ID
3607 // Ops[2] = True Constant ID
3608 // Ops[3] = False Constant ID
3609 SPIRVOperandList Ops;
3610
David Neto257c3892018-04-11 13:19:45 -04003611 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003612
David Neto22f144c2017-06-12 14:26:21 -04003613 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003614 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003615
3616 uint32_t TrueID = 0;
3617 if (I.getOpcode() == Instruction::ZExt) {
3618 APInt One(32, 1);
3619 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3620 } else if (I.getOpcode() == Instruction::SExt) {
3621 APInt MinusOne(32, UINT64_MAX, true);
3622 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3623 } else {
3624 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3625 }
David Neto257c3892018-04-11 13:19:45 -04003626 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003627
3628 uint32_t FalseID = 0;
3629 if (I.getOpcode() == Instruction::ZExt) {
3630 FalseID = VMap[Constant::getNullValue(I.getType())];
3631 } else if (I.getOpcode() == Instruction::SExt) {
3632 FalseID = VMap[Constant::getNullValue(I.getType())];
3633 } else {
3634 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3635 }
David Neto257c3892018-04-11 13:19:45 -04003636 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003637
David Neto87846742018-04-11 17:36:22 -04003638 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003639 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003640 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3641 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3642 // 8 bits.
3643 // Before:
3644 // %result = trunc i32 %a to i8
3645 // After
3646 // %result = OpBitwiseAnd %uint %a %uint_255
3647
3648 SPIRVOperandList Ops;
3649
David Neto257c3892018-04-11 13:19:45 -04003650 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003651
3652 Type *UintTy = Type::getInt32Ty(Context);
3653 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003654 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003655
David Neto87846742018-04-11 17:36:22 -04003656 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003657 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003658 } else {
3659 // Ops[0] = Result Type ID
3660 // Ops[1] = Source Value ID
3661 SPIRVOperandList Ops;
3662
David Neto257c3892018-04-11 13:19:45 -04003663 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003664
David Neto87846742018-04-11 17:36:22 -04003665 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003666 SPIRVInstList.push_back(Inst);
3667 }
3668 } else if (isa<BinaryOperator>(I)) {
3669 //
3670 // Generate SPIRV instructions for binary operators.
3671 //
3672
3673 // Handle xor with i1 type specially.
3674 if (I.getOpcode() == Instruction::Xor &&
3675 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003676 ((isa<ConstantInt>(I.getOperand(0)) &&
3677 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3678 (isa<ConstantInt>(I.getOperand(1)) &&
3679 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003680 //
3681 // Generate OpLogicalNot.
3682 //
3683 // Ops[0] = Result Type ID
3684 // Ops[1] = Operand
3685 SPIRVOperandList Ops;
3686
David Neto257c3892018-04-11 13:19:45 -04003687 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003688
3689 Value *CondV = I.getOperand(0);
3690 if (isa<Constant>(I.getOperand(0))) {
3691 CondV = I.getOperand(1);
3692 }
David Neto257c3892018-04-11 13:19:45 -04003693 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003694
David Neto87846742018-04-11 17:36:22 -04003695 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003696 SPIRVInstList.push_back(Inst);
3697 } else {
3698 // Ops[0] = Result Type ID
3699 // Ops[1] = Operand 0
3700 // Ops[2] = Operand 1
3701 SPIRVOperandList Ops;
3702
David Neto257c3892018-04-11 13:19:45 -04003703 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3704 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003705
David Neto87846742018-04-11 17:36:22 -04003706 auto *Inst =
3707 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003708 SPIRVInstList.push_back(Inst);
3709 }
3710 } else {
3711 I.print(errs());
3712 llvm_unreachable("Unsupported instruction???");
3713 }
3714 break;
3715 }
3716 case Instruction::GetElementPtr: {
3717 auto &GlobalConstArgSet = getGlobalConstArgSet();
3718
3719 //
3720 // Generate OpAccessChain.
3721 //
3722 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3723
3724 //
3725 // Generate OpAccessChain.
3726 //
3727
3728 // Ops[0] = Result Type ID
3729 // Ops[1] = Base ID
3730 // Ops[2] ... Ops[n] = Indexes ID
3731 SPIRVOperandList Ops;
3732
alan-bakerb6b09dc2018-11-08 16:59:28 -05003733 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003734 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3735 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3736 // Use pointer type with private address space for global constant.
3737 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003738 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003739 }
David Neto257c3892018-04-11 13:19:45 -04003740
3741 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003742
David Neto862b7d82018-06-14 18:48:37 -04003743 // Generate the base pointer.
3744 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003745
David Neto862b7d82018-06-14 18:48:37 -04003746 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003747
3748 //
3749 // Follows below rules for gep.
3750 //
David Neto862b7d82018-06-14 18:48:37 -04003751 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3752 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003753 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3754 // first index.
3755 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3756 // use gep's first index.
3757 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3758 // gep's first index.
3759 //
3760 spv::Op Opcode = spv::OpAccessChain;
3761 unsigned offset = 0;
3762 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003763 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003764 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003765 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003766 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003767 }
David Neto862b7d82018-06-14 18:48:37 -04003768 } else {
David Neto22f144c2017-06-12 14:26:21 -04003769 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003770 }
3771
3772 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003773 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003774 // Do we need to generate ArrayStride? Check against the GEP result type
3775 // rather than the pointer type of the base because when indexing into
3776 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3777 // for something else in the SPIR-V.
3778 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
Alan Bakerfcda9482018-10-02 17:09:59 -04003779 switch (GetStorageClass(ResultType->getAddressSpace())) {
3780 case spv::StorageClassStorageBuffer:
3781 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003782 // Save the need to generate an ArrayStride decoration. But defer
3783 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003784 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003785 break;
3786 default:
3787 break;
David Neto1a1a0582017-07-07 12:01:44 -04003788 }
David Neto22f144c2017-06-12 14:26:21 -04003789 }
3790
3791 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003792 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003793 }
3794
David Neto87846742018-04-11 17:36:22 -04003795 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003796 SPIRVInstList.push_back(Inst);
3797 break;
3798 }
3799 case Instruction::ExtractValue: {
3800 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3801 // Ops[0] = Result Type ID
3802 // Ops[1] = Composite ID
3803 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3804 SPIRVOperandList Ops;
3805
David Neto257c3892018-04-11 13:19:45 -04003806 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003807
3808 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003809 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003810
3811 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003812 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003813 }
3814
David Neto87846742018-04-11 17:36:22 -04003815 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003816 SPIRVInstList.push_back(Inst);
3817 break;
3818 }
3819 case Instruction::InsertValue: {
3820 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3821 // Ops[0] = Result Type ID
3822 // Ops[1] = Object ID
3823 // Ops[2] = Composite ID
3824 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3825 SPIRVOperandList Ops;
3826
3827 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003828 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003829
3830 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003831 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003832
3833 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003834 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003835
3836 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003837 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003838 }
3839
David Neto87846742018-04-11 17:36:22 -04003840 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003841 SPIRVInstList.push_back(Inst);
3842 break;
3843 }
3844 case Instruction::Select: {
3845 //
3846 // Generate OpSelect.
3847 //
3848
3849 // Ops[0] = Result Type ID
3850 // Ops[1] = Condition ID
3851 // Ops[2] = True Constant ID
3852 // Ops[3] = False Constant ID
3853 SPIRVOperandList Ops;
3854
3855 // Find SPIRV instruction for parameter type.
3856 auto Ty = I.getType();
3857 if (Ty->isPointerTy()) {
3858 auto PointeeTy = Ty->getPointerElementType();
3859 if (PointeeTy->isStructTy() &&
3860 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3861 Ty = PointeeTy;
3862 }
3863 }
3864
David Neto257c3892018-04-11 13:19:45 -04003865 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3866 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003867
David Neto87846742018-04-11 17:36:22 -04003868 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003869 SPIRVInstList.push_back(Inst);
3870 break;
3871 }
3872 case Instruction::ExtractElement: {
3873 // Handle <4 x i8> type manually.
3874 Type *CompositeTy = I.getOperand(0)->getType();
3875 if (is4xi8vec(CompositeTy)) {
3876 //
3877 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3878 // <4 x i8>.
3879 //
3880
3881 //
3882 // Generate OpShiftRightLogical
3883 //
3884 // Ops[0] = Result Type ID
3885 // Ops[1] = Operand 0
3886 // Ops[2] = Operand 1
3887 //
3888 SPIRVOperandList Ops;
3889
David Neto257c3892018-04-11 13:19:45 -04003890 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003891
3892 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003893 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003894
3895 uint32_t Op1ID = 0;
3896 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3897 // Handle constant index.
3898 uint64_t Idx = CI->getZExtValue();
3899 Value *ShiftAmount =
3900 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3901 Op1ID = VMap[ShiftAmount];
3902 } else {
3903 // Handle variable index.
3904 SPIRVOperandList TmpOps;
3905
David Neto257c3892018-04-11 13:19:45 -04003906 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3907 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003908
3909 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003910 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003911
3912 Op1ID = nextID;
3913
David Neto87846742018-04-11 17:36:22 -04003914 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003915 SPIRVInstList.push_back(TmpInst);
3916 }
David Neto257c3892018-04-11 13:19:45 -04003917 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003918
3919 uint32_t ShiftID = nextID;
3920
David Neto87846742018-04-11 17:36:22 -04003921 auto *Inst =
3922 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003923 SPIRVInstList.push_back(Inst);
3924
3925 //
3926 // Generate OpBitwiseAnd
3927 //
3928 // Ops[0] = Result Type ID
3929 // Ops[1] = Operand 0
3930 // Ops[2] = Operand 1
3931 //
3932 Ops.clear();
3933
David Neto257c3892018-04-11 13:19:45 -04003934 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003937 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003938
David Neto9b2d6252017-09-06 15:47:37 -04003939 // Reset mapping for this value to the result of the bitwise and.
3940 VMap[&I] = nextID;
3941
David Neto87846742018-04-11 17:36:22 -04003942 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003943 SPIRVInstList.push_back(Inst);
3944 break;
3945 }
3946
3947 // Ops[0] = Result Type ID
3948 // Ops[1] = Composite ID
3949 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3950 SPIRVOperandList Ops;
3951
David Neto257c3892018-04-11 13:19:45 -04003952 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003953
3954 spv::Op Opcode = spv::OpCompositeExtract;
3955 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003956 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003957 } else {
David Neto257c3892018-04-11 13:19:45 -04003958 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003959 Opcode = spv::OpVectorExtractDynamic;
3960 }
3961
David Neto87846742018-04-11 17:36:22 -04003962 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003963 SPIRVInstList.push_back(Inst);
3964 break;
3965 }
3966 case Instruction::InsertElement: {
3967 // Handle <4 x i8> type manually.
3968 Type *CompositeTy = I.getOperand(0)->getType();
3969 if (is4xi8vec(CompositeTy)) {
3970 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3971 uint32_t CstFFID = VMap[CstFF];
3972
3973 uint32_t ShiftAmountID = 0;
3974 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3975 // Handle constant index.
3976 uint64_t Idx = CI->getZExtValue();
3977 Value *ShiftAmount =
3978 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3979 ShiftAmountID = VMap[ShiftAmount];
3980 } else {
3981 // Handle variable index.
3982 SPIRVOperandList TmpOps;
3983
David Neto257c3892018-04-11 13:19:45 -04003984 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3985 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003986
3987 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003988 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003989
3990 ShiftAmountID = nextID;
3991
David Neto87846742018-04-11 17:36:22 -04003992 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003993 SPIRVInstList.push_back(TmpInst);
3994 }
3995
3996 //
3997 // Generate mask operations.
3998 //
3999
4000 // ShiftLeft mask according to index of insertelement.
4001 SPIRVOperandList Ops;
4002
David Neto257c3892018-04-11 13:19:45 -04004003 const uint32_t ResTyID = lookupType(CompositeTy);
4004 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004005
4006 uint32_t MaskID = nextID;
4007
David Neto87846742018-04-11 17:36:22 -04004008 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004009 SPIRVInstList.push_back(Inst);
4010
4011 // Inverse mask.
4012 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004013 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004014
4015 uint32_t InvMaskID = nextID;
4016
David Neto87846742018-04-11 17:36:22 -04004017 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004018 SPIRVInstList.push_back(Inst);
4019
4020 // Apply mask.
4021 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004022 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004023
4024 uint32_t OrgValID = nextID;
4025
David Neto87846742018-04-11 17:36:22 -04004026 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004027 SPIRVInstList.push_back(Inst);
4028
4029 // Create correct value according to index of insertelement.
4030 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004031 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4032 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004033
4034 uint32_t InsertValID = nextID;
4035
David Neto87846742018-04-11 17:36:22 -04004036 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004037 SPIRVInstList.push_back(Inst);
4038
4039 // Insert value to original value.
4040 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004041 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004042
David Netoa394f392017-08-26 20:45:29 -04004043 VMap[&I] = nextID;
4044
David Neto87846742018-04-11 17:36:22 -04004045 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004046 SPIRVInstList.push_back(Inst);
4047
4048 break;
4049 }
4050
David Neto22f144c2017-06-12 14:26:21 -04004051 SPIRVOperandList Ops;
4052
James Priced26efea2018-06-09 23:28:32 +01004053 // Ops[0] = Result Type ID
4054 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004055
4056 spv::Op Opcode = spv::OpCompositeInsert;
4057 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004058 const auto value = CI->getZExtValue();
4059 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004060 // Ops[1] = Object ID
4061 // Ops[2] = Composite ID
4062 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004063 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004064 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004065 } else {
James Priced26efea2018-06-09 23:28:32 +01004066 // Ops[1] = Composite ID
4067 // Ops[2] = Object ID
4068 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004069 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004070 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004071 Opcode = spv::OpVectorInsertDynamic;
4072 }
4073
David Neto87846742018-04-11 17:36:22 -04004074 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004075 SPIRVInstList.push_back(Inst);
4076 break;
4077 }
4078 case Instruction::ShuffleVector: {
4079 // Ops[0] = Result Type ID
4080 // Ops[1] = Vector 1 ID
4081 // Ops[2] = Vector 2 ID
4082 // Ops[3] ... Ops[n] = Components (Literal Number)
4083 SPIRVOperandList Ops;
4084
David Neto257c3892018-04-11 13:19:45 -04004085 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4086 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004087
4088 uint64_t NumElements = 0;
4089 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4090 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4091
4092 if (Cst->isNullValue()) {
4093 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004094 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004095 }
4096 } else if (const ConstantDataSequential *CDS =
4097 dyn_cast<ConstantDataSequential>(Cst)) {
4098 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4099 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004100 const auto value = CDS->getElementAsInteger(i);
4101 assert(value <= UINT32_MAX);
4102 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004103 }
4104 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4105 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4106 auto Op = CV->getOperand(i);
4107
4108 uint32_t literal = 0;
4109
4110 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4111 literal = static_cast<uint32_t>(CI->getZExtValue());
4112 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4113 literal = 0xFFFFFFFFu;
4114 } else {
4115 Op->print(errs());
4116 llvm_unreachable("Unsupported element in ConstantVector!");
4117 }
4118
David Neto257c3892018-04-11 13:19:45 -04004119 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004120 }
4121 } else {
4122 Cst->print(errs());
4123 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4124 }
4125 }
4126
David Neto87846742018-04-11 17:36:22 -04004127 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004128 SPIRVInstList.push_back(Inst);
4129 break;
4130 }
4131 case Instruction::ICmp:
4132 case Instruction::FCmp: {
4133 CmpInst *CmpI = cast<CmpInst>(&I);
4134
David Netod4ca2e62017-07-06 18:47:35 -04004135 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004136 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004137 if (isa<PointerType>(ArgTy)) {
4138 CmpI->print(errs());
4139 std::string name = I.getParent()->getParent()->getName();
4140 errs()
4141 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4142 << "in function " << name << "\n";
4143 llvm_unreachable("Pointer equality check is invalid");
4144 break;
4145 }
4146
David Neto257c3892018-04-11 13:19:45 -04004147 // Ops[0] = Result Type ID
4148 // Ops[1] = Operand 1 ID
4149 // Ops[2] = Operand 2 ID
4150 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004151
David Neto257c3892018-04-11 13:19:45 -04004152 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4153 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004154
4155 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004156 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004157 SPIRVInstList.push_back(Inst);
4158 break;
4159 }
4160 case Instruction::Br: {
4161 // Branch instrucion is deferred because it needs label's ID. Record slot's
4162 // location on SPIRVInstructionList.
4163 DeferredInsts.push_back(
4164 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4165 break;
4166 }
4167 case Instruction::Switch: {
4168 I.print(errs());
4169 llvm_unreachable("Unsupported instruction???");
4170 break;
4171 }
4172 case Instruction::IndirectBr: {
4173 I.print(errs());
4174 llvm_unreachable("Unsupported instruction???");
4175 break;
4176 }
4177 case Instruction::PHI: {
4178 // Branch instrucion is deferred because it needs label's ID. Record slot's
4179 // location on SPIRVInstructionList.
4180 DeferredInsts.push_back(
4181 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4182 break;
4183 }
4184 case Instruction::Alloca: {
4185 //
4186 // Generate OpVariable.
4187 //
4188 // Ops[0] : Result Type ID
4189 // Ops[1] : Storage Class
4190 SPIRVOperandList Ops;
4191
David Neto257c3892018-04-11 13:19:45 -04004192 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004193
David Neto87846742018-04-11 17:36:22 -04004194 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004195 SPIRVInstList.push_back(Inst);
4196 break;
4197 }
4198 case Instruction::Load: {
4199 LoadInst *LD = cast<LoadInst>(&I);
4200 //
4201 // Generate OpLoad.
4202 //
4203
David Neto0a2f98d2017-09-15 19:38:40 -04004204 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004205 uint32_t PointerID = VMap[LD->getPointerOperand()];
4206
4207 // This is a hack to work around what looks like a driver bug.
4208 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004209 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4210 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004211 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004212 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004213 // Generate a bitwise-and of the original value with itself.
4214 // We should have been able to get away with just an OpCopyObject,
4215 // but we need something more complex to get past certain driver bugs.
4216 // This is ridiculous, but necessary.
4217 // TODO(dneto): Revisit this once drivers fix their bugs.
4218
4219 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004220 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4221 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004222
David Neto87846742018-04-11 17:36:22 -04004223 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004224 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004225 break;
4226 }
4227
4228 // This is the normal path. Generate a load.
4229
David Neto22f144c2017-06-12 14:26:21 -04004230 // Ops[0] = Result Type ID
4231 // Ops[1] = Pointer ID
4232 // Ops[2] ... Ops[n] = Optional Memory Access
4233 //
4234 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004235
David Neto22f144c2017-06-12 14:26:21 -04004236 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004237 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004238
David Neto87846742018-04-11 17:36:22 -04004239 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004240 SPIRVInstList.push_back(Inst);
4241 break;
4242 }
4243 case Instruction::Store: {
4244 StoreInst *ST = cast<StoreInst>(&I);
4245 //
4246 // Generate OpStore.
4247 //
4248
4249 // Ops[0] = Pointer ID
4250 // Ops[1] = Object ID
4251 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4252 //
4253 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004254 SPIRVOperandList Ops;
4255 Ops << MkId(VMap[ST->getPointerOperand()])
4256 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004257
David Neto87846742018-04-11 17:36:22 -04004258 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004259 SPIRVInstList.push_back(Inst);
4260 break;
4261 }
4262 case Instruction::AtomicCmpXchg: {
4263 I.print(errs());
4264 llvm_unreachable("Unsupported instruction???");
4265 break;
4266 }
4267 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004268 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4269
4270 spv::Op opcode;
4271
4272 switch (AtomicRMW->getOperation()) {
4273 default:
4274 I.print(errs());
4275 llvm_unreachable("Unsupported instruction???");
4276 case llvm::AtomicRMWInst::Add:
4277 opcode = spv::OpAtomicIAdd;
4278 break;
4279 case llvm::AtomicRMWInst::Sub:
4280 opcode = spv::OpAtomicISub;
4281 break;
4282 case llvm::AtomicRMWInst::Xchg:
4283 opcode = spv::OpAtomicExchange;
4284 break;
4285 case llvm::AtomicRMWInst::Min:
4286 opcode = spv::OpAtomicSMin;
4287 break;
4288 case llvm::AtomicRMWInst::Max:
4289 opcode = spv::OpAtomicSMax;
4290 break;
4291 case llvm::AtomicRMWInst::UMin:
4292 opcode = spv::OpAtomicUMin;
4293 break;
4294 case llvm::AtomicRMWInst::UMax:
4295 opcode = spv::OpAtomicUMax;
4296 break;
4297 case llvm::AtomicRMWInst::And:
4298 opcode = spv::OpAtomicAnd;
4299 break;
4300 case llvm::AtomicRMWInst::Or:
4301 opcode = spv::OpAtomicOr;
4302 break;
4303 case llvm::AtomicRMWInst::Xor:
4304 opcode = spv::OpAtomicXor;
4305 break;
4306 }
4307
4308 //
4309 // Generate OpAtomic*.
4310 //
4311 SPIRVOperandList Ops;
4312
David Neto257c3892018-04-11 13:19:45 -04004313 Ops << MkId(lookupType(I.getType()))
4314 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004315
4316 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004317 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004318 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004319
4320 const auto ConstantMemorySemantics = ConstantInt::get(
4321 IntTy, spv::MemorySemanticsUniformMemoryMask |
4322 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004323 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004324
David Neto257c3892018-04-11 13:19:45 -04004325 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004326
4327 VMap[&I] = nextID;
4328
David Neto87846742018-04-11 17:36:22 -04004329 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004330 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004331 break;
4332 }
4333 case Instruction::Fence: {
4334 I.print(errs());
4335 llvm_unreachable("Unsupported instruction???");
4336 break;
4337 }
4338 case Instruction::Call: {
4339 CallInst *Call = dyn_cast<CallInst>(&I);
4340 Function *Callee = Call->getCalledFunction();
4341
Alan Baker202c8c72018-08-13 13:47:44 -04004342 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004343 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4344 // Generate an OpLoad
4345 SPIRVOperandList Ops;
4346 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004347
David Neto862b7d82018-06-14 18:48:37 -04004348 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4349 << MkId(ResourceVarDeferredLoadCalls[Call]);
4350
4351 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4352 SPIRVInstList.push_back(Inst);
4353 VMap[Call] = load_id;
4354 break;
4355
4356 } else {
4357 // This maps to an OpVariable we've already generated.
4358 // No code is generated for the call.
4359 }
4360 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004361 } else if (Callee->getName().startswith(
4362 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004363 // Don't codegen an instruction here, but instead map this call directly
4364 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004365 int spec_id = static_cast<int>(
4366 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004367 const auto &info = LocalSpecIdInfoMap[spec_id];
4368 VMap[Call] = info.variable_id;
4369 break;
David Neto862b7d82018-06-14 18:48:37 -04004370 }
4371
4372 // Sampler initializers become a load of the corresponding sampler.
4373
4374 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4375 // Map this to a load from the variable.
4376 const auto index_into_sampler_map =
4377 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4378
4379 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004380 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004381 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004382
David Neto257c3892018-04-11 13:19:45 -04004383 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004384 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4385 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004386
David Neto862b7d82018-06-14 18:48:37 -04004387 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004388 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004389 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004390 break;
4391 }
4392
4393 if (Callee->getName().startswith("spirv.atomic")) {
4394 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4395 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4396 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4397 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4398 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4399 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4400 .Case("spirv.atomic_compare_exchange",
4401 spv::OpAtomicCompareExchange)
4402 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4403 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4404 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4405 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4406 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4407 .Case("spirv.atomic_or", spv::OpAtomicOr)
4408 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4409 .Default(spv::OpNop);
4410
4411 //
4412 // Generate OpAtomic*.
4413 //
4414 SPIRVOperandList Ops;
4415
David Neto257c3892018-04-11 13:19:45 -04004416 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004417
4418 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004420 }
4421
4422 VMap[&I] = nextID;
4423
David Neto87846742018-04-11 17:36:22 -04004424 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004425 SPIRVInstList.push_back(Inst);
4426 break;
4427 }
4428
4429 if (Callee->getName().startswith("_Z3dot")) {
4430 // If the argument is a vector type, generate OpDot
4431 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4432 //
4433 // Generate OpDot.
4434 //
4435 SPIRVOperandList Ops;
4436
David Neto257c3892018-04-11 13:19:45 -04004437 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004438
4439 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004440 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004441 }
4442
4443 VMap[&I] = nextID;
4444
David Neto87846742018-04-11 17:36:22 -04004445 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004446 SPIRVInstList.push_back(Inst);
4447 } else {
4448 //
4449 // Generate OpFMul.
4450 //
4451 SPIRVOperandList Ops;
4452
David Neto257c3892018-04-11 13:19:45 -04004453 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004454
4455 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004456 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004457 }
4458
4459 VMap[&I] = nextID;
4460
David Neto87846742018-04-11 17:36:22 -04004461 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004462 SPIRVInstList.push_back(Inst);
4463 }
4464 break;
4465 }
4466
David Neto8505ebf2017-10-13 18:50:50 -04004467 if (Callee->getName().startswith("_Z4fmod")) {
4468 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4469 // The sign for a non-zero result is taken from x.
4470 // (Try an example.)
4471 // So translate to OpFRem
4472
4473 SPIRVOperandList Ops;
4474
David Neto257c3892018-04-11 13:19:45 -04004475 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004476
4477 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004478 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004479 }
4480
4481 VMap[&I] = nextID;
4482
David Neto87846742018-04-11 17:36:22 -04004483 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004484 SPIRVInstList.push_back(Inst);
4485 break;
4486 }
4487
David Neto22f144c2017-06-12 14:26:21 -04004488 // spirv.store_null.* intrinsics become OpStore's.
4489 if (Callee->getName().startswith("spirv.store_null")) {
4490 //
4491 // Generate OpStore.
4492 //
4493
4494 // Ops[0] = Pointer ID
4495 // Ops[1] = Object ID
4496 // Ops[2] ... Ops[n]
4497 SPIRVOperandList Ops;
4498
4499 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004500 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004501 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004502
David Neto87846742018-04-11 17:36:22 -04004503 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004504
4505 break;
4506 }
4507
4508 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4509 if (Callee->getName().startswith("spirv.copy_memory")) {
4510 //
4511 // Generate OpCopyMemory.
4512 //
4513
4514 // Ops[0] = Dst ID
4515 // Ops[1] = Src ID
4516 // Ops[2] = Memory Access
4517 // Ops[3] = Alignment
4518
4519 auto IsVolatile =
4520 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4521
4522 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4523 : spv::MemoryAccessMaskNone;
4524
4525 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4526
4527 auto Alignment =
4528 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4529
David Neto257c3892018-04-11 13:19:45 -04004530 SPIRVOperandList Ops;
4531 Ops << MkId(VMap[Call->getArgOperand(0)])
4532 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4533 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004534
David Neto87846742018-04-11 17:36:22 -04004535 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004536
4537 SPIRVInstList.push_back(Inst);
4538
4539 break;
4540 }
4541
4542 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4543 // with unit.
4544 if (Callee->getName().equals("_Z3absj") ||
4545 Callee->getName().equals("_Z3absDv2_j") ||
4546 Callee->getName().equals("_Z3absDv3_j") ||
4547 Callee->getName().equals("_Z3absDv4_j")) {
4548 VMap[&I] = VMap[Call->getOperand(0)];
4549 break;
4550 }
4551
4552 // barrier is converted to OpControlBarrier
4553 if (Callee->getName().equals("__spirv_control_barrier")) {
4554 //
4555 // Generate OpControlBarrier.
4556 //
4557 // Ops[0] = Execution Scope ID
4558 // Ops[1] = Memory Scope ID
4559 // Ops[2] = Memory Semantics ID
4560 //
4561 Value *ExecutionScope = Call->getArgOperand(0);
4562 Value *MemoryScope = Call->getArgOperand(1);
4563 Value *MemorySemantics = Call->getArgOperand(2);
4564
David Neto257c3892018-04-11 13:19:45 -04004565 SPIRVOperandList Ops;
4566 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4567 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004568
David Neto87846742018-04-11 17:36:22 -04004569 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004570 break;
4571 }
4572
4573 // memory barrier is converted to OpMemoryBarrier
4574 if (Callee->getName().equals("__spirv_memory_barrier")) {
4575 //
4576 // Generate OpMemoryBarrier.
4577 //
4578 // Ops[0] = Memory Scope ID
4579 // Ops[1] = Memory Semantics ID
4580 //
4581 SPIRVOperandList Ops;
4582
David Neto257c3892018-04-11 13:19:45 -04004583 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4584 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004585
David Neto257c3892018-04-11 13:19:45 -04004586 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004587
David Neto87846742018-04-11 17:36:22 -04004588 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004589 SPIRVInstList.push_back(Inst);
4590 break;
4591 }
4592
4593 // isinf is converted to OpIsInf
4594 if (Callee->getName().equals("__spirv_isinff") ||
4595 Callee->getName().equals("__spirv_isinfDv2_f") ||
4596 Callee->getName().equals("__spirv_isinfDv3_f") ||
4597 Callee->getName().equals("__spirv_isinfDv4_f")) {
4598 //
4599 // Generate OpIsInf.
4600 //
4601 // Ops[0] = Result Type ID
4602 // Ops[1] = X ID
4603 //
4604 SPIRVOperandList Ops;
4605
David Neto257c3892018-04-11 13:19:45 -04004606 Ops << MkId(lookupType(I.getType()))
4607 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004608
4609 VMap[&I] = nextID;
4610
David Neto87846742018-04-11 17:36:22 -04004611 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004612 SPIRVInstList.push_back(Inst);
4613 break;
4614 }
4615
4616 // isnan is converted to OpIsNan
4617 if (Callee->getName().equals("__spirv_isnanf") ||
4618 Callee->getName().equals("__spirv_isnanDv2_f") ||
4619 Callee->getName().equals("__spirv_isnanDv3_f") ||
4620 Callee->getName().equals("__spirv_isnanDv4_f")) {
4621 //
4622 // Generate OpIsInf.
4623 //
4624 // Ops[0] = Result Type ID
4625 // Ops[1] = X ID
4626 //
4627 SPIRVOperandList Ops;
4628
David Neto257c3892018-04-11 13:19:45 -04004629 Ops << MkId(lookupType(I.getType()))
4630 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004631
4632 VMap[&I] = nextID;
4633
David Neto87846742018-04-11 17:36:22 -04004634 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004635 SPIRVInstList.push_back(Inst);
4636 break;
4637 }
4638
4639 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004640 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004641 //
4642 // Generate OpAll.
4643 //
4644 // Ops[0] = Result Type ID
4645 // Ops[1] = Vector ID
4646 //
4647 SPIRVOperandList Ops;
4648
David Neto257c3892018-04-11 13:19:45 -04004649 Ops << MkId(lookupType(I.getType()))
4650 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004651
4652 VMap[&I] = nextID;
4653
David Neto87846742018-04-11 17:36:22 -04004654 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004655 SPIRVInstList.push_back(Inst);
4656 break;
4657 }
4658
4659 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004660 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004661 //
4662 // Generate OpAny.
4663 //
4664 // Ops[0] = Result Type ID
4665 // Ops[1] = Vector ID
4666 //
4667 SPIRVOperandList Ops;
4668
David Neto257c3892018-04-11 13:19:45 -04004669 Ops << MkId(lookupType(I.getType()))
4670 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004671
4672 VMap[&I] = nextID;
4673
David Neto87846742018-04-11 17:36:22 -04004674 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004675 SPIRVInstList.push_back(Inst);
4676 break;
4677 }
4678
4679 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4680 // Additionally, OpTypeSampledImage is generated.
4681 if (Callee->getName().equals(
4682 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4683 Callee->getName().equals(
4684 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4685 //
4686 // Generate OpSampledImage.
4687 //
4688 // Ops[0] = Result Type ID
4689 // Ops[1] = Image ID
4690 // Ops[2] = Sampler ID
4691 //
4692 SPIRVOperandList Ops;
4693
4694 Value *Image = Call->getArgOperand(0);
4695 Value *Sampler = Call->getArgOperand(1);
4696 Value *Coordinate = Call->getArgOperand(2);
4697
4698 TypeMapType &OpImageTypeMap = getImageTypeMap();
4699 Type *ImageTy = Image->getType()->getPointerElementType();
4700 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004701 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004702 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004703
4704 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004705
4706 uint32_t SampledImageID = nextID;
4707
David Neto87846742018-04-11 17:36:22 -04004708 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004709 SPIRVInstList.push_back(Inst);
4710
4711 //
4712 // Generate OpImageSampleExplicitLod.
4713 //
4714 // Ops[0] = Result Type ID
4715 // Ops[1] = Sampled Image ID
4716 // Ops[2] = Coordinate ID
4717 // Ops[3] = Image Operands Type ID
4718 // Ops[4] ... Ops[n] = Operands ID
4719 //
4720 Ops.clear();
4721
David Neto257c3892018-04-11 13:19:45 -04004722 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4723 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004724
4725 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004726 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004727
4728 VMap[&I] = nextID;
4729
David Neto87846742018-04-11 17:36:22 -04004730 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004731 SPIRVInstList.push_back(Inst);
4732 break;
4733 }
4734
4735 // write_imagef is mapped to OpImageWrite.
4736 if (Callee->getName().equals(
4737 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4738 Callee->getName().equals(
4739 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4740 //
4741 // Generate OpImageWrite.
4742 //
4743 // Ops[0] = Image ID
4744 // Ops[1] = Coordinate ID
4745 // Ops[2] = Texel ID
4746 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4747 // Ops[4] ... Ops[n] = (Optional) Operands ID
4748 //
4749 SPIRVOperandList Ops;
4750
4751 Value *Image = Call->getArgOperand(0);
4752 Value *Coordinate = Call->getArgOperand(1);
4753 Value *Texel = Call->getArgOperand(2);
4754
4755 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004756 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004757 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004758 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004759
David Neto87846742018-04-11 17:36:22 -04004760 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004761 SPIRVInstList.push_back(Inst);
4762 break;
4763 }
4764
David Neto5c22a252018-03-15 16:07:41 -04004765 // get_image_width is mapped to OpImageQuerySize
4766 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4767 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4768 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4769 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4770 //
4771 // Generate OpImageQuerySize, then pull out the right component.
4772 // Assume 2D image for now.
4773 //
4774 // Ops[0] = Image ID
4775 //
4776 // %sizes = OpImageQuerySizes %uint2 %im
4777 // %result = OpCompositeExtract %uint %sizes 0-or-1
4778 SPIRVOperandList Ops;
4779
4780 // Implement:
4781 // %sizes = OpImageQuerySizes %uint2 %im
4782 uint32_t SizesTypeID =
4783 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004784 Value *Image = Call->getArgOperand(0);
4785 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004786 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004787
4788 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004789 auto *QueryInst =
4790 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004791 SPIRVInstList.push_back(QueryInst);
4792
4793 // Reset value map entry since we generated an intermediate instruction.
4794 VMap[&I] = nextID;
4795
4796 // Implement:
4797 // %result = OpCompositeExtract %uint %sizes 0-or-1
4798 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004799 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004800
4801 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004802 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004803
David Neto87846742018-04-11 17:36:22 -04004804 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004805 SPIRVInstList.push_back(Inst);
4806 break;
4807 }
4808
David Neto22f144c2017-06-12 14:26:21 -04004809 // Call instrucion is deferred because it needs function's ID. Record
4810 // slot's location on SPIRVInstructionList.
4811 DeferredInsts.push_back(
4812 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4813
David Neto3fbb4072017-10-16 11:28:14 -04004814 // Check whether the implementation of this call uses an extended
4815 // instruction plus one more value-producing instruction. If so, then
4816 // reserve the id for the extra value-producing slot.
4817 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4818 if (EInst != kGlslExtInstBad) {
4819 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004820 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004821 VMap[&I] = nextID;
4822 nextID++;
4823 }
4824 break;
4825 }
4826 case Instruction::Ret: {
4827 unsigned NumOps = I.getNumOperands();
4828 if (NumOps == 0) {
4829 //
4830 // Generate OpReturn.
4831 //
David Neto87846742018-04-11 17:36:22 -04004832 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004833 } else {
4834 //
4835 // Generate OpReturnValue.
4836 //
4837
4838 // Ops[0] = Return Value ID
4839 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004840
4841 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004842
David Neto87846742018-04-11 17:36:22 -04004843 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004844 SPIRVInstList.push_back(Inst);
4845 break;
4846 }
4847 break;
4848 }
4849 }
4850}
4851
4852void SPIRVProducerPass::GenerateFuncEpilogue() {
4853 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4854
4855 //
4856 // Generate OpFunctionEnd
4857 //
4858
David Neto87846742018-04-11 17:36:22 -04004859 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004860 SPIRVInstList.push_back(Inst);
4861}
4862
4863bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4864 LLVMContext &Context = Ty->getContext();
4865 if (Ty->isVectorTy()) {
4866 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4867 Ty->getVectorNumElements() == 4) {
4868 return true;
4869 }
4870 }
4871
4872 return false;
4873}
4874
David Neto257c3892018-04-11 13:19:45 -04004875uint32_t SPIRVProducerPass::GetI32Zero() {
4876 if (0 == constant_i32_zero_id_) {
4877 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4878 "defined in the SPIR-V module");
4879 }
4880 return constant_i32_zero_id_;
4881}
4882
David Neto22f144c2017-06-12 14:26:21 -04004883void SPIRVProducerPass::HandleDeferredInstruction() {
4884 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4885 ValueMapType &VMap = getValueMap();
4886 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4887
4888 for (auto DeferredInst = DeferredInsts.rbegin();
4889 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4890 Value *Inst = std::get<0>(*DeferredInst);
4891 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4892 if (InsertPoint != SPIRVInstList.end()) {
4893 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4894 ++InsertPoint;
4895 }
4896 }
4897
4898 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4899 // Check whether basic block, which has this branch instruction, is loop
4900 // header or not. If it is loop header, generate OpLoopMerge and
4901 // OpBranchConditional.
4902 Function *Func = Br->getParent()->getParent();
4903 DominatorTree &DT =
4904 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4905 const LoopInfo &LI =
4906 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4907
4908 BasicBlock *BrBB = Br->getParent();
4909 if (LI.isLoopHeader(BrBB)) {
4910 Value *ContinueBB = nullptr;
4911 Value *MergeBB = nullptr;
4912
4913 Loop *L = LI.getLoopFor(BrBB);
4914 MergeBB = L->getExitBlock();
4915 if (!MergeBB) {
4916 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4917 // has regions with single entry/exit. As a result, loop should not
4918 // have multiple exits.
4919 llvm_unreachable("Loop has multiple exits???");
4920 }
4921
4922 if (L->isLoopLatch(BrBB)) {
4923 ContinueBB = BrBB;
4924 } else {
4925 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4926 // block.
4927 BasicBlock *Header = L->getHeader();
4928 BasicBlock *Latch = L->getLoopLatch();
4929 for (BasicBlock *BB : L->blocks()) {
4930 if (BB == Header) {
4931 continue;
4932 }
4933
4934 // Check whether block dominates block with back-edge.
4935 if (DT.dominates(BB, Latch)) {
4936 ContinueBB = BB;
4937 }
4938 }
4939
4940 if (!ContinueBB) {
4941 llvm_unreachable("Wrong continue block from loop");
4942 }
4943 }
4944
4945 //
4946 // Generate OpLoopMerge.
4947 //
4948 // Ops[0] = Merge Block ID
4949 // Ops[1] = Continue Target ID
4950 // Ops[2] = Selection Control
4951 SPIRVOperandList Ops;
4952
4953 // StructurizeCFG pass already manipulated CFG. Just use false block of
4954 // branch instruction as merge block.
4955 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004956 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004957 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4958 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004959
David Neto87846742018-04-11 17:36:22 -04004960 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004961 SPIRVInstList.insert(InsertPoint, MergeInst);
4962
4963 } else if (Br->isConditional()) {
4964 bool HasBackEdge = false;
4965
4966 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4967 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4968 HasBackEdge = true;
4969 }
4970 }
4971 if (!HasBackEdge) {
4972 //
4973 // Generate OpSelectionMerge.
4974 //
4975 // Ops[0] = Merge Block ID
4976 // Ops[1] = Selection Control
4977 SPIRVOperandList Ops;
4978
4979 // StructurizeCFG pass already manipulated CFG. Just use false block
4980 // of branch instruction as merge block.
4981 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004982 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004983
David Neto87846742018-04-11 17:36:22 -04004984 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004985 SPIRVInstList.insert(InsertPoint, MergeInst);
4986 }
4987 }
4988
4989 if (Br->isConditional()) {
4990 //
4991 // Generate OpBranchConditional.
4992 //
4993 // Ops[0] = Condition ID
4994 // Ops[1] = True Label ID
4995 // Ops[2] = False Label ID
4996 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4997 SPIRVOperandList Ops;
4998
4999 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005000 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005001 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005002
5003 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005004
David Neto87846742018-04-11 17:36:22 -04005005 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005006 SPIRVInstList.insert(InsertPoint, BrInst);
5007 } else {
5008 //
5009 // Generate OpBranch.
5010 //
5011 // Ops[0] = Target Label ID
5012 SPIRVOperandList Ops;
5013
5014 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005015 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005016
David Neto87846742018-04-11 17:36:22 -04005017 SPIRVInstList.insert(InsertPoint,
5018 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005019 }
5020 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5021 //
5022 // Generate OpPhi.
5023 //
5024 // Ops[0] = Result Type ID
5025 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5026 SPIRVOperandList Ops;
5027
David Neto257c3892018-04-11 13:19:45 -04005028 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005029
David Neto22f144c2017-06-12 14:26:21 -04005030 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5031 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005032 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005033 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005034 }
5035
5036 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005037 InsertPoint,
5038 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005039 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5040 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005041 auto callee_name = Callee->getName();
5042 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005043
5044 if (EInst) {
5045 uint32_t &ExtInstImportID = getOpExtInstImportID();
5046
5047 //
5048 // Generate OpExtInst.
5049 //
5050
5051 // Ops[0] = Result Type ID
5052 // Ops[1] = Set ID (OpExtInstImport ID)
5053 // Ops[2] = Instruction Number (Literal Number)
5054 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5055 SPIRVOperandList Ops;
5056
David Neto862b7d82018-06-14 18:48:37 -04005057 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5058 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005059
David Neto22f144c2017-06-12 14:26:21 -04005060 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5061 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005062 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005063 }
5064
David Neto87846742018-04-11 17:36:22 -04005065 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5066 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005067 SPIRVInstList.insert(InsertPoint, ExtInst);
5068
David Neto3fbb4072017-10-16 11:28:14 -04005069 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5070 if (IndirectExtInst != kGlslExtInstBad) {
5071 // Generate one more instruction that uses the result of the extended
5072 // instruction. Its result id is one more than the id of the
5073 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005074 LLVMContext &Context =
5075 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005076
David Neto3fbb4072017-10-16 11:28:14 -04005077 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5078 &VMap, &SPIRVInstList, &InsertPoint](
5079 spv::Op opcode, Constant *constant) {
5080 //
5081 // Generate instruction like:
5082 // result = opcode constant <extinst-result>
5083 //
5084 // Ops[0] = Result Type ID
5085 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5086 // Ops[2] = Operand 1 ;; the result of the extended instruction
5087 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005088
David Neto3fbb4072017-10-16 11:28:14 -04005089 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005090 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005091
5092 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5093 constant = ConstantVector::getSplat(
5094 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5095 }
David Neto257c3892018-04-11 13:19:45 -04005096 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005097
5098 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005099 InsertPoint, new SPIRVInstruction(
5100 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005101 };
5102
5103 switch (IndirectExtInst) {
5104 case glsl::ExtInstFindUMsb: // Implementing clz
5105 generate_extra_inst(
5106 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5107 break;
5108 case glsl::ExtInstAcos: // Implementing acospi
5109 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005110 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005111 case glsl::ExtInstAtan2: // Implementing atan2pi
5112 generate_extra_inst(
5113 spv::OpFMul,
5114 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5115 break;
5116
5117 default:
5118 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005119 }
David Neto22f144c2017-06-12 14:26:21 -04005120 }
David Neto3fbb4072017-10-16 11:28:14 -04005121
David Neto862b7d82018-06-14 18:48:37 -04005122 } else if (callee_name.equals("_Z8popcounti") ||
5123 callee_name.equals("_Z8popcountj") ||
5124 callee_name.equals("_Z8popcountDv2_i") ||
5125 callee_name.equals("_Z8popcountDv3_i") ||
5126 callee_name.equals("_Z8popcountDv4_i") ||
5127 callee_name.equals("_Z8popcountDv2_j") ||
5128 callee_name.equals("_Z8popcountDv3_j") ||
5129 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005130 //
5131 // Generate OpBitCount
5132 //
5133 // Ops[0] = Result Type ID
5134 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005135 SPIRVOperandList Ops;
5136 Ops << MkId(lookupType(Call->getType()))
5137 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005138
5139 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005140 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005141 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005142
David Neto862b7d82018-06-14 18:48:37 -04005143 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005144
5145 // Generate an OpCompositeConstruct
5146 SPIRVOperandList Ops;
5147
5148 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005149 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005150
5151 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005152 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005153 }
5154
5155 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005156 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5157 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005158
Alan Baker202c8c72018-08-13 13:47:44 -04005159 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5160
5161 // We have already mapped the call's result value to an ID.
5162 // Don't generate any code now.
5163
5164 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005165
5166 // We have already mapped the call's result value to an ID.
5167 // Don't generate any code now.
5168
David Neto22f144c2017-06-12 14:26:21 -04005169 } else {
5170 //
5171 // Generate OpFunctionCall.
5172 //
5173
5174 // Ops[0] = Result Type ID
5175 // Ops[1] = Callee Function ID
5176 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5177 SPIRVOperandList Ops;
5178
David Neto862b7d82018-06-14 18:48:37 -04005179 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005180
5181 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005182 if (CalleeID == 0) {
5183 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005184 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005185 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5186 // causes an infinite loop. Instead, go ahead and generate
5187 // the bad function call. A validator will catch the 0-Id.
5188 // llvm_unreachable("Can't translate function call");
5189 }
David Neto22f144c2017-06-12 14:26:21 -04005190
David Neto257c3892018-04-11 13:19:45 -04005191 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005192
David Neto22f144c2017-06-12 14:26:21 -04005193 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5194 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005195 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005196 }
5197
David Neto87846742018-04-11 17:36:22 -04005198 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5199 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005200 SPIRVInstList.insert(InsertPoint, CallInst);
5201 }
5202 }
5203 }
5204}
5205
David Neto1a1a0582017-07-07 12:01:44 -04005206void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005207 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005208 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005209 }
David Neto1a1a0582017-07-07 12:01:44 -04005210
5211 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005212
5213 // Find an iterator pointing just past the last decoration.
5214 bool seen_decorations = false;
5215 auto DecoInsertPoint =
5216 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5217 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5218 const bool is_decoration =
5219 Inst->getOpcode() == spv::OpDecorate ||
5220 Inst->getOpcode() == spv::OpMemberDecorate;
5221 if (is_decoration) {
5222 seen_decorations = true;
5223 return false;
5224 } else {
5225 return seen_decorations;
5226 }
5227 });
5228
David Netoc6f3ab22018-04-06 18:02:31 -04005229 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5230 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005231 for (auto *type : getTypesNeedingArrayStride()) {
5232 Type *elemTy = nullptr;
5233 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5234 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005235 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005236 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005237 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005238 elemTy = seqTy->getSequentialElementType();
5239 } else {
5240 errs() << "Unhandled strided type " << *type << "\n";
5241 llvm_unreachable("Unhandled strided type");
5242 }
David Neto1a1a0582017-07-07 12:01:44 -04005243
5244 // Ops[0] = Target ID
5245 // Ops[1] = Decoration (ArrayStride)
5246 // Ops[2] = Stride number (Literal Number)
5247 SPIRVOperandList Ops;
5248
David Neto85082642018-03-24 06:55:20 -07005249 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005250 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005251
5252 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5253 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005254
David Neto87846742018-04-11 17:36:22 -04005255 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005256 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5257 }
David Netoc6f3ab22018-04-06 18:02:31 -04005258
5259 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005260 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5261 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005262 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005263 SPIRVOperandList Ops;
5264 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5265 << MkNum(arg_info.spec_id);
5266 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005267 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005268 }
David Neto1a1a0582017-07-07 12:01:44 -04005269}
5270
David Neto22f144c2017-06-12 14:26:21 -04005271glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5272 return StringSwitch<glsl::ExtInst>(Name)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005273 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5274 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5275 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5276 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005277 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5278 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5279 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5280 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005281 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5282 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5283 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5284 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005285 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5286 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5287 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5288 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5289 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5290 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5291 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5292 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5293 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5294 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5295 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5296 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005297 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5298 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5299 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5300 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5301 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5302 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5303 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5304 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005305 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5306 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5307 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5308 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5309 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5310 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5311 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5312 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005313 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5314 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5315 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5316 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5317 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5318 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5319 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5320 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005321 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5322 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5323 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5324 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5325 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005326 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5327 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5328 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5329 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5330 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5331 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5332 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5333 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005334 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5335 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5336 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5337 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5338 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5339 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5340 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5341 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005342 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5343 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5344 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5345 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5346 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5347 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5348 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5349 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005350 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5351 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5352 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5353 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5354 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5355 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5356 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5357 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5358 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5359 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5360 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5361 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5362 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5363 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5364 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5365 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5366 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5367 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5368 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5369 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5370 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5371 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5372 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5373 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5374 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5375 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5376 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5377 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5378 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5379 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5380 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5381 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5382 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5383 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5384 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5385 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5386 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5387 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5388 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5389 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5390 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005391 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005392 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5393 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5394 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5395 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5396 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5397 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5398 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5399 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5400 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5401 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5402 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5403 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5404 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5405 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5406 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5407 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5408 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005409 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005410 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005411 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005412 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005413 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005414 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5415 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005416 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005417 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5418 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5419 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005420 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5421 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5422 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5423 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005424 .Default(kGlslExtInstBad);
5425}
5426
5427glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5428 // Check indirect cases.
5429 return StringSwitch<glsl::ExtInst>(Name)
5430 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5431 // Use exact match on float arg because these need a multiply
5432 // of a constant of the right floating point type.
5433 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5434 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5435 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5436 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5437 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5438 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5439 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5440 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005441 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5442 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5443 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5444 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005445 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5446 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5447 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5448 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5449 .Default(kGlslExtInstBad);
5450}
5451
alan-bakerb6b09dc2018-11-08 16:59:28 -05005452glsl::ExtInst
5453SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005454 auto direct = getExtInstEnum(Name);
5455 if (direct != kGlslExtInstBad)
5456 return direct;
5457 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005458}
5459
5460void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5461 out << "%" << Inst->getResultID();
5462}
5463
5464void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5465 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5466 out << "\t" << spv::getOpName(Opcode);
5467}
5468
5469void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5470 SPIRVOperandType OpTy = Op->getType();
5471 switch (OpTy) {
5472 default: {
5473 llvm_unreachable("Unsupported SPIRV Operand Type???");
5474 break;
5475 }
5476 case SPIRVOperandType::NUMBERID: {
5477 out << "%" << Op->getNumID();
5478 break;
5479 }
5480 case SPIRVOperandType::LITERAL_STRING: {
5481 out << "\"" << Op->getLiteralStr() << "\"";
5482 break;
5483 }
5484 case SPIRVOperandType::LITERAL_INTEGER: {
5485 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005486 auto Words = Op->getLiteralNum();
5487 auto NumWords = Words.size();
5488
5489 if (NumWords == 1) {
5490 out << Words[0];
5491 } else if (NumWords == 2) {
5492 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5493 out << Val;
5494 } else {
5495 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005496 }
5497 break;
5498 }
5499 case SPIRVOperandType::LITERAL_FLOAT: {
5500 // TODO: Handle LiteralNum carefully.
5501 for (auto Word : Op->getLiteralNum()) {
5502 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5503 SmallString<8> Str;
5504 APF.toString(Str, 6, 2);
5505 out << Str;
5506 }
5507 break;
5508 }
5509 }
5510}
5511
5512void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5513 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5514 out << spv::getCapabilityName(Cap);
5515}
5516
5517void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5518 auto LiteralNum = Op->getLiteralNum();
5519 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5520 out << glsl::getExtInstName(Ext);
5521}
5522
5523void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5524 spv::AddressingModel AddrModel =
5525 static_cast<spv::AddressingModel>(Op->getNumID());
5526 out << spv::getAddressingModelName(AddrModel);
5527}
5528
5529void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5530 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5531 out << spv::getMemoryModelName(MemModel);
5532}
5533
5534void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5535 spv::ExecutionModel ExecModel =
5536 static_cast<spv::ExecutionModel>(Op->getNumID());
5537 out << spv::getExecutionModelName(ExecModel);
5538}
5539
5540void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5541 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5542 out << spv::getExecutionModeName(ExecMode);
5543}
5544
5545void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005546 spv::SourceLanguage SourceLang =
5547 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005548 out << spv::getSourceLanguageName(SourceLang);
5549}
5550
5551void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5552 spv::FunctionControlMask FuncCtrl =
5553 static_cast<spv::FunctionControlMask>(Op->getNumID());
5554 out << spv::getFunctionControlName(FuncCtrl);
5555}
5556
5557void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5558 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5559 out << getStorageClassName(StClass);
5560}
5561
5562void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5563 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5564 out << getDecorationName(Deco);
5565}
5566
5567void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5568 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5569 out << getBuiltInName(BIn);
5570}
5571
5572void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5573 spv::SelectionControlMask BIn =
5574 static_cast<spv::SelectionControlMask>(Op->getNumID());
5575 out << getSelectionControlName(BIn);
5576}
5577
5578void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5579 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5580 out << getLoopControlName(BIn);
5581}
5582
5583void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5584 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5585 out << getDimName(DIM);
5586}
5587
5588void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5589 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5590 out << getImageFormatName(Format);
5591}
5592
5593void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5594 out << spv::getMemoryAccessName(
5595 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5596}
5597
5598void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5599 auto LiteralNum = Op->getLiteralNum();
5600 spv::ImageOperandsMask Type =
5601 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5602 out << getImageOperandsName(Type);
5603}
5604
5605void SPIRVProducerPass::WriteSPIRVAssembly() {
5606 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5607
5608 for (auto Inst : SPIRVInstList) {
5609 SPIRVOperandList Ops = Inst->getOperands();
5610 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5611
5612 switch (Opcode) {
5613 default: {
5614 llvm_unreachable("Unsupported SPIRV instruction");
5615 break;
5616 }
5617 case spv::OpCapability: {
5618 // Ops[0] = Capability
5619 PrintOpcode(Inst);
5620 out << " ";
5621 PrintCapability(Ops[0]);
5622 out << "\n";
5623 break;
5624 }
5625 case spv::OpMemoryModel: {
5626 // Ops[0] = Addressing Model
5627 // Ops[1] = Memory Model
5628 PrintOpcode(Inst);
5629 out << " ";
5630 PrintAddrModel(Ops[0]);
5631 out << " ";
5632 PrintMemModel(Ops[1]);
5633 out << "\n";
5634 break;
5635 }
5636 case spv::OpEntryPoint: {
5637 // Ops[0] = Execution Model
5638 // Ops[1] = EntryPoint ID
5639 // Ops[2] = Name (Literal String)
5640 // Ops[3] ... Ops[n] = Interface ID
5641 PrintOpcode(Inst);
5642 out << " ";
5643 PrintExecModel(Ops[0]);
5644 for (uint32_t i = 1; i < Ops.size(); i++) {
5645 out << " ";
5646 PrintOperand(Ops[i]);
5647 }
5648 out << "\n";
5649 break;
5650 }
5651 case spv::OpExecutionMode: {
5652 // Ops[0] = Entry Point ID
5653 // Ops[1] = Execution Mode
5654 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5655 PrintOpcode(Inst);
5656 out << " ";
5657 PrintOperand(Ops[0]);
5658 out << " ";
5659 PrintExecMode(Ops[1]);
5660 for (uint32_t i = 2; i < Ops.size(); i++) {
5661 out << " ";
5662 PrintOperand(Ops[i]);
5663 }
5664 out << "\n";
5665 break;
5666 }
5667 case spv::OpSource: {
5668 // Ops[0] = SourceLanguage ID
5669 // Ops[1] = Version (LiteralNum)
5670 PrintOpcode(Inst);
5671 out << " ";
5672 PrintSourceLanguage(Ops[0]);
5673 out << " ";
5674 PrintOperand(Ops[1]);
5675 out << "\n";
5676 break;
5677 }
5678 case spv::OpDecorate: {
5679 // Ops[0] = Target ID
5680 // Ops[1] = Decoration (Block or BufferBlock)
5681 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5682 PrintOpcode(Inst);
5683 out << " ";
5684 PrintOperand(Ops[0]);
5685 out << " ";
5686 PrintDecoration(Ops[1]);
5687 // Handle BuiltIn OpDecorate specially.
5688 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5689 out << " ";
5690 PrintBuiltIn(Ops[2]);
5691 } else {
5692 for (uint32_t i = 2; i < Ops.size(); i++) {
5693 out << " ";
5694 PrintOperand(Ops[i]);
5695 }
5696 }
5697 out << "\n";
5698 break;
5699 }
5700 case spv::OpMemberDecorate: {
5701 // Ops[0] = Structure Type ID
5702 // Ops[1] = Member Index(Literal Number)
5703 // Ops[2] = Decoration
5704 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5705 PrintOpcode(Inst);
5706 out << " ";
5707 PrintOperand(Ops[0]);
5708 out << " ";
5709 PrintOperand(Ops[1]);
5710 out << " ";
5711 PrintDecoration(Ops[2]);
5712 for (uint32_t i = 3; i < Ops.size(); i++) {
5713 out << " ";
5714 PrintOperand(Ops[i]);
5715 }
5716 out << "\n";
5717 break;
5718 }
5719 case spv::OpTypePointer: {
5720 // Ops[0] = Storage Class
5721 // Ops[1] = Element Type ID
5722 PrintResID(Inst);
5723 out << " = ";
5724 PrintOpcode(Inst);
5725 out << " ";
5726 PrintStorageClass(Ops[0]);
5727 out << " ";
5728 PrintOperand(Ops[1]);
5729 out << "\n";
5730 break;
5731 }
5732 case spv::OpTypeImage: {
5733 // Ops[0] = Sampled Type ID
5734 // Ops[1] = Dim ID
5735 // Ops[2] = Depth (Literal Number)
5736 // Ops[3] = Arrayed (Literal Number)
5737 // Ops[4] = MS (Literal Number)
5738 // Ops[5] = Sampled (Literal Number)
5739 // Ops[6] = Image Format ID
5740 PrintResID(Inst);
5741 out << " = ";
5742 PrintOpcode(Inst);
5743 out << " ";
5744 PrintOperand(Ops[0]);
5745 out << " ";
5746 PrintDimensionality(Ops[1]);
5747 out << " ";
5748 PrintOperand(Ops[2]);
5749 out << " ";
5750 PrintOperand(Ops[3]);
5751 out << " ";
5752 PrintOperand(Ops[4]);
5753 out << " ";
5754 PrintOperand(Ops[5]);
5755 out << " ";
5756 PrintImageFormat(Ops[6]);
5757 out << "\n";
5758 break;
5759 }
5760 case spv::OpFunction: {
5761 // Ops[0] : Result Type ID
5762 // Ops[1] : Function Control
5763 // Ops[2] : Function Type ID
5764 PrintResID(Inst);
5765 out << " = ";
5766 PrintOpcode(Inst);
5767 out << " ";
5768 PrintOperand(Ops[0]);
5769 out << " ";
5770 PrintFuncCtrl(Ops[1]);
5771 out << " ";
5772 PrintOperand(Ops[2]);
5773 out << "\n";
5774 break;
5775 }
5776 case spv::OpSelectionMerge: {
5777 // Ops[0] = Merge Block ID
5778 // Ops[1] = Selection Control
5779 PrintOpcode(Inst);
5780 out << " ";
5781 PrintOperand(Ops[0]);
5782 out << " ";
5783 PrintSelectionControl(Ops[1]);
5784 out << "\n";
5785 break;
5786 }
5787 case spv::OpLoopMerge: {
5788 // Ops[0] = Merge Block ID
5789 // Ops[1] = Continue Target ID
5790 // Ops[2] = Selection Control
5791 PrintOpcode(Inst);
5792 out << " ";
5793 PrintOperand(Ops[0]);
5794 out << " ";
5795 PrintOperand(Ops[1]);
5796 out << " ";
5797 PrintLoopControl(Ops[2]);
5798 out << "\n";
5799 break;
5800 }
5801 case spv::OpImageSampleExplicitLod: {
5802 // Ops[0] = Result Type ID
5803 // Ops[1] = Sampled Image ID
5804 // Ops[2] = Coordinate ID
5805 // Ops[3] = Image Operands Type ID
5806 // Ops[4] ... Ops[n] = Operands ID
5807 PrintResID(Inst);
5808 out << " = ";
5809 PrintOpcode(Inst);
5810 for (uint32_t i = 0; i < 3; i++) {
5811 out << " ";
5812 PrintOperand(Ops[i]);
5813 }
5814 out << " ";
5815 PrintImageOperandsType(Ops[3]);
5816 for (uint32_t i = 4; i < Ops.size(); i++) {
5817 out << " ";
5818 PrintOperand(Ops[i]);
5819 }
5820 out << "\n";
5821 break;
5822 }
5823 case spv::OpVariable: {
5824 // Ops[0] : Result Type ID
5825 // Ops[1] : Storage Class
5826 // Ops[2] ... Ops[n] = Initializer IDs
5827 PrintResID(Inst);
5828 out << " = ";
5829 PrintOpcode(Inst);
5830 out << " ";
5831 PrintOperand(Ops[0]);
5832 out << " ";
5833 PrintStorageClass(Ops[1]);
5834 for (uint32_t i = 2; i < Ops.size(); i++) {
5835 out << " ";
5836 PrintOperand(Ops[i]);
5837 }
5838 out << "\n";
5839 break;
5840 }
5841 case spv::OpExtInst: {
5842 // Ops[0] = Result Type ID
5843 // Ops[1] = Set ID (OpExtInstImport ID)
5844 // Ops[2] = Instruction Number (Literal Number)
5845 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5846 PrintResID(Inst);
5847 out << " = ";
5848 PrintOpcode(Inst);
5849 out << " ";
5850 PrintOperand(Ops[0]);
5851 out << " ";
5852 PrintOperand(Ops[1]);
5853 out << " ";
5854 PrintExtInst(Ops[2]);
5855 for (uint32_t i = 3; i < Ops.size(); i++) {
5856 out << " ";
5857 PrintOperand(Ops[i]);
5858 }
5859 out << "\n";
5860 break;
5861 }
5862 case spv::OpCopyMemory: {
5863 // Ops[0] = Addressing Model
5864 // Ops[1] = Memory Model
5865 PrintOpcode(Inst);
5866 out << " ";
5867 PrintOperand(Ops[0]);
5868 out << " ";
5869 PrintOperand(Ops[1]);
5870 out << " ";
5871 PrintMemoryAccess(Ops[2]);
5872 out << " ";
5873 PrintOperand(Ops[3]);
5874 out << "\n";
5875 break;
5876 }
5877 case spv::OpExtension:
5878 case spv::OpControlBarrier:
5879 case spv::OpMemoryBarrier:
5880 case spv::OpBranch:
5881 case spv::OpBranchConditional:
5882 case spv::OpStore:
5883 case spv::OpImageWrite:
5884 case spv::OpReturnValue:
5885 case spv::OpReturn:
5886 case spv::OpFunctionEnd: {
5887 PrintOpcode(Inst);
5888 for (uint32_t i = 0; i < Ops.size(); i++) {
5889 out << " ";
5890 PrintOperand(Ops[i]);
5891 }
5892 out << "\n";
5893 break;
5894 }
5895 case spv::OpExtInstImport:
5896 case spv::OpTypeRuntimeArray:
5897 case spv::OpTypeStruct:
5898 case spv::OpTypeSampler:
5899 case spv::OpTypeSampledImage:
5900 case spv::OpTypeInt:
5901 case spv::OpTypeFloat:
5902 case spv::OpTypeArray:
5903 case spv::OpTypeVector:
5904 case spv::OpTypeBool:
5905 case spv::OpTypeVoid:
5906 case spv::OpTypeFunction:
5907 case spv::OpFunctionParameter:
5908 case spv::OpLabel:
5909 case spv::OpPhi:
5910 case spv::OpLoad:
5911 case spv::OpSelect:
5912 case spv::OpAccessChain:
5913 case spv::OpPtrAccessChain:
5914 case spv::OpInBoundsAccessChain:
5915 case spv::OpUConvert:
5916 case spv::OpSConvert:
5917 case spv::OpConvertFToU:
5918 case spv::OpConvertFToS:
5919 case spv::OpConvertUToF:
5920 case spv::OpConvertSToF:
5921 case spv::OpFConvert:
5922 case spv::OpConvertPtrToU:
5923 case spv::OpConvertUToPtr:
5924 case spv::OpBitcast:
5925 case spv::OpIAdd:
5926 case spv::OpFAdd:
5927 case spv::OpISub:
5928 case spv::OpFSub:
5929 case spv::OpIMul:
5930 case spv::OpFMul:
5931 case spv::OpUDiv:
5932 case spv::OpSDiv:
5933 case spv::OpFDiv:
5934 case spv::OpUMod:
5935 case spv::OpSRem:
5936 case spv::OpFRem:
5937 case spv::OpBitwiseOr:
5938 case spv::OpBitwiseXor:
5939 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005940 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005941 case spv::OpShiftLeftLogical:
5942 case spv::OpShiftRightLogical:
5943 case spv::OpShiftRightArithmetic:
5944 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005945 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005946 case spv::OpCompositeExtract:
5947 case spv::OpVectorExtractDynamic:
5948 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005949 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005950 case spv::OpVectorInsertDynamic:
5951 case spv::OpVectorShuffle:
5952 case spv::OpIEqual:
5953 case spv::OpINotEqual:
5954 case spv::OpUGreaterThan:
5955 case spv::OpUGreaterThanEqual:
5956 case spv::OpULessThan:
5957 case spv::OpULessThanEqual:
5958 case spv::OpSGreaterThan:
5959 case spv::OpSGreaterThanEqual:
5960 case spv::OpSLessThan:
5961 case spv::OpSLessThanEqual:
5962 case spv::OpFOrdEqual:
5963 case spv::OpFOrdGreaterThan:
5964 case spv::OpFOrdGreaterThanEqual:
5965 case spv::OpFOrdLessThan:
5966 case spv::OpFOrdLessThanEqual:
5967 case spv::OpFOrdNotEqual:
5968 case spv::OpFUnordEqual:
5969 case spv::OpFUnordGreaterThan:
5970 case spv::OpFUnordGreaterThanEqual:
5971 case spv::OpFUnordLessThan:
5972 case spv::OpFUnordLessThanEqual:
5973 case spv::OpFUnordNotEqual:
5974 case spv::OpSampledImage:
5975 case spv::OpFunctionCall:
5976 case spv::OpConstantTrue:
5977 case spv::OpConstantFalse:
5978 case spv::OpConstant:
5979 case spv::OpSpecConstant:
5980 case spv::OpConstantComposite:
5981 case spv::OpSpecConstantComposite:
5982 case spv::OpConstantNull:
5983 case spv::OpLogicalOr:
5984 case spv::OpLogicalAnd:
5985 case spv::OpLogicalNot:
5986 case spv::OpLogicalNotEqual:
5987 case spv::OpUndef:
5988 case spv::OpIsInf:
5989 case spv::OpIsNan:
5990 case spv::OpAny:
5991 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005992 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005993 case spv::OpAtomicIAdd:
5994 case spv::OpAtomicISub:
5995 case spv::OpAtomicExchange:
5996 case spv::OpAtomicIIncrement:
5997 case spv::OpAtomicIDecrement:
5998 case spv::OpAtomicCompareExchange:
5999 case spv::OpAtomicUMin:
6000 case spv::OpAtomicSMin:
6001 case spv::OpAtomicUMax:
6002 case spv::OpAtomicSMax:
6003 case spv::OpAtomicAnd:
6004 case spv::OpAtomicOr:
6005 case spv::OpAtomicXor:
6006 case spv::OpDot: {
6007 PrintResID(Inst);
6008 out << " = ";
6009 PrintOpcode(Inst);
6010 for (uint32_t i = 0; i < Ops.size(); i++) {
6011 out << " ";
6012 PrintOperand(Ops[i]);
6013 }
6014 out << "\n";
6015 break;
6016 }
6017 }
6018 }
6019}
6020
6021void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006022 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006023}
6024
6025void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6026 WriteOneWord(Inst->getResultID());
6027}
6028
6029void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6030 // High 16 bit : Word Count
6031 // Low 16 bit : Opcode
6032 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006033 const uint32_t count = Inst->getWordCount();
6034 if (count > 65535) {
6035 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6036 llvm_unreachable("Word count too high");
6037 }
David Neto22f144c2017-06-12 14:26:21 -04006038 Word |= Inst->getWordCount() << 16;
6039 WriteOneWord(Word);
6040}
6041
6042void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6043 SPIRVOperandType OpTy = Op->getType();
6044 switch (OpTy) {
6045 default: {
6046 llvm_unreachable("Unsupported SPIRV Operand Type???");
6047 break;
6048 }
6049 case SPIRVOperandType::NUMBERID: {
6050 WriteOneWord(Op->getNumID());
6051 break;
6052 }
6053 case SPIRVOperandType::LITERAL_STRING: {
6054 std::string Str = Op->getLiteralStr();
6055 const char *Data = Str.c_str();
6056 size_t WordSize = Str.size() / 4;
6057 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6058 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6059 }
6060
6061 uint32_t Remainder = Str.size() % 4;
6062 uint32_t LastWord = 0;
6063 if (Remainder) {
6064 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6065 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6066 }
6067 }
6068
6069 WriteOneWord(LastWord);
6070 break;
6071 }
6072 case SPIRVOperandType::LITERAL_INTEGER:
6073 case SPIRVOperandType::LITERAL_FLOAT: {
6074 auto LiteralNum = Op->getLiteralNum();
6075 // TODO: Handle LiteranNum carefully.
6076 for (auto Word : LiteralNum) {
6077 WriteOneWord(Word);
6078 }
6079 break;
6080 }
6081 }
6082}
6083
6084void SPIRVProducerPass::WriteSPIRVBinary() {
6085 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6086
6087 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006088 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006089 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6090
6091 switch (Opcode) {
6092 default: {
David Neto5c22a252018-03-15 16:07:41 -04006093 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006094 llvm_unreachable("Unsupported SPIRV instruction");
6095 break;
6096 }
6097 case spv::OpCapability:
6098 case spv::OpExtension:
6099 case spv::OpMemoryModel:
6100 case spv::OpEntryPoint:
6101 case spv::OpExecutionMode:
6102 case spv::OpSource:
6103 case spv::OpDecorate:
6104 case spv::OpMemberDecorate:
6105 case spv::OpBranch:
6106 case spv::OpBranchConditional:
6107 case spv::OpSelectionMerge:
6108 case spv::OpLoopMerge:
6109 case spv::OpStore:
6110 case spv::OpImageWrite:
6111 case spv::OpReturnValue:
6112 case spv::OpControlBarrier:
6113 case spv::OpMemoryBarrier:
6114 case spv::OpReturn:
6115 case spv::OpFunctionEnd:
6116 case spv::OpCopyMemory: {
6117 WriteWordCountAndOpcode(Inst);
6118 for (uint32_t i = 0; i < Ops.size(); i++) {
6119 WriteOperand(Ops[i]);
6120 }
6121 break;
6122 }
6123 case spv::OpTypeBool:
6124 case spv::OpTypeVoid:
6125 case spv::OpTypeSampler:
6126 case spv::OpLabel:
6127 case spv::OpExtInstImport:
6128 case spv::OpTypePointer:
6129 case spv::OpTypeRuntimeArray:
6130 case spv::OpTypeStruct:
6131 case spv::OpTypeImage:
6132 case spv::OpTypeSampledImage:
6133 case spv::OpTypeInt:
6134 case spv::OpTypeFloat:
6135 case spv::OpTypeArray:
6136 case spv::OpTypeVector:
6137 case spv::OpTypeFunction: {
6138 WriteWordCountAndOpcode(Inst);
6139 WriteResultID(Inst);
6140 for (uint32_t i = 0; i < Ops.size(); i++) {
6141 WriteOperand(Ops[i]);
6142 }
6143 break;
6144 }
6145 case spv::OpFunction:
6146 case spv::OpFunctionParameter:
6147 case spv::OpAccessChain:
6148 case spv::OpPtrAccessChain:
6149 case spv::OpInBoundsAccessChain:
6150 case spv::OpUConvert:
6151 case spv::OpSConvert:
6152 case spv::OpConvertFToU:
6153 case spv::OpConvertFToS:
6154 case spv::OpConvertUToF:
6155 case spv::OpConvertSToF:
6156 case spv::OpFConvert:
6157 case spv::OpConvertPtrToU:
6158 case spv::OpConvertUToPtr:
6159 case spv::OpBitcast:
6160 case spv::OpIAdd:
6161 case spv::OpFAdd:
6162 case spv::OpISub:
6163 case spv::OpFSub:
6164 case spv::OpIMul:
6165 case spv::OpFMul:
6166 case spv::OpUDiv:
6167 case spv::OpSDiv:
6168 case spv::OpFDiv:
6169 case spv::OpUMod:
6170 case spv::OpSRem:
6171 case spv::OpFRem:
6172 case spv::OpBitwiseOr:
6173 case spv::OpBitwiseXor:
6174 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006175 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006176 case spv::OpShiftLeftLogical:
6177 case spv::OpShiftRightLogical:
6178 case spv::OpShiftRightArithmetic:
6179 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006180 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006181 case spv::OpCompositeExtract:
6182 case spv::OpVectorExtractDynamic:
6183 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006184 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006185 case spv::OpVectorInsertDynamic:
6186 case spv::OpVectorShuffle:
6187 case spv::OpIEqual:
6188 case spv::OpINotEqual:
6189 case spv::OpUGreaterThan:
6190 case spv::OpUGreaterThanEqual:
6191 case spv::OpULessThan:
6192 case spv::OpULessThanEqual:
6193 case spv::OpSGreaterThan:
6194 case spv::OpSGreaterThanEqual:
6195 case spv::OpSLessThan:
6196 case spv::OpSLessThanEqual:
6197 case spv::OpFOrdEqual:
6198 case spv::OpFOrdGreaterThan:
6199 case spv::OpFOrdGreaterThanEqual:
6200 case spv::OpFOrdLessThan:
6201 case spv::OpFOrdLessThanEqual:
6202 case spv::OpFOrdNotEqual:
6203 case spv::OpFUnordEqual:
6204 case spv::OpFUnordGreaterThan:
6205 case spv::OpFUnordGreaterThanEqual:
6206 case spv::OpFUnordLessThan:
6207 case spv::OpFUnordLessThanEqual:
6208 case spv::OpFUnordNotEqual:
6209 case spv::OpExtInst:
6210 case spv::OpIsInf:
6211 case spv::OpIsNan:
6212 case spv::OpAny:
6213 case spv::OpAll:
6214 case spv::OpUndef:
6215 case spv::OpConstantNull:
6216 case spv::OpLogicalOr:
6217 case spv::OpLogicalAnd:
6218 case spv::OpLogicalNot:
6219 case spv::OpLogicalNotEqual:
6220 case spv::OpConstantComposite:
6221 case spv::OpSpecConstantComposite:
6222 case spv::OpConstantTrue:
6223 case spv::OpConstantFalse:
6224 case spv::OpConstant:
6225 case spv::OpSpecConstant:
6226 case spv::OpVariable:
6227 case spv::OpFunctionCall:
6228 case spv::OpSampledImage:
6229 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006230 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006231 case spv::OpSelect:
6232 case spv::OpPhi:
6233 case spv::OpLoad:
6234 case spv::OpAtomicIAdd:
6235 case spv::OpAtomicISub:
6236 case spv::OpAtomicExchange:
6237 case spv::OpAtomicIIncrement:
6238 case spv::OpAtomicIDecrement:
6239 case spv::OpAtomicCompareExchange:
6240 case spv::OpAtomicUMin:
6241 case spv::OpAtomicSMin:
6242 case spv::OpAtomicUMax:
6243 case spv::OpAtomicSMax:
6244 case spv::OpAtomicAnd:
6245 case spv::OpAtomicOr:
6246 case spv::OpAtomicXor:
6247 case spv::OpDot: {
6248 WriteWordCountAndOpcode(Inst);
6249 WriteOperand(Ops[0]);
6250 WriteResultID(Inst);
6251 for (uint32_t i = 1; i < Ops.size(); i++) {
6252 WriteOperand(Ops[i]);
6253 }
6254 break;
6255 }
6256 }
6257 }
6258}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006259
alan-bakerb6b09dc2018-11-08 16:59:28 -05006260bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006261 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006262 case Type::HalfTyID:
6263 case Type::FloatTyID:
6264 case Type::DoubleTyID:
6265 case Type::IntegerTyID:
6266 case Type::VectorTyID:
6267 return true;
6268 case Type::PointerTyID: {
6269 const PointerType *pointer_type = cast<PointerType>(type);
6270 if (pointer_type->getPointerAddressSpace() !=
6271 AddressSpace::UniformConstant) {
6272 auto pointee_type = pointer_type->getPointerElementType();
6273 if (pointee_type->isStructTy() &&
6274 cast<StructType>(pointee_type)->isOpaque()) {
6275 // Images and samplers are not nullable.
6276 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006277 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006278 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006279 return true;
6280 }
6281 case Type::ArrayTyID:
6282 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6283 case Type::StructTyID: {
6284 const StructType *struct_type = cast<StructType>(type);
6285 // Images and samplers are not nullable.
6286 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006287 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006288 for (const auto element : struct_type->elements()) {
6289 if (!IsTypeNullable(element))
6290 return false;
6291 }
6292 return true;
6293 }
6294 default:
6295 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006296 }
6297}
Alan Bakerfcda9482018-10-02 17:09:59 -04006298
6299void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6300 if (auto *offsets_md =
6301 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6302 // Metdata is stored as key-value pair operands. The first element of each
6303 // operand is the type and the second is a vector of offsets.
6304 for (const auto *operand : offsets_md->operands()) {
6305 const auto *pair = cast<MDTuple>(operand);
6306 auto *type =
6307 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6308 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6309 std::vector<uint32_t> offsets;
6310 for (const Metadata *offset_md : offset_vector->operands()) {
6311 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006312 offsets.push_back(static_cast<uint32_t>(
6313 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006314 }
6315 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6316 }
6317 }
6318
6319 if (auto *sizes_md =
6320 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6321 // Metadata is stored as key-value pair operands. The first element of each
6322 // operand is the type and the second is a triple of sizes: type size in
6323 // bits, store size and alloc size.
6324 for (const auto *operand : sizes_md->operands()) {
6325 const auto *pair = cast<MDTuple>(operand);
6326 auto *type =
6327 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6328 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6329 uint64_t type_size_in_bits =
6330 cast<ConstantInt>(
6331 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6332 ->getZExtValue();
6333 uint64_t type_store_size =
6334 cast<ConstantInt>(
6335 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6336 ->getZExtValue();
6337 uint64_t type_alloc_size =
6338 cast<ConstantInt>(
6339 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6340 ->getZExtValue();
6341 RemappedUBOTypeSizes.insert(std::make_pair(
6342 type, std::make_tuple(type_size_in_bits, type_store_size,
6343 type_alloc_size)));
6344 }
6345 }
6346}
6347
6348uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6349 const DataLayout &DL) {
6350 auto iter = RemappedUBOTypeSizes.find(type);
6351 if (iter != RemappedUBOTypeSizes.end()) {
6352 return std::get<0>(iter->second);
6353 }
6354
6355 return DL.getTypeSizeInBits(type);
6356}
6357
6358uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6359 auto iter = RemappedUBOTypeSizes.find(type);
6360 if (iter != RemappedUBOTypeSizes.end()) {
6361 return std::get<1>(iter->second);
6362 }
6363
6364 return DL.getTypeStoreSize(type);
6365}
6366
6367uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6368 auto iter = RemappedUBOTypeSizes.find(type);
6369 if (iter != RemappedUBOTypeSizes.end()) {
6370 return std::get<2>(iter->second);
6371 }
6372
6373 return DL.getTypeAllocSize(type);
6374}