blob: b7df0c37c2d90e7fd412bcaeb5ea224c3ddcc906 [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),
alan-baker5b86ed72019-02-15 08:26:50 -0500229 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
230 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
231 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
232 }
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500286 bool hasVariablePointers() {
alan-baker5b86ed72019-02-15 08:26:50 -0500287 return HasVariablePointers;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 };
David Neto22f144c2017-06-12 14:26:21 -0400289 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
291 return samplerMap;
292 }
David Neto22f144c2017-06-12 14:26:21 -0400293 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
294 return GlobalConstFuncTypeMap;
295 }
296 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
297 return GlobalConstArgumentSet;
298 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500299 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400300
David Netoc6f3ab22018-04-06 18:02:31 -0400301 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500302 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
303 // *not* be converted to a storage buffer, replace each such global variable
304 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindGlobalConstVars(Module &M, const DataLayout &DL);
306 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
307 // ModuleOrderedResourceVars.
308 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400309 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400310 bool FindExtInst(Module &M);
311 void FindTypePerGlobalVar(GlobalVariable &GV);
312 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400313 void FindTypesForSamplerMap(Module &M);
314 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
316 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400317 void FindType(Type *Ty);
318 void FindConstantPerGlobalVar(GlobalVariable &GV);
319 void FindConstantPerFunc(Function &F);
320 void FindConstant(Value *V);
321 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400322 // Generates instructions for SPIR-V types corresponding to the LLVM types
323 // saved in the |Types| member. A type follows its subtypes. IDs are
324 // allocated sequentially starting with the current value of nextID, and
325 // with a type following its subtypes. Also updates nextID to just beyond
326 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400329 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400331 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400332 // Generate descriptor map entries for resource variables associated with
333 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500334 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400335 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400336 // Generate OpVariables for %clspv.resource.var.* calls.
337 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400338 void GenerateFuncPrologue(Function &F);
339 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400340 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400341 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
342 spv::Op GetSPIRVCastOpcode(Instruction &I);
343 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
344 void GenerateInstruction(Instruction &I);
345 void GenerateFuncEpilogue();
346 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500347 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400348 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400349 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
350 // have been created.
351 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400353 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400354 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400355 // Returns the GLSL extended instruction enum that the given function
356 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400357 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400358 // Returns the GLSL extended instruction enum indirectly used by the given
359 // function. That is, to implement the given function, we use an extended
360 // instruction plus one more instruction. If none, then returns the 0 value,
361 // i.e. GLSLstd4580Bad.
362 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
363 // Returns the single GLSL extended instruction used directly or
364 // indirectly by the given function call.
365 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400366 void PrintResID(SPIRVInstruction *Inst);
367 void PrintOpcode(SPIRVInstruction *Inst);
368 void PrintOperand(SPIRVOperand *Op);
369 void PrintCapability(SPIRVOperand *Op);
370 void PrintExtInst(SPIRVOperand *Op);
371 void PrintAddrModel(SPIRVOperand *Op);
372 void PrintMemModel(SPIRVOperand *Op);
373 void PrintExecModel(SPIRVOperand *Op);
374 void PrintExecMode(SPIRVOperand *Op);
375 void PrintSourceLanguage(SPIRVOperand *Op);
376 void PrintFuncCtrl(SPIRVOperand *Op);
377 void PrintStorageClass(SPIRVOperand *Op);
378 void PrintDecoration(SPIRVOperand *Op);
379 void PrintBuiltIn(SPIRVOperand *Op);
380 void PrintSelectionControl(SPIRVOperand *Op);
381 void PrintLoopControl(SPIRVOperand *Op);
382 void PrintDimensionality(SPIRVOperand *Op);
383 void PrintImageFormat(SPIRVOperand *Op);
384 void PrintMemoryAccess(SPIRVOperand *Op);
385 void PrintImageOperandsType(SPIRVOperand *Op);
386 void WriteSPIRVAssembly();
387 void WriteOneWord(uint32_t Word);
388 void WriteResultID(SPIRVInstruction *Inst);
389 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
390 void WriteOperand(SPIRVOperand *Op);
391 void WriteSPIRVBinary();
392
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500394 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400395
Alan Bakerfcda9482018-10-02 17:09:59 -0400396 // Populate UBO remapped type maps.
397 void PopulateUBOTypeMaps(Module &module);
398
399 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
400 // uses the internal map, otherwise it falls back on the data layout.
401 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
402 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
403 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
404
alan-baker5b86ed72019-02-15 08:26:50 -0500405 // Returns the base pointer of |v|.
406 Value *GetBasePointer(Value *v);
407
408 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
409 // |address_space|.
410 void setVariablePointersCapabilities(unsigned address_space);
411
412 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
413 // variable.
414 bool sameResource(Value *lhs, Value *rhs) const;
415
416 // Returns true if |inst| is phi or select that selects from the same
417 // structure (or null).
418 bool selectFromSameObject(Instruction *inst);
419
David Neto22f144c2017-06-12 14:26:21 -0400420private:
421 static char ID;
David Neto44795152017-07-13 15:45:28 -0400422 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400423 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400424
425 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
426 // convert to other formats on demand?
427
428 // When emitting a C initialization list, the WriteSPIRVBinary method
429 // will actually write its words to this vector via binaryTempOut.
430 SmallVector<char, 100> binaryTempUnderlyingVector;
431 raw_svector_ostream binaryTempOut;
432
433 // Binary output writes to this stream, which might be |out| or
434 // |binaryTempOut|. It's the latter when we really want to write a C
435 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500436 raw_pwrite_stream* binaryOut;
437 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400438 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400439 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400440 uint64_t patchBoundOffset;
441 uint32_t nextID;
442
David Neto19a1bad2017-08-25 15:01:41 -0400443 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400444 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400445 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400446 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400447 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400448 TypeList Types;
449 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400450 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400451 ValueMapType ValueMap;
452 ValueMapType AllocatedValueMap;
453 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400454
David Neto22f144c2017-06-12 14:26:21 -0400455 EntryPointVecType EntryPointVec;
456 DeferredInstVecType DeferredInstVec;
457 ValueList EntryPointInterfacesVec;
458 uint32_t OpExtInstImportID;
459 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500460 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400461 bool HasVariablePointers;
462 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500463 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700464
465 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700466 // will map F's type to (G, index of the parameter), where in a first phase
467 // G is F's type. During FindTypePerFunc, G will be changed to F's type
468 // but replacing the pointer-to-constant parameter with
469 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700470 // TODO(dneto): This doesn't seem general enough? A function might have
471 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400472 GlobalConstFuncMapType GlobalConstFuncTypeMap;
473 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400474 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700475 // or array types, and which point into transparent memory (StorageBuffer
476 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400477 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700478 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400479
480 // This is truly ugly, but works around what look like driver bugs.
481 // For get_local_size, an earlier part of the flow has created a module-scope
482 // variable in Private address space to hold the value for the workgroup
483 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
484 // When this is present, save the IDs of the initializer value and variable
485 // in these two variables. We only ever do a vector load from it, and
486 // when we see one of those, substitute just the value of the intializer.
487 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700488 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400489 uint32_t WorkgroupSizeValueID;
490 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400491
David Neto862b7d82018-06-14 18:48:37 -0400492 // Bookkeeping for mapping kernel arguments to resource variables.
493 struct ResourceVarInfo {
494 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
495 Function *fn, clspv::ArgKind arg_kind_arg)
496 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
497 var_fn(fn), arg_kind(arg_kind_arg),
498 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
499 const int index; // Index into ResourceVarInfoList
500 const unsigned descriptor_set;
501 const unsigned binding;
502 Function *const var_fn; // The @clspv.resource.var.* function.
503 const clspv::ArgKind arg_kind;
504 const unsigned addr_space; // The LLVM address space
505 // The SPIR-V ID of the OpVariable. Not populated at construction time.
506 uint32_t var_id = 0;
507 };
508 // A list of resource var info. Each one correponds to a module-scope
509 // resource variable we will have to create. Resource var indices are
510 // indices into this vector.
511 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
512 // This is a vector of pointers of all the resource vars, but ordered by
513 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500514 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400515 // Map a function to the ordered list of resource variables it uses, one for
516 // each argument. If an argument does not use a resource variable, it
517 // will have a null pointer entry.
518 using FunctionToResourceVarsMapType =
519 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
520 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
521
522 // What LLVM types map to SPIR-V types needing layout? These are the
523 // arrays and structures supporting storage buffers and uniform buffers.
524 TypeList TypesNeedingLayout;
525 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
526 UniqueVector<StructType *> StructTypesNeedingBlock;
527 // For a call that represents a load from an opaque type (samplers, images),
528 // map it to the variable id it should load from.
529 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700530
Alan Baker202c8c72018-08-13 13:47:44 -0400531 // One larger than the maximum used SpecId for pointer-to-local arguments.
532 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400533 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500534 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400535 LocalArgList LocalArgs;
536 // Information about a pointer-to-local argument.
537 struct LocalArgInfo {
538 // The SPIR-V ID of the array variable.
539 uint32_t variable_id;
540 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500541 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400542 // The ID of the array type.
543 uint32_t array_size_id;
544 // The ID of the array type.
545 uint32_t array_type_id;
546 // The ID of the pointer to the array type.
547 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400548 // The specialization constant ID of the array size.
549 int spec_id;
550 };
Alan Baker202c8c72018-08-13 13:47:44 -0400551 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500552 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400553 // A mapping from SpecId to its LocalArgInfo.
554 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400555 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500556 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500558 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
559 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400560
561 // The ID of 32-bit integer zero constant. This is only valid after
562 // GenerateSPIRVConstants has run.
563 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400564};
565
566char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400567
alan-bakerb6b09dc2018-11-08 16:59:28 -0500568} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400569
570namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500571ModulePass *createSPIRVProducerPass(
572 raw_pwrite_stream &out,
573 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
574 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
575 bool outputCInitList) {
576 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
577 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400578}
David Netoc2c368d2017-06-30 16:50:17 -0400579} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400580
581bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400582 binaryOut = outputCInitList ? &binaryTempOut : &out;
583
David Neto257c3892018-04-11 13:19:45 -0400584 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
585
Alan Bakerfcda9482018-10-02 17:09:59 -0400586 PopulateUBOTypeMaps(module);
587
David Neto22f144c2017-06-12 14:26:21 -0400588 // SPIR-V always begins with its header information
589 outputHeader();
590
David Netoc6f3ab22018-04-06 18:02:31 -0400591 const DataLayout &DL = module.getDataLayout();
592
David Neto22f144c2017-06-12 14:26:21 -0400593 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400594 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400595
David Neto22f144c2017-06-12 14:26:21 -0400596 // Collect information on global variables too.
597 for (GlobalVariable &GV : module.globals()) {
598 // If the GV is one of our special __spirv_* variables, remove the
599 // initializer as it was only placed there to force LLVM to not throw the
600 // value away.
601 if (GV.getName().startswith("__spirv_")) {
602 GV.setInitializer(nullptr);
603 }
604
605 // Collect types' information from global variable.
606 FindTypePerGlobalVar(GV);
607
608 // Collect constant information from global variable.
609 FindConstantPerGlobalVar(GV);
610
611 // If the variable is an input, entry points need to know about it.
612 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400613 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400614 }
615 }
616
617 // If there are extended instructions, generate OpExtInstImport.
618 if (FindExtInst(module)) {
619 GenerateExtInstImport();
620 }
621
622 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400623 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400624
625 // Generate SPIRV constants.
626 GenerateSPIRVConstants();
627
628 // If we have a sampler map, we might have literal samplers to generate.
629 if (0 < getSamplerMap().size()) {
630 GenerateSamplers(module);
631 }
632
633 // Generate SPIRV variables.
634 for (GlobalVariable &GV : module.globals()) {
635 GenerateGlobalVar(GV);
636 }
David Neto862b7d82018-06-14 18:48:37 -0400637 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400638 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400639
640 // Generate SPIRV instructions for each function.
641 for (Function &F : module) {
642 if (F.isDeclaration()) {
643 continue;
644 }
645
David Neto862b7d82018-06-14 18:48:37 -0400646 GenerateDescriptorMapInfo(DL, F);
647
David Neto22f144c2017-06-12 14:26:21 -0400648 // Generate Function Prologue.
649 GenerateFuncPrologue(F);
650
651 // Generate SPIRV instructions for function body.
652 GenerateFuncBody(F);
653
654 // Generate Function Epilogue.
655 GenerateFuncEpilogue();
656 }
657
658 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400659 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400660
661 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400662 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400663
664 if (outputAsm) {
665 WriteSPIRVAssembly();
666 } else {
667 WriteSPIRVBinary();
668 }
669
670 // We need to patch the SPIR-V header to set bound correctly.
671 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400672
673 if (outputCInitList) {
674 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400675 std::ostringstream os;
676
David Neto57fb0b92017-08-04 15:35:09 -0400677 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400678 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400679 os << ",\n";
680 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400681 first = false;
682 };
683
684 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400685 const std::string str(binaryTempOut.str());
686 for (unsigned i = 0; i < str.size(); i += 4) {
687 const uint32_t a = static_cast<unsigned char>(str[i]);
688 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
689 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
690 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
691 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400692 }
693 os << "}\n";
694 out << os.str();
695 }
696
David Neto22f144c2017-06-12 14:26:21 -0400697 return false;
698}
699
700void SPIRVProducerPass::outputHeader() {
701 if (outputAsm) {
702 // for ASM output the header goes into 5 comments at the beginning of the
703 // file
704 out << "; SPIR-V\n";
705
706 // the major version number is in the 2nd highest byte
707 const uint32_t major = (spv::Version >> 16) & 0xFF;
708
709 // the minor version number is in the 2nd lowest byte
710 const uint32_t minor = (spv::Version >> 8) & 0xFF;
711 out << "; Version: " << major << "." << minor << "\n";
712
713 // use Codeplay's vendor ID
714 out << "; Generator: Codeplay; 0\n";
715
716 out << "; Bound: ";
717
718 // we record where we need to come back to and patch in the bound value
719 patchBoundOffset = out.tell();
720
721 // output one space per digit for the max size of a 32 bit unsigned integer
722 // (which is the maximum ID we could possibly be using)
723 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
724 out << " ";
725 }
726
727 out << "\n";
728
729 out << "; Schema: 0\n";
730 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400731 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500732 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500734 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400735
736 // use Codeplay's vendor ID
737 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400738 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400739
740 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400741 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400742
743 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400744 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400745
746 // output the schema (reserved for use and must be 0)
747 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400748 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400749 }
750}
751
752void SPIRVProducerPass::patchHeader() {
753 if (outputAsm) {
754 // get the string representation of the max bound used (nextID will be the
755 // max ID used)
756 auto asString = std::to_string(nextID);
757 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
758 } else {
759 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400760 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
761 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400762 }
763}
764
David Netoc6f3ab22018-04-06 18:02:31 -0400765void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400766 // This function generates LLVM IR for function such as global variable for
767 // argument, constant and pointer type for argument access. These information
768 // is artificial one because we need Vulkan SPIR-V output. This function is
769 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400770 LLVMContext &Context = M.getContext();
771
David Neto862b7d82018-06-14 18:48:37 -0400772 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400773
David Neto862b7d82018-06-14 18:48:37 -0400774 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400775
776 bool HasWorkGroupBuiltin = false;
777 for (GlobalVariable &GV : M.globals()) {
778 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
779 if (spv::BuiltInWorkgroupSize == BuiltinType) {
780 HasWorkGroupBuiltin = true;
781 }
782 }
783
David Neto862b7d82018-06-14 18:48:37 -0400784 FindTypesForSamplerMap(M);
785 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400786 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400787
David Neto862b7d82018-06-14 18:48:37 -0400788 // TODO(dneto): Delete the next 3 vars.
789
790 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400791 // Map kernel functions to their ordinal number in the compilation unit.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500792 UniqueVector<Function *> KernelOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400793
794 // Map the global variables created for kernel args to their creation
795 // order.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500796 UniqueVector<GlobalVariable *> KernelArgVarOrdinal;
David Neto26aaf622017-10-23 18:11:53 -0400797
David Neto862b7d82018-06-14 18:48:37 -0400798 // For each kernel argument type, record the kernel arg global resource
799 // variables generated for that type, the function in which that variable
800 // was most recently used, and the binding number it took. For
801 // reproducibility, we track things by ordinal number (rather than pointer),
802 // and we use a std::set rather than DenseSet since std::set maintains an
803 // ordering. Each tuple is the ordinals of the kernel function, the binding
804 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400805 //
806 // This table lets us reuse module-scope StorageBuffer variables between
807 // different kernels.
808 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
809 GVarsForType;
810
David Neto862b7d82018-06-14 18:48:37 -0400811 // These function calls need a <2 x i32> as an intermediate result but not
812 // the final result.
813 std::unordered_set<std::string> NeedsIVec2{
814 "_Z15get_image_width14ocl_image2d_ro",
815 "_Z15get_image_width14ocl_image2d_wo",
816 "_Z16get_image_height14ocl_image2d_ro",
817 "_Z16get_image_height14ocl_image2d_wo",
818 };
819
David Neto22f144c2017-06-12 14:26:21 -0400820 for (Function &F : M) {
821 // Handle kernel function first.
822 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
823 continue;
824 }
David Neto26aaf622017-10-23 18:11:53 -0400825 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400826
827 for (BasicBlock &BB : F) {
828 for (Instruction &I : BB) {
829 if (I.getOpcode() == Instruction::ZExt ||
830 I.getOpcode() == Instruction::SExt ||
831 I.getOpcode() == Instruction::UIToFP) {
832 // If there is zext with i1 type, it will be changed to OpSelect. The
833 // OpSelect needs constant 0 and 1 so the constants are added here.
834
835 auto OpTy = I.getOperand(0)->getType();
836
Kévin Petit24272b62018-10-18 19:16:12 +0000837 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400838 if (I.getOpcode() == Instruction::ZExt) {
839 APInt One(32, 1);
840 FindConstant(Constant::getNullValue(I.getType()));
841 FindConstant(Constant::getIntegerValue(I.getType(), One));
842 } else if (I.getOpcode() == Instruction::SExt) {
843 APInt MinusOne(32, UINT64_MAX, true);
844 FindConstant(Constant::getNullValue(I.getType()));
845 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
846 } else {
847 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
848 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
849 }
850 }
851 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400852 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400853
854 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400855 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400856 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400857 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400858 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
859 TypeMapType &OpImageTypeMap = getImageTypeMap();
860 Type *ImageTy =
861 Call->getArgOperand(0)->getType()->getPointerElementType();
862 OpImageTypeMap[ImageTy] = 0;
863
864 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
865 }
David Neto5c22a252018-03-15 16:07:41 -0400866
David Neto862b7d82018-06-14 18:48:37 -0400867 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400868 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
869 }
David Neto22f144c2017-06-12 14:26:21 -0400870 }
871 }
872 }
873
David Neto22f144c2017-06-12 14:26:21 -0400874 if (const MDNode *MD =
875 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
876 // We generate constants if the WorkgroupSize builtin is being used.
877 if (HasWorkGroupBuiltin) {
878 // Collect constant information for work group size.
879 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
880 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
881 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
882 }
883 }
884
David Neto22f144c2017-06-12 14:26:21 -0400885 // Collect types' information from function.
886 FindTypePerFunc(F);
887
888 // Collect constant information from function.
889 FindConstantPerFunc(F);
890 }
891
892 for (Function &F : M) {
893 // Handle non-kernel functions.
894 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
895 continue;
896 }
897
898 for (BasicBlock &BB : F) {
899 for (Instruction &I : BB) {
900 if (I.getOpcode() == Instruction::ZExt ||
901 I.getOpcode() == Instruction::SExt ||
902 I.getOpcode() == Instruction::UIToFP) {
903 // If there is zext with i1 type, it will be changed to OpSelect. The
904 // OpSelect needs constant 0 and 1 so the constants are added here.
905
906 auto OpTy = I.getOperand(0)->getType();
907
Kévin Petit24272b62018-10-18 19:16:12 +0000908 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400909 if (I.getOpcode() == Instruction::ZExt) {
910 APInt One(32, 1);
911 FindConstant(Constant::getNullValue(I.getType()));
912 FindConstant(Constant::getIntegerValue(I.getType(), One));
913 } else if (I.getOpcode() == Instruction::SExt) {
914 APInt MinusOne(32, UINT64_MAX, true);
915 FindConstant(Constant::getNullValue(I.getType()));
916 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
917 } else {
918 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
919 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
920 }
921 }
922 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
923 Function *Callee = Call->getCalledFunction();
924
925 // Handle image type specially.
926 if (Callee->getName().equals(
927 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
928 Callee->getName().equals(
929 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
930 TypeMapType &OpImageTypeMap = getImageTypeMap();
931 Type *ImageTy =
932 Call->getArgOperand(0)->getType()->getPointerElementType();
933 OpImageTypeMap[ImageTy] = 0;
934
935 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
936 }
937 }
938 }
939 }
940
941 if (M.getTypeByName("opencl.image2d_ro_t") ||
942 M.getTypeByName("opencl.image2d_wo_t") ||
943 M.getTypeByName("opencl.image3d_ro_t") ||
944 M.getTypeByName("opencl.image3d_wo_t")) {
945 // Assume Image type's sampled type is float type.
946 FindType(Type::getFloatTy(Context));
947 }
948
949 // Collect types' information from function.
950 FindTypePerFunc(F);
951
952 // Collect constant information from function.
953 FindConstantPerFunc(F);
954 }
955}
956
David Neto862b7d82018-06-14 18:48:37 -0400957void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
958 SmallVector<GlobalVariable *, 8> GVList;
959 SmallVector<GlobalVariable *, 8> DeadGVList;
960 for (GlobalVariable &GV : M.globals()) {
961 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
962 if (GV.use_empty()) {
963 DeadGVList.push_back(&GV);
964 } else {
965 GVList.push_back(&GV);
966 }
967 }
968 }
969
970 // Remove dead global __constant variables.
971 for (auto GV : DeadGVList) {
972 GV->eraseFromParent();
973 }
974 DeadGVList.clear();
975
976 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
977 // For now, we only support a single storage buffer.
978 if (GVList.size() > 0) {
979 assert(GVList.size() == 1);
980 const auto *GV = GVList[0];
981 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400982 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400983 const size_t kConstantMaxSize = 65536;
984 if (constants_byte_size > kConstantMaxSize) {
985 outs() << "Max __constant capacity of " << kConstantMaxSize
986 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
987 llvm_unreachable("Max __constant capacity exceeded");
988 }
989 }
990 } else {
991 // Change global constant variable's address space to ModuleScopePrivate.
992 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
993 for (auto GV : GVList) {
994 // Create new gv with ModuleScopePrivate address space.
995 Type *NewGVTy = GV->getType()->getPointerElementType();
996 GlobalVariable *NewGV = new GlobalVariable(
997 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
998 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
999 NewGV->takeName(GV);
1000
1001 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1002 SmallVector<User *, 8> CandidateUsers;
1003
1004 auto record_called_function_type_as_user =
1005 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1006 // Find argument index.
1007 unsigned index = 0;
1008 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1009 if (gv == call->getOperand(i)) {
1010 // TODO(dneto): Should we break here?
1011 index = i;
1012 }
1013 }
1014
1015 // Record function type with global constant.
1016 GlobalConstFuncTyMap[call->getFunctionType()] =
1017 std::make_pair(call->getFunctionType(), index);
1018 };
1019
1020 for (User *GVU : GVUsers) {
1021 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1022 record_called_function_type_as_user(GV, Call);
1023 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1024 // Check GEP users.
1025 for (User *GEPU : GEP->users()) {
1026 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1027 record_called_function_type_as_user(GEP, GEPCall);
1028 }
1029 }
1030 }
1031
1032 CandidateUsers.push_back(GVU);
1033 }
1034
1035 for (User *U : CandidateUsers) {
1036 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001037 if (!isa<Constant>(U)) {
1038 // #254: Can't change operands of a constant, but this shouldn't be
1039 // something that sticks around in the module.
1040 U->replaceUsesOfWith(GV, NewGV);
1041 }
David Neto862b7d82018-06-14 18:48:37 -04001042 }
1043
1044 // Delete original gv.
1045 GV->eraseFromParent();
1046 }
1047 }
1048}
1049
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001050void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001051 ResourceVarInfoList.clear();
1052 FunctionToResourceVarsMap.clear();
1053 ModuleOrderedResourceVars.reset();
1054 // Normally, there is one resource variable per clspv.resource.var.*
1055 // function, since that is unique'd by arg type and index. By design,
1056 // we can share these resource variables across kernels because all
1057 // kernels use the same descriptor set.
1058 //
1059 // But if the user requested distinct descriptor sets per kernel, then
1060 // the descriptor allocator has made different (set,binding) pairs for
1061 // the same (type,arg_index) pair. Since we can decorate a resource
1062 // variable with only exactly one DescriptorSet and Binding, we are
1063 // forced in this case to make distinct resource variables whenever
1064 // the same clspv.reource.var.X function is seen with disintct
1065 // (set,binding) values.
1066 const bool always_distinct_sets =
1067 clspv::Option::DistinctKernelDescriptorSets();
1068 for (Function &F : M) {
1069 // Rely on the fact the resource var functions have a stable ordering
1070 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001071 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001072 // Find all calls to this function with distinct set and binding pairs.
1073 // Save them in ResourceVarInfoList.
1074
1075 // Determine uniqueness of the (set,binding) pairs only withing this
1076 // one resource-var builtin function.
1077 using SetAndBinding = std::pair<unsigned, unsigned>;
1078 // Maps set and binding to the resource var info.
1079 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1080 bool first_use = true;
1081 for (auto &U : F.uses()) {
1082 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1083 const auto set = unsigned(
1084 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1085 const auto binding = unsigned(
1086 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1087 const auto arg_kind = clspv::ArgKind(
1088 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1089 const auto arg_index = unsigned(
1090 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1091
1092 // Find or make the resource var info for this combination.
1093 ResourceVarInfo *rv = nullptr;
1094 if (always_distinct_sets) {
1095 // Make a new resource var any time we see a different
1096 // (set,binding) pair.
1097 SetAndBinding key{set, binding};
1098 auto where = set_and_binding_map.find(key);
1099 if (where == set_and_binding_map.end()) {
1100 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1101 binding, &F, arg_kind);
1102 ResourceVarInfoList.emplace_back(rv);
1103 set_and_binding_map[key] = rv;
1104 } else {
1105 rv = where->second;
1106 }
1107 } else {
1108 // The default is to make exactly one resource for each
1109 // clspv.resource.var.* function.
1110 if (first_use) {
1111 first_use = false;
1112 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1113 binding, &F, arg_kind);
1114 ResourceVarInfoList.emplace_back(rv);
1115 } else {
1116 rv = ResourceVarInfoList.back().get();
1117 }
1118 }
1119
1120 // Now populate FunctionToResourceVarsMap.
1121 auto &mapping =
1122 FunctionToResourceVarsMap[call->getParent()->getParent()];
1123 while (mapping.size() <= arg_index) {
1124 mapping.push_back(nullptr);
1125 }
1126 mapping[arg_index] = rv;
1127 }
1128 }
1129 }
1130 }
1131
1132 // Populate ModuleOrderedResourceVars.
1133 for (Function &F : M) {
1134 auto where = FunctionToResourceVarsMap.find(&F);
1135 if (where != FunctionToResourceVarsMap.end()) {
1136 for (auto &rv : where->second) {
1137 if (rv != nullptr) {
1138 ModuleOrderedResourceVars.insert(rv);
1139 }
1140 }
1141 }
1142 }
1143 if (ShowResourceVars) {
1144 for (auto *info : ModuleOrderedResourceVars) {
1145 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1146 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1147 << "\n";
1148 }
1149 }
1150}
1151
David Neto22f144c2017-06-12 14:26:21 -04001152bool SPIRVProducerPass::FindExtInst(Module &M) {
1153 LLVMContext &Context = M.getContext();
1154 bool HasExtInst = false;
1155
1156 for (Function &F : M) {
1157 for (BasicBlock &BB : F) {
1158 for (Instruction &I : BB) {
1159 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1160 Function *Callee = Call->getCalledFunction();
1161 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001162 auto callee_name = Callee->getName();
1163 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1164 const glsl::ExtInst IndirectEInst =
1165 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001166
David Neto3fbb4072017-10-16 11:28:14 -04001167 HasExtInst |=
1168 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1169
1170 if (IndirectEInst) {
1171 // Register extra constants if needed.
1172
1173 // Registers a type and constant for computing the result of the
1174 // given instruction. If the result of the instruction is a vector,
1175 // then make a splat vector constant with the same number of
1176 // elements.
1177 auto register_constant = [this, &I](Constant *constant) {
1178 FindType(constant->getType());
1179 FindConstant(constant);
1180 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1181 // Register the splat vector of the value with the same
1182 // width as the result of the instruction.
1183 auto *vec_constant = ConstantVector::getSplat(
1184 static_cast<unsigned>(vectorTy->getNumElements()),
1185 constant);
1186 FindConstant(vec_constant);
1187 FindType(vec_constant->getType());
1188 }
1189 };
1190 switch (IndirectEInst) {
1191 case glsl::ExtInstFindUMsb:
1192 // clz needs OpExtInst and OpISub with constant 31, or splat
1193 // vector of 31. Add it to the constant list here.
1194 register_constant(
1195 ConstantInt::get(Type::getInt32Ty(Context), 31));
1196 break;
1197 case glsl::ExtInstAcos:
1198 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001199 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001200 case glsl::ExtInstAtan2:
1201 // We need 1/pi for acospi, asinpi, atan2pi.
1202 register_constant(
1203 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1204 break;
1205 default:
1206 assert(false && "internally inconsistent");
1207 }
David Neto22f144c2017-06-12 14:26:21 -04001208 }
1209 }
1210 }
1211 }
1212 }
1213
1214 return HasExtInst;
1215}
1216
1217void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1218 // Investigate global variable's type.
1219 FindType(GV.getType());
1220}
1221
1222void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1223 // Investigate function's type.
1224 FunctionType *FTy = F.getFunctionType();
1225
1226 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1227 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001228 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001229 if (GlobalConstFuncTyMap.count(FTy)) {
1230 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1231 SmallVector<Type *, 4> NewFuncParamTys;
1232 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1233 Type *ParamTy = FTy->getParamType(i);
1234 if (i == GVCstArgIdx) {
1235 Type *EleTy = ParamTy->getPointerElementType();
1236 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1237 }
1238
1239 NewFuncParamTys.push_back(ParamTy);
1240 }
1241
1242 FunctionType *NewFTy =
1243 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1244 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1245 FTy = NewFTy;
1246 }
1247
1248 FindType(FTy);
1249 } else {
1250 // As kernel functions do not have parameters, create new function type and
1251 // add it to type map.
1252 SmallVector<Type *, 4> NewFuncParamTys;
1253 FunctionType *NewFTy =
1254 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1255 FindType(NewFTy);
1256 }
1257
1258 // Investigate instructions' type in function body.
1259 for (BasicBlock &BB : F) {
1260 for (Instruction &I : BB) {
1261 if (isa<ShuffleVectorInst>(I)) {
1262 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1263 // Ignore type for mask of shuffle vector instruction.
1264 if (i == 2) {
1265 continue;
1266 }
1267
1268 Value *Op = I.getOperand(i);
1269 if (!isa<MetadataAsValue>(Op)) {
1270 FindType(Op->getType());
1271 }
1272 }
1273
1274 FindType(I.getType());
1275 continue;
1276 }
1277
David Neto862b7d82018-06-14 18:48:37 -04001278 CallInst *Call = dyn_cast<CallInst>(&I);
1279
1280 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001281 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001282 // This is a fake call representing access to a resource variable.
1283 // We handle that elsewhere.
1284 continue;
1285 }
1286
Alan Baker202c8c72018-08-13 13:47:44 -04001287 if (Call && Call->getCalledFunction()->getName().startswith(
1288 clspv::WorkgroupAccessorFunction())) {
1289 // This is a fake call representing access to a workgroup variable.
1290 // We handle that elsewhere.
1291 continue;
1292 }
1293
David Neto22f144c2017-06-12 14:26:21 -04001294 // Work through the operands of the instruction.
1295 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1296 Value *const Op = I.getOperand(i);
1297 // If any of the operands is a constant, find the type!
1298 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1299 FindType(Op->getType());
1300 }
1301 }
1302
1303 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001304 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001305 // Avoid to check call instruction's type.
1306 break;
1307 }
Alan Baker202c8c72018-08-13 13:47:44 -04001308 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1309 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1310 clspv::WorkgroupAccessorFunction())) {
1311 // This is a fake call representing access to a workgroup variable.
1312 // We handle that elsewhere.
1313 continue;
1314 }
1315 }
David Neto22f144c2017-06-12 14:26:21 -04001316 if (!isa<MetadataAsValue>(&Op)) {
1317 FindType(Op->getType());
1318 continue;
1319 }
1320 }
1321
David Neto22f144c2017-06-12 14:26:21 -04001322 // We don't want to track the type of this call as we are going to replace
1323 // it.
David Neto862b7d82018-06-14 18:48:37 -04001324 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001325 Call->getCalledFunction()->getName())) {
1326 continue;
1327 }
1328
1329 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1330 // If gep's base operand has ModuleScopePrivate address space, make gep
1331 // return ModuleScopePrivate address space.
1332 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1333 // Add pointer type with private address space for global constant to
1334 // type list.
1335 Type *EleTy = I.getType()->getPointerElementType();
1336 Type *NewPTy =
1337 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1338
1339 FindType(NewPTy);
1340 continue;
1341 }
1342 }
1343
1344 FindType(I.getType());
1345 }
1346 }
1347}
1348
David Neto862b7d82018-06-14 18:48:37 -04001349void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1350 // If we are using a sampler map, find the type of the sampler.
1351 if (M.getFunction("clspv.sampler.var.literal") ||
1352 0 < getSamplerMap().size()) {
1353 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1354 if (!SamplerStructTy) {
1355 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1356 }
1357
1358 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1359
1360 FindType(SamplerTy);
1361 }
1362}
1363
1364void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1365 // Record types so they are generated.
1366 TypesNeedingLayout.reset();
1367 StructTypesNeedingBlock.reset();
1368
1369 // To match older clspv codegen, generate the float type first if required
1370 // for images.
1371 for (const auto *info : ModuleOrderedResourceVars) {
1372 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1373 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1374 // We need "float" for the sampled component type.
1375 FindType(Type::getFloatTy(M.getContext()));
1376 // We only need to find it once.
1377 break;
1378 }
1379 }
1380
1381 for (const auto *info : ModuleOrderedResourceVars) {
1382 Type *type = info->var_fn->getReturnType();
1383
1384 switch (info->arg_kind) {
1385 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001386 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001387 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1388 StructTypesNeedingBlock.insert(sty);
1389 } else {
1390 errs() << *type << "\n";
1391 llvm_unreachable("Buffer arguments must map to structures!");
1392 }
1393 break;
1394 case clspv::ArgKind::Pod:
1395 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1396 StructTypesNeedingBlock.insert(sty);
1397 } else {
1398 errs() << *type << "\n";
1399 llvm_unreachable("POD arguments must map to structures!");
1400 }
1401 break;
1402 case clspv::ArgKind::ReadOnlyImage:
1403 case clspv::ArgKind::WriteOnlyImage:
1404 case clspv::ArgKind::Sampler:
1405 // Sampler and image types map to the pointee type but
1406 // in the uniform constant address space.
1407 type = PointerType::get(type->getPointerElementType(),
1408 clspv::AddressSpace::UniformConstant);
1409 break;
1410 default:
1411 break;
1412 }
1413
1414 // The converted type is the type of the OpVariable we will generate.
1415 // If the pointee type is an array of size zero, FindType will convert it
1416 // to a runtime array.
1417 FindType(type);
1418 }
1419
1420 // Traverse the arrays and structures underneath each Block, and
1421 // mark them as needing layout.
1422 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1423 StructTypesNeedingBlock.end());
1424 while (!work_list.empty()) {
1425 Type *type = work_list.back();
1426 work_list.pop_back();
1427 TypesNeedingLayout.insert(type);
1428 switch (type->getTypeID()) {
1429 case Type::ArrayTyID:
1430 work_list.push_back(type->getArrayElementType());
1431 if (!Hack_generate_runtime_array_stride_early) {
1432 // Remember this array type for deferred decoration.
1433 TypesNeedingArrayStride.insert(type);
1434 }
1435 break;
1436 case Type::StructTyID:
1437 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1438 work_list.push_back(elem_ty);
1439 }
1440 default:
1441 // This type and its contained types don't get layout.
1442 break;
1443 }
1444 }
1445}
1446
Alan Baker202c8c72018-08-13 13:47:44 -04001447void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1448 // The SpecId assignment for pointer-to-local arguments is recorded in
1449 // module-level metadata. Translate that information into local argument
1450 // information.
1451 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001452 if (!nmd)
1453 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001454 for (auto operand : nmd->operands()) {
1455 MDTuple *tuple = cast<MDTuple>(operand);
1456 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1457 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001458 ConstantAsMetadata *arg_index_md =
1459 cast<ConstantAsMetadata>(tuple->getOperand(1));
1460 int arg_index = static_cast<int>(
1461 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1462 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001463
1464 ConstantAsMetadata *spec_id_md =
1465 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001466 int spec_id = static_cast<int>(
1467 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001468
1469 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1470 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001471 if (LocalSpecIdInfoMap.count(spec_id))
1472 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001473
1474 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1475 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1476 nextID + 1, nextID + 2,
1477 nextID + 3, spec_id};
1478 LocalSpecIdInfoMap[spec_id] = info;
1479 nextID += 4;
1480
1481 // Ensure the types necessary for this argument get generated.
1482 Type *IdxTy = Type::getInt32Ty(M.getContext());
1483 FindConstant(ConstantInt::get(IdxTy, 0));
1484 FindType(IdxTy);
1485 FindType(arg->getType());
1486 }
1487}
1488
David Neto22f144c2017-06-12 14:26:21 -04001489void SPIRVProducerPass::FindType(Type *Ty) {
1490 TypeList &TyList = getTypeList();
1491
1492 if (0 != TyList.idFor(Ty)) {
1493 return;
1494 }
1495
1496 if (Ty->isPointerTy()) {
1497 auto AddrSpace = Ty->getPointerAddressSpace();
1498 if ((AddressSpace::Constant == AddrSpace) ||
1499 (AddressSpace::Global == AddrSpace)) {
1500 auto PointeeTy = Ty->getPointerElementType();
1501
1502 if (PointeeTy->isStructTy() &&
1503 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1504 FindType(PointeeTy);
1505 auto ActualPointerTy =
1506 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1507 FindType(ActualPointerTy);
1508 return;
1509 }
1510 }
1511 }
1512
David Neto862b7d82018-06-14 18:48:37 -04001513 // By convention, LLVM array type with 0 elements will map to
1514 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1515 // has a constant number of elements. We need to support type of the
1516 // constant.
1517 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1518 if (arrayTy->getNumElements() > 0) {
1519 LLVMContext &Context = Ty->getContext();
1520 FindType(Type::getInt32Ty(Context));
1521 }
David Neto22f144c2017-06-12 14:26:21 -04001522 }
1523
1524 for (Type *SubTy : Ty->subtypes()) {
1525 FindType(SubTy);
1526 }
1527
1528 TyList.insert(Ty);
1529}
1530
1531void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1532 // If the global variable has a (non undef) initializer.
1533 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001534 // Generate the constant if it's not the initializer to a module scope
1535 // constant that we will expect in a storage buffer.
1536 const bool module_scope_constant_external_init =
1537 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1538 clspv::Option::ModuleConstantsInStorageBuffer();
1539 if (!module_scope_constant_external_init) {
1540 FindConstant(GV.getInitializer());
1541 }
David Neto22f144c2017-06-12 14:26:21 -04001542 }
1543}
1544
1545void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1546 // Investigate constants in function body.
1547 for (BasicBlock &BB : F) {
1548 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001549 if (auto *call = dyn_cast<CallInst>(&I)) {
1550 auto name = call->getCalledFunction()->getName();
1551 if (name == "clspv.sampler.var.literal") {
1552 // We've handled these constants elsewhere, so skip it.
1553 continue;
1554 }
Alan Baker202c8c72018-08-13 13:47:44 -04001555 if (name.startswith(clspv::ResourceAccessorFunction())) {
1556 continue;
1557 }
1558 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001559 continue;
1560 }
David Neto22f144c2017-06-12 14:26:21 -04001561 }
1562
1563 if (isa<AllocaInst>(I)) {
1564 // Alloca instruction has constant for the number of element. Ignore it.
1565 continue;
1566 } else if (isa<ShuffleVectorInst>(I)) {
1567 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1568 // Ignore constant for mask of shuffle vector instruction.
1569 if (i == 2) {
1570 continue;
1571 }
1572
1573 if (isa<Constant>(I.getOperand(i)) &&
1574 !isa<GlobalValue>(I.getOperand(i))) {
1575 FindConstant(I.getOperand(i));
1576 }
1577 }
1578
1579 continue;
1580 } else if (isa<InsertElementInst>(I)) {
1581 // Handle InsertElement with <4 x i8> specially.
1582 Type *CompositeTy = I.getOperand(0)->getType();
1583 if (is4xi8vec(CompositeTy)) {
1584 LLVMContext &Context = CompositeTy->getContext();
1585 if (isa<Constant>(I.getOperand(0))) {
1586 FindConstant(I.getOperand(0));
1587 }
1588
1589 if (isa<Constant>(I.getOperand(1))) {
1590 FindConstant(I.getOperand(1));
1591 }
1592
1593 // Add mask constant 0xFF.
1594 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1595 FindConstant(CstFF);
1596
1597 // Add shift amount constant.
1598 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1599 uint64_t Idx = CI->getZExtValue();
1600 Constant *CstShiftAmount =
1601 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1602 FindConstant(CstShiftAmount);
1603 }
1604
1605 continue;
1606 }
1607
1608 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1609 // Ignore constant for index of InsertElement instruction.
1610 if (i == 2) {
1611 continue;
1612 }
1613
1614 if (isa<Constant>(I.getOperand(i)) &&
1615 !isa<GlobalValue>(I.getOperand(i))) {
1616 FindConstant(I.getOperand(i));
1617 }
1618 }
1619
1620 continue;
1621 } else if (isa<ExtractElementInst>(I)) {
1622 // Handle ExtractElement with <4 x i8> specially.
1623 Type *CompositeTy = I.getOperand(0)->getType();
1624 if (is4xi8vec(CompositeTy)) {
1625 LLVMContext &Context = CompositeTy->getContext();
1626 if (isa<Constant>(I.getOperand(0))) {
1627 FindConstant(I.getOperand(0));
1628 }
1629
1630 // Add mask constant 0xFF.
1631 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1632 FindConstant(CstFF);
1633
1634 // Add shift amount constant.
1635 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1636 uint64_t Idx = CI->getZExtValue();
1637 Constant *CstShiftAmount =
1638 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1639 FindConstant(CstShiftAmount);
1640 } else {
1641 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1642 FindConstant(Cst8);
1643 }
1644
1645 continue;
1646 }
1647
1648 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1649 // Ignore constant for index of ExtractElement instruction.
1650 if (i == 1) {
1651 continue;
1652 }
1653
1654 if (isa<Constant>(I.getOperand(i)) &&
1655 !isa<GlobalValue>(I.getOperand(i))) {
1656 FindConstant(I.getOperand(i));
1657 }
1658 }
1659
1660 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001661 } else if ((Instruction::Xor == I.getOpcode()) &&
1662 I.getType()->isIntegerTy(1)) {
1663 // We special case for Xor where the type is i1 and one of the arguments
1664 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1665 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001666 bool foundConstantTrue = false;
1667 for (Use &Op : I.operands()) {
1668 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1669 auto CI = cast<ConstantInt>(Op);
1670
1671 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001672 // If we already found the true constant, we might (probably only
1673 // on -O0) have an OpLogicalNot which is taking a constant
1674 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001675 FindConstant(Op);
1676 } else {
1677 foundConstantTrue = true;
1678 }
1679 }
1680 }
1681
1682 continue;
David Netod2de94a2017-08-28 17:27:47 -04001683 } else if (isa<TruncInst>(I)) {
1684 // For truncation to i8 we mask against 255.
1685 Type *ToTy = I.getType();
1686 if (8u == ToTy->getPrimitiveSizeInBits()) {
1687 LLVMContext &Context = ToTy->getContext();
1688 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1689 FindConstant(Cst255);
1690 }
1691 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001692 } else if (isa<AtomicRMWInst>(I)) {
1693 LLVMContext &Context = I.getContext();
1694
1695 FindConstant(
1696 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1697 FindConstant(ConstantInt::get(
1698 Type::getInt32Ty(Context),
1699 spv::MemorySemanticsUniformMemoryMask |
1700 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001701 }
1702
1703 for (Use &Op : I.operands()) {
1704 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1705 FindConstant(Op);
1706 }
1707 }
1708 }
1709 }
1710}
1711
1712void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001713 ValueList &CstList = getConstantList();
1714
David Netofb9a7972017-08-25 17:08:24 -04001715 // If V is already tracked, ignore it.
1716 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001717 return;
1718 }
1719
David Neto862b7d82018-06-14 18:48:37 -04001720 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1721 return;
1722 }
1723
David Neto22f144c2017-06-12 14:26:21 -04001724 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001725 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001726
1727 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001728 if (is4xi8vec(CstTy)) {
1729 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001730 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001731 }
1732 }
1733
1734 if (Cst->getNumOperands()) {
1735 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1736 ++I) {
1737 FindConstant(*I);
1738 }
1739
David Netofb9a7972017-08-25 17:08:24 -04001740 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001741 return;
1742 } else if (const ConstantDataSequential *CDS =
1743 dyn_cast<ConstantDataSequential>(Cst)) {
1744 // Add constants for each element to constant list.
1745 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1746 Constant *EleCst = CDS->getElementAsConstant(i);
1747 FindConstant(EleCst);
1748 }
1749 }
1750
1751 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001752 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001753 }
1754}
1755
1756spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1757 switch (AddrSpace) {
1758 default:
1759 llvm_unreachable("Unsupported OpenCL address space");
1760 case AddressSpace::Private:
1761 return spv::StorageClassFunction;
1762 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001763 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001764 case AddressSpace::Constant:
1765 return clspv::Option::ConstantArgsInUniformBuffer()
1766 ? spv::StorageClassUniform
1767 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001768 case AddressSpace::Input:
1769 return spv::StorageClassInput;
1770 case AddressSpace::Local:
1771 return spv::StorageClassWorkgroup;
1772 case AddressSpace::UniformConstant:
1773 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001774 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001775 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001776 case AddressSpace::ModuleScopePrivate:
1777 return spv::StorageClassPrivate;
1778 }
1779}
1780
David Neto862b7d82018-06-14 18:48:37 -04001781spv::StorageClass
1782SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1783 switch (arg_kind) {
1784 case clspv::ArgKind::Buffer:
1785 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001786 case clspv::ArgKind::BufferUBO:
1787 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001788 case clspv::ArgKind::Pod:
1789 return clspv::Option::PodArgsInUniformBuffer()
1790 ? spv::StorageClassUniform
1791 : spv::StorageClassStorageBuffer;
1792 case clspv::ArgKind::Local:
1793 return spv::StorageClassWorkgroup;
1794 case clspv::ArgKind::ReadOnlyImage:
1795 case clspv::ArgKind::WriteOnlyImage:
1796 case clspv::ArgKind::Sampler:
1797 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001798 default:
1799 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001800 }
1801}
1802
David Neto22f144c2017-06-12 14:26:21 -04001803spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1804 return StringSwitch<spv::BuiltIn>(Name)
1805 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1806 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1807 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1808 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1809 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1810 .Default(spv::BuiltInMax);
1811}
1812
1813void SPIRVProducerPass::GenerateExtInstImport() {
1814 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1815 uint32_t &ExtInstImportID = getOpExtInstImportID();
1816
1817 //
1818 // Generate OpExtInstImport.
1819 //
1820 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001821 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001822 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1823 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001824}
1825
alan-bakerb6b09dc2018-11-08 16:59:28 -05001826void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1827 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001828 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1829 ValueMapType &VMap = getValueMap();
1830 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001831 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001832
1833 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1834 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1835 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1836
1837 for (Type *Ty : getTypeList()) {
1838 // Update TypeMap with nextID for reference later.
1839 TypeMap[Ty] = nextID;
1840
1841 switch (Ty->getTypeID()) {
1842 default: {
1843 Ty->print(errs());
1844 llvm_unreachable("Unsupported type???");
1845 break;
1846 }
1847 case Type::MetadataTyID:
1848 case Type::LabelTyID: {
1849 // Ignore these types.
1850 break;
1851 }
1852 case Type::PointerTyID: {
1853 PointerType *PTy = cast<PointerType>(Ty);
1854 unsigned AddrSpace = PTy->getAddressSpace();
1855
1856 // For the purposes of our Vulkan SPIR-V type system, constant and global
1857 // are conflated.
1858 bool UseExistingOpTypePointer = false;
1859 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001860 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1861 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001862 // Check to see if we already created this type (for instance, if we
1863 // had a constant <type>* and a global <type>*, the type would be
1864 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001865 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1866 if (0 < TypeMap.count(GlobalTy)) {
1867 TypeMap[PTy] = TypeMap[GlobalTy];
1868 UseExistingOpTypePointer = true;
1869 break;
1870 }
David Neto22f144c2017-06-12 14:26:21 -04001871 }
1872 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001873 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1874 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001875
alan-bakerb6b09dc2018-11-08 16:59:28 -05001876 // Check to see if we already created this type (for instance, if we
1877 // had a constant <type>* and a global <type>*, the type would be
1878 // created by one of these types, and shared by both).
1879 auto ConstantTy =
1880 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001881 if (0 < TypeMap.count(ConstantTy)) {
1882 TypeMap[PTy] = TypeMap[ConstantTy];
1883 UseExistingOpTypePointer = true;
1884 }
David Neto22f144c2017-06-12 14:26:21 -04001885 }
1886 }
1887
David Neto862b7d82018-06-14 18:48:37 -04001888 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001889
David Neto862b7d82018-06-14 18:48:37 -04001890 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001891 //
1892 // Generate OpTypePointer.
1893 //
1894
1895 // OpTypePointer
1896 // Ops[0] = Storage Class
1897 // Ops[1] = Element Type ID
1898 SPIRVOperandList Ops;
1899
David Neto257c3892018-04-11 13:19:45 -04001900 Ops << MkNum(GetStorageClass(AddrSpace))
1901 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001902
David Neto87846742018-04-11 17:36:22 -04001903 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001904 SPIRVInstList.push_back(Inst);
1905 }
David Neto22f144c2017-06-12 14:26:21 -04001906 break;
1907 }
1908 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001909 StructType *STy = cast<StructType>(Ty);
1910
1911 // Handle sampler type.
1912 if (STy->isOpaque()) {
1913 if (STy->getName().equals("opencl.sampler_t")) {
1914 //
1915 // Generate OpTypeSampler
1916 //
1917 // Empty Ops.
1918 SPIRVOperandList Ops;
1919
David Neto87846742018-04-11 17:36:22 -04001920 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001921 SPIRVInstList.push_back(Inst);
1922 break;
1923 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1924 STy->getName().equals("opencl.image2d_wo_t") ||
1925 STy->getName().equals("opencl.image3d_ro_t") ||
1926 STy->getName().equals("opencl.image3d_wo_t")) {
1927 //
1928 // Generate OpTypeImage
1929 //
1930 // Ops[0] = Sampled Type ID
1931 // Ops[1] = Dim ID
1932 // Ops[2] = Depth (Literal Number)
1933 // Ops[3] = Arrayed (Literal Number)
1934 // Ops[4] = MS (Literal Number)
1935 // Ops[5] = Sampled (Literal Number)
1936 // Ops[6] = Image Format ID
1937 //
1938 SPIRVOperandList Ops;
1939
1940 // TODO: Changed Sampled Type according to situations.
1941 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001942 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001943
1944 spv::Dim DimID = spv::Dim2D;
1945 if (STy->getName().equals("opencl.image3d_ro_t") ||
1946 STy->getName().equals("opencl.image3d_wo_t")) {
1947 DimID = spv::Dim3D;
1948 }
David Neto257c3892018-04-11 13:19:45 -04001949 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001950
1951 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001952 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001953
1954 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001955 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001956
1957 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001958 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001959
1960 // TODO: Set up Sampled.
1961 //
1962 // From Spec
1963 //
1964 // 0 indicates this is only known at run time, not at compile time
1965 // 1 indicates will be used with sampler
1966 // 2 indicates will be used without a sampler (a storage image)
1967 uint32_t Sampled = 1;
1968 if (STy->getName().equals("opencl.image2d_wo_t") ||
1969 STy->getName().equals("opencl.image3d_wo_t")) {
1970 Sampled = 2;
1971 }
David Neto257c3892018-04-11 13:19:45 -04001972 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001973
1974 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001975 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001976
David Neto87846742018-04-11 17:36:22 -04001977 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001978 SPIRVInstList.push_back(Inst);
1979 break;
1980 }
1981 }
1982
1983 //
1984 // Generate OpTypeStruct
1985 //
1986 // Ops[0] ... Ops[n] = Member IDs
1987 SPIRVOperandList Ops;
1988
1989 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001990 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001991 }
1992
David Neto22f144c2017-06-12 14:26:21 -04001993 uint32_t STyID = nextID;
1994
alan-bakerb6b09dc2018-11-08 16:59:28 -05001995 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001996 SPIRVInstList.push_back(Inst);
1997
1998 // Generate OpMemberDecorate.
1999 auto DecoInsertPoint =
2000 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2001 [](SPIRVInstruction *Inst) -> bool {
2002 return Inst->getOpcode() != spv::OpDecorate &&
2003 Inst->getOpcode() != spv::OpMemberDecorate &&
2004 Inst->getOpcode() != spv::OpExtInstImport;
2005 });
2006
David Netoc463b372017-08-10 15:32:21 -04002007 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04002008 // Search for the correct offsets if this type was remapped.
2009 std::vector<uint32_t> *offsets = nullptr;
2010 auto iter = RemappedUBOTypeOffsets.find(STy);
2011 if (iter != RemappedUBOTypeOffsets.end()) {
2012 offsets = &iter->second;
2013 }
David Netoc463b372017-08-10 15:32:21 -04002014
David Neto862b7d82018-06-14 18:48:37 -04002015 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04002016 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
2017 MemberIdx++) {
2018 // Ops[0] = Structure Type ID
2019 // Ops[1] = Member Index(Literal Number)
2020 // Ops[2] = Decoration (Offset)
2021 // Ops[3] = Byte Offset (Literal Number)
2022 Ops.clear();
2023
David Neto257c3892018-04-11 13:19:45 -04002024 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04002025
alan-bakerb6b09dc2018-11-08 16:59:28 -05002026 auto ByteOffset =
2027 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002028 if (offsets) {
2029 ByteOffset = (*offsets)[MemberIdx];
2030 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002031 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002032 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002033 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002034
David Neto87846742018-04-11 17:36:22 -04002035 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002036 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002037 }
2038
2039 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002040 if (StructTypesNeedingBlock.idFor(STy)) {
2041 Ops.clear();
2042 // Use Block decorations with StorageBuffer storage class.
2043 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002044
David Neto862b7d82018-06-14 18:48:37 -04002045 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2046 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002047 }
2048 break;
2049 }
2050 case Type::IntegerTyID: {
2051 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2052
2053 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002054 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002055 SPIRVInstList.push_back(Inst);
2056 } else {
2057 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002058 // No matter what LLVM type is requested first, always alias the
2059 // second one's SPIR-V type to be the same as the one we generated
2060 // first.
Neil Henning39672102017-09-29 14:33:13 +01002061 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002062 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002063 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002064 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002065 } else if (BitWidth == 32) {
2066 aliasToWidth = 8;
2067 }
2068 if (aliasToWidth) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002069 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
David Neto391aeb12017-08-26 15:51:58 -04002070 auto where = TypeMap.find(otherType);
2071 if (where == TypeMap.end()) {
2072 // Go ahead and make it, but also map the other type to it.
2073 TypeMap[otherType] = nextID;
2074 } else {
2075 // Alias this SPIR-V type the existing type.
2076 TypeMap[Ty] = where->second;
2077 break;
2078 }
David Neto22f144c2017-06-12 14:26:21 -04002079 }
2080
David Neto257c3892018-04-11 13:19:45 -04002081 SPIRVOperandList Ops;
2082 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002083
2084 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002085 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002086 }
2087 break;
2088 }
2089 case Type::HalfTyID:
2090 case Type::FloatTyID:
2091 case Type::DoubleTyID: {
2092 SPIRVOperand *WidthOp = new SPIRVOperand(
2093 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2094
2095 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002096 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002097 break;
2098 }
2099 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002100 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002101 const uint64_t Length = ArrTy->getArrayNumElements();
2102 if (Length == 0) {
2103 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002104
David Neto862b7d82018-06-14 18:48:37 -04002105 // Only generate the type once.
2106 // TODO(dneto): Can it ever be generated more than once?
2107 // Doesn't LLVM type uniqueness guarantee we'll only see this
2108 // once?
2109 Type *EleTy = ArrTy->getArrayElementType();
2110 if (OpRuntimeTyMap.count(EleTy) == 0) {
2111 uint32_t OpTypeRuntimeArrayID = nextID;
2112 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002113
David Neto862b7d82018-06-14 18:48:37 -04002114 //
2115 // Generate OpTypeRuntimeArray.
2116 //
David Neto22f144c2017-06-12 14:26:21 -04002117
David Neto862b7d82018-06-14 18:48:37 -04002118 // OpTypeRuntimeArray
2119 // Ops[0] = Element Type ID
2120 SPIRVOperandList Ops;
2121 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002122
David Neto862b7d82018-06-14 18:48:37 -04002123 SPIRVInstList.push_back(
2124 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002125
David Neto862b7d82018-06-14 18:48:37 -04002126 if (Hack_generate_runtime_array_stride_early) {
2127 // Generate OpDecorate.
2128 auto DecoInsertPoint = std::find_if(
2129 SPIRVInstList.begin(), SPIRVInstList.end(),
2130 [](SPIRVInstruction *Inst) -> bool {
2131 return Inst->getOpcode() != spv::OpDecorate &&
2132 Inst->getOpcode() != spv::OpMemberDecorate &&
2133 Inst->getOpcode() != spv::OpExtInstImport;
2134 });
David Neto22f144c2017-06-12 14:26:21 -04002135
David Neto862b7d82018-06-14 18:48:37 -04002136 // Ops[0] = Target ID
2137 // Ops[1] = Decoration (ArrayStride)
2138 // Ops[2] = Stride Number(Literal Number)
2139 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002140
David Neto862b7d82018-06-14 18:48:37 -04002141 Ops << MkId(OpTypeRuntimeArrayID)
2142 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002143 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002144
David Neto862b7d82018-06-14 18:48:37 -04002145 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2146 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2147 }
2148 }
David Neto22f144c2017-06-12 14:26:21 -04002149
David Neto862b7d82018-06-14 18:48:37 -04002150 } else {
David Neto22f144c2017-06-12 14:26:21 -04002151
David Neto862b7d82018-06-14 18:48:37 -04002152 //
2153 // Generate OpConstant and OpTypeArray.
2154 //
2155
2156 //
2157 // Generate OpConstant for array length.
2158 //
2159 // Ops[0] = Result Type ID
2160 // Ops[1] .. Ops[n] = Values LiteralNumber
2161 SPIRVOperandList Ops;
2162
2163 Type *LengthTy = Type::getInt32Ty(Context);
2164 uint32_t ResTyID = lookupType(LengthTy);
2165 Ops << MkId(ResTyID);
2166
2167 assert(Length < UINT32_MAX);
2168 Ops << MkNum(static_cast<uint32_t>(Length));
2169
2170 // Add constant for length to constant list.
2171 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2172 AllocatedVMap[CstLength] = nextID;
2173 VMap[CstLength] = nextID;
2174 uint32_t LengthID = nextID;
2175
2176 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2177 SPIRVInstList.push_back(CstInst);
2178
2179 // Remember to generate ArrayStride later
2180 getTypesNeedingArrayStride().insert(Ty);
2181
2182 //
2183 // Generate OpTypeArray.
2184 //
2185 // Ops[0] = Element Type ID
2186 // Ops[1] = Array Length Constant ID
2187 Ops.clear();
2188
2189 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2190 Ops << MkId(EleTyID) << MkId(LengthID);
2191
2192 // Update TypeMap with nextID.
2193 TypeMap[Ty] = nextID;
2194
2195 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2196 SPIRVInstList.push_back(ArrayInst);
2197 }
David Neto22f144c2017-06-12 14:26:21 -04002198 break;
2199 }
2200 case Type::VectorTyID: {
2201 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002202 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2203 if (Ty->getVectorNumElements() == 4) {
2204 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2205 break;
2206 } else {
2207 Ty->print(errs());
2208 llvm_unreachable("Support above i8 vector type");
2209 }
2210 }
2211
2212 // Ops[0] = Component Type ID
2213 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002214 SPIRVOperandList Ops;
2215 Ops << MkId(lookupType(Ty->getVectorElementType()))
2216 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002217
alan-bakerb6b09dc2018-11-08 16:59:28 -05002218 SPIRVInstruction *inst =
2219 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002220 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002221 break;
2222 }
2223 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002224 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002225 SPIRVInstList.push_back(Inst);
2226 break;
2227 }
2228 case Type::FunctionTyID: {
2229 // Generate SPIRV instruction for function type.
2230 FunctionType *FTy = cast<FunctionType>(Ty);
2231
2232 // Ops[0] = Return Type ID
2233 // Ops[1] ... Ops[n] = Parameter Type IDs
2234 SPIRVOperandList Ops;
2235
2236 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002237 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002238
2239 // Find SPIRV instructions for parameter types
2240 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2241 // Find SPIRV instruction for parameter type.
2242 auto ParamTy = FTy->getParamType(k);
2243 if (ParamTy->isPointerTy()) {
2244 auto PointeeTy = ParamTy->getPointerElementType();
2245 if (PointeeTy->isStructTy() &&
2246 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2247 ParamTy = PointeeTy;
2248 }
2249 }
2250
David Netoc6f3ab22018-04-06 18:02:31 -04002251 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002252 }
2253
David Neto87846742018-04-11 17:36:22 -04002254 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002255 SPIRVInstList.push_back(Inst);
2256 break;
2257 }
2258 }
2259 }
2260
2261 // Generate OpTypeSampledImage.
2262 TypeMapType &OpImageTypeMap = getImageTypeMap();
2263 for (auto &ImageType : OpImageTypeMap) {
2264 //
2265 // Generate OpTypeSampledImage.
2266 //
2267 // Ops[0] = Image Type ID
2268 //
2269 SPIRVOperandList Ops;
2270
2271 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002272 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002273
2274 // Update OpImageTypeMap.
2275 ImageType.second = nextID;
2276
David Neto87846742018-04-11 17:36:22 -04002277 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002278 SPIRVInstList.push_back(Inst);
2279 }
David Netoc6f3ab22018-04-06 18:02:31 -04002280
2281 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002282 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2283 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002284 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002285
2286 // Generate the spec constant.
2287 SPIRVOperandList Ops;
2288 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002289 SPIRVInstList.push_back(
2290 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002291
2292 // Generate the array type.
2293 Ops.clear();
2294 // The element type must have been created.
2295 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2296 assert(elem_ty_id);
2297 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2298
2299 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002300 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002301
2302 Ops.clear();
2303 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002304 SPIRVInstList.push_back(new SPIRVInstruction(
2305 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002306 }
David Neto22f144c2017-06-12 14:26:21 -04002307}
2308
2309void SPIRVProducerPass::GenerateSPIRVConstants() {
2310 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2311 ValueMapType &VMap = getValueMap();
2312 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2313 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002314 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002315
2316 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002317 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002318 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002319
2320 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002321 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002322 continue;
2323 }
2324
David Netofb9a7972017-08-25 17:08:24 -04002325 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002326 VMap[Cst] = nextID;
2327
2328 //
2329 // Generate OpConstant.
2330 //
2331
2332 // Ops[0] = Result Type ID
2333 // Ops[1] .. Ops[n] = Values LiteralNumber
2334 SPIRVOperandList Ops;
2335
David Neto257c3892018-04-11 13:19:45 -04002336 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002337
2338 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002339 spv::Op Opcode = spv::OpNop;
2340
2341 if (isa<UndefValue>(Cst)) {
2342 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002343 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002344 if (hack_undef && IsTypeNullable(Cst->getType())) {
2345 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002346 }
David Neto22f144c2017-06-12 14:26:21 -04002347 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2348 unsigned BitWidth = CI->getBitWidth();
2349 if (BitWidth == 1) {
2350 // If the bitwidth of constant is 1, generate OpConstantTrue or
2351 // OpConstantFalse.
2352 if (CI->getZExtValue()) {
2353 // Ops[0] = Result Type ID
2354 Opcode = spv::OpConstantTrue;
2355 } else {
2356 // Ops[0] = Result Type ID
2357 Opcode = spv::OpConstantFalse;
2358 }
David Neto22f144c2017-06-12 14:26:21 -04002359 } else {
2360 auto V = CI->getZExtValue();
2361 LiteralNum.push_back(V & 0xFFFFFFFF);
2362
2363 if (BitWidth > 32) {
2364 LiteralNum.push_back(V >> 32);
2365 }
2366
2367 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002368
David Neto257c3892018-04-11 13:19:45 -04002369 Ops << MkInteger(LiteralNum);
2370
2371 if (BitWidth == 32 && V == 0) {
2372 constant_i32_zero_id_ = nextID;
2373 }
David Neto22f144c2017-06-12 14:26:21 -04002374 }
2375 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2376 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2377 Type *CFPTy = CFP->getType();
2378 if (CFPTy->isFloatTy()) {
2379 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2380 } else {
2381 CFPTy->print(errs());
2382 llvm_unreachable("Implement this ConstantFP Type");
2383 }
2384
2385 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002386
David Neto257c3892018-04-11 13:19:45 -04002387 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002388 } else if (isa<ConstantDataSequential>(Cst) &&
2389 cast<ConstantDataSequential>(Cst)->isString()) {
2390 Cst->print(errs());
2391 llvm_unreachable("Implement this Constant");
2392
2393 } else if (const ConstantDataSequential *CDS =
2394 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002395 // Let's convert <4 x i8> constant to int constant specially.
2396 // This case occurs when all the values are specified as constant
2397 // ints.
2398 Type *CstTy = Cst->getType();
2399 if (is4xi8vec(CstTy)) {
2400 LLVMContext &Context = CstTy->getContext();
2401
2402 //
2403 // Generate OpConstant with OpTypeInt 32 0.
2404 //
Neil Henning39672102017-09-29 14:33:13 +01002405 uint32_t IntValue = 0;
2406 for (unsigned k = 0; k < 4; k++) {
2407 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002408 IntValue = (IntValue << 8) | (Val & 0xffu);
2409 }
2410
2411 Type *i32 = Type::getInt32Ty(Context);
2412 Constant *CstInt = ConstantInt::get(i32, IntValue);
2413 // If this constant is already registered on VMap, use it.
2414 if (VMap.count(CstInt)) {
2415 uint32_t CstID = VMap[CstInt];
2416 VMap[Cst] = CstID;
2417 continue;
2418 }
2419
David Neto257c3892018-04-11 13:19:45 -04002420 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002421
David Neto87846742018-04-11 17:36:22 -04002422 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002423 SPIRVInstList.push_back(CstInst);
2424
2425 continue;
2426 }
2427
2428 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002429 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2430 Constant *EleCst = CDS->getElementAsConstant(k);
2431 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002432 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002433 }
2434
2435 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002436 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2437 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002438 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002439 Type *CstTy = Cst->getType();
2440 if (is4xi8vec(CstTy)) {
2441 LLVMContext &Context = CstTy->getContext();
2442
2443 //
2444 // Generate OpConstant with OpTypeInt 32 0.
2445 //
Neil Henning39672102017-09-29 14:33:13 +01002446 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002447 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2448 I != E; ++I) {
2449 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002450 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002451 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2452 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002453 }
David Neto49351ac2017-08-26 17:32:20 -04002454 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002455 }
2456
David Neto49351ac2017-08-26 17:32:20 -04002457 Type *i32 = Type::getInt32Ty(Context);
2458 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002459 // If this constant is already registered on VMap, use it.
2460 if (VMap.count(CstInt)) {
2461 uint32_t CstID = VMap[CstInt];
2462 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002463 continue;
David Neto22f144c2017-06-12 14:26:21 -04002464 }
2465
David Neto257c3892018-04-11 13:19:45 -04002466 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002467
David Neto87846742018-04-11 17:36:22 -04002468 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002469 SPIRVInstList.push_back(CstInst);
2470
David Neto19a1bad2017-08-25 15:01:41 -04002471 continue;
David Neto22f144c2017-06-12 14:26:21 -04002472 }
2473
2474 // We use a constant composite in SPIR-V for our constant aggregate in
2475 // LLVM.
2476 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002477
2478 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2479 // Look up the ID of the element of this aggregate (which we will
2480 // previously have created a constant for).
2481 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2482
2483 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002484 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002485 }
2486 } else if (Cst->isNullValue()) {
2487 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002488 } else {
2489 Cst->print(errs());
2490 llvm_unreachable("Unsupported Constant???");
2491 }
2492
alan-baker5b86ed72019-02-15 08:26:50 -05002493 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2494 // Null pointer requires variable pointers.
2495 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2496 }
2497
David Neto87846742018-04-11 17:36:22 -04002498 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002499 SPIRVInstList.push_back(CstInst);
2500 }
2501}
2502
2503void SPIRVProducerPass::GenerateSamplers(Module &M) {
2504 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002505
alan-bakerb6b09dc2018-11-08 16:59:28 -05002506 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002507 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002508 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002509 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2510 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002511
David Neto862b7d82018-06-14 18:48:37 -04002512 // We might have samplers in the sampler map that are not used
2513 // in the translation unit. We need to allocate variables
2514 // for them and bindings too.
2515 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002516
alan-bakerb6b09dc2018-11-08 16:59:28 -05002517 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2518 if (!var_fn)
2519 return;
David Neto862b7d82018-06-14 18:48:37 -04002520 for (auto user : var_fn->users()) {
2521 // Populate SamplerLiteralToDescriptorSetMap and
2522 // SamplerLiteralToBindingMap.
2523 //
2524 // Look for calls like
2525 // call %opencl.sampler_t addrspace(2)*
2526 // @clspv.sampler.var.literal(
2527 // i32 descriptor,
2528 // i32 binding,
2529 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002530 if (auto *call = dyn_cast<CallInst>(user)) {
2531 const size_t index_into_sampler_map = static_cast<size_t>(
2532 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002533 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002534 errs() << "Out of bounds index to sampler map: "
2535 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002536 llvm_unreachable("bad sampler init: out of bounds");
2537 }
2538
2539 auto sampler_value = sampler_map[index_into_sampler_map].first;
2540 const auto descriptor_set = static_cast<unsigned>(
2541 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2542 const auto binding = static_cast<unsigned>(
2543 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2544
2545 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2546 SamplerLiteralToBindingMap[sampler_value] = binding;
2547 used_bindings.insert(binding);
2548 }
2549 }
2550
2551 unsigned index = 0;
2552 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002553 // Generate OpVariable.
2554 //
2555 // GIDOps[0] : Result Type ID
2556 // GIDOps[1] : Storage Class
2557 SPIRVOperandList Ops;
2558
David Neto257c3892018-04-11 13:19:45 -04002559 Ops << MkId(lookupType(SamplerTy))
2560 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002561
David Neto862b7d82018-06-14 18:48:37 -04002562 auto sampler_var_id = nextID++;
2563 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002564 SPIRVInstList.push_back(Inst);
2565
David Neto862b7d82018-06-14 18:48:37 -04002566 SamplerMapIndexToIDMap[index] = sampler_var_id;
2567 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002568
2569 // Find Insert Point for OpDecorate.
2570 auto DecoInsertPoint =
2571 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2572 [](SPIRVInstruction *Inst) -> bool {
2573 return Inst->getOpcode() != spv::OpDecorate &&
2574 Inst->getOpcode() != spv::OpMemberDecorate &&
2575 Inst->getOpcode() != spv::OpExtInstImport;
2576 });
2577
2578 // Ops[0] = Target ID
2579 // Ops[1] = Decoration (DescriptorSet)
2580 // Ops[2] = LiteralNumber according to Decoration
2581 Ops.clear();
2582
David Neto862b7d82018-06-14 18:48:37 -04002583 unsigned descriptor_set;
2584 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002585 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2586 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002587 // This sampler is not actually used. Find the next one.
2588 for (binding = 0; used_bindings.count(binding); binding++)
2589 ;
2590 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2591 used_bindings.insert(binding);
2592 } else {
2593 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2594 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2595 }
2596
2597 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2598 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002599
alan-bakerf5e5f692018-11-27 08:33:24 -05002600 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2601 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002602
David Neto87846742018-04-11 17:36:22 -04002603 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002604 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2605
2606 // Ops[0] = Target ID
2607 // Ops[1] = Decoration (Binding)
2608 // Ops[2] = LiteralNumber according to Decoration
2609 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002610 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2611 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002612
David Neto87846742018-04-11 17:36:22 -04002613 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002614 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002615
2616 index++;
David Neto22f144c2017-06-12 14:26:21 -04002617 }
David Neto862b7d82018-06-14 18:48:37 -04002618}
David Neto22f144c2017-06-12 14:26:21 -04002619
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002620void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002621 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2622 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002623
David Neto862b7d82018-06-14 18:48:37 -04002624 // Generate variables. Make one for each of resource var info object.
2625 for (auto *info : ModuleOrderedResourceVars) {
2626 Type *type = info->var_fn->getReturnType();
2627 // Remap the address space for opaque types.
2628 switch (info->arg_kind) {
2629 case clspv::ArgKind::Sampler:
2630 case clspv::ArgKind::ReadOnlyImage:
2631 case clspv::ArgKind::WriteOnlyImage:
2632 type = PointerType::get(type->getPointerElementType(),
2633 clspv::AddressSpace::UniformConstant);
2634 break;
2635 default:
2636 break;
2637 }
David Neto22f144c2017-06-12 14:26:21 -04002638
David Neto862b7d82018-06-14 18:48:37 -04002639 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002640
David Neto862b7d82018-06-14 18:48:37 -04002641 const auto type_id = lookupType(type);
2642 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2643 SPIRVOperandList Ops;
2644 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002645
David Neto862b7d82018-06-14 18:48:37 -04002646 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2647 SPIRVInstList.push_back(Inst);
2648
2649 // Map calls to the variable-builtin-function.
2650 for (auto &U : info->var_fn->uses()) {
2651 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2652 const auto set = unsigned(
2653 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2654 const auto binding = unsigned(
2655 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2656 if (set == info->descriptor_set && binding == info->binding) {
2657 switch (info->arg_kind) {
2658 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002659 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002660 case clspv::ArgKind::Pod:
2661 // The call maps to the variable directly.
2662 VMap[call] = info->var_id;
2663 break;
2664 case clspv::ArgKind::Sampler:
2665 case clspv::ArgKind::ReadOnlyImage:
2666 case clspv::ArgKind::WriteOnlyImage:
2667 // The call maps to a load we generate later.
2668 ResourceVarDeferredLoadCalls[call] = info->var_id;
2669 break;
2670 default:
2671 llvm_unreachable("Unhandled arg kind");
2672 }
2673 }
David Neto22f144c2017-06-12 14:26:21 -04002674 }
David Neto862b7d82018-06-14 18:48:37 -04002675 }
2676 }
David Neto22f144c2017-06-12 14:26:21 -04002677
David Neto862b7d82018-06-14 18:48:37 -04002678 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002679
David Neto862b7d82018-06-14 18:48:37 -04002680 // Find Insert Point for OpDecorate.
2681 auto DecoInsertPoint =
2682 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2683 [](SPIRVInstruction *Inst) -> bool {
2684 return Inst->getOpcode() != spv::OpDecorate &&
2685 Inst->getOpcode() != spv::OpMemberDecorate &&
2686 Inst->getOpcode() != spv::OpExtInstImport;
2687 });
2688
2689 SPIRVOperandList Ops;
2690 for (auto *info : ModuleOrderedResourceVars) {
2691 // Decorate with DescriptorSet and Binding.
2692 Ops.clear();
2693 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2694 << MkNum(info->descriptor_set);
2695 SPIRVInstList.insert(DecoInsertPoint,
2696 new SPIRVInstruction(spv::OpDecorate, Ops));
2697
2698 Ops.clear();
2699 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2700 << MkNum(info->binding);
2701 SPIRVInstList.insert(DecoInsertPoint,
2702 new SPIRVInstruction(spv::OpDecorate, Ops));
2703
2704 // Generate NonWritable and NonReadable
2705 switch (info->arg_kind) {
2706 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002707 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002708 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2709 clspv::AddressSpace::Constant) {
2710 Ops.clear();
2711 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2712 SPIRVInstList.insert(DecoInsertPoint,
2713 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002714 }
David Neto862b7d82018-06-14 18:48:37 -04002715 break;
2716 case clspv::ArgKind::ReadOnlyImage:
2717 Ops.clear();
2718 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2719 SPIRVInstList.insert(DecoInsertPoint,
2720 new SPIRVInstruction(spv::OpDecorate, Ops));
2721 break;
2722 case clspv::ArgKind::WriteOnlyImage:
2723 Ops.clear();
2724 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2725 SPIRVInstList.insert(DecoInsertPoint,
2726 new SPIRVInstruction(spv::OpDecorate, Ops));
2727 break;
2728 default:
2729 break;
David Neto22f144c2017-06-12 14:26:21 -04002730 }
2731 }
2732}
2733
2734void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002735 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002736 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2737 ValueMapType &VMap = getValueMap();
2738 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002739 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002740
2741 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2742 Type *Ty = GV.getType();
2743 PointerType *PTy = cast<PointerType>(Ty);
2744
2745 uint32_t InitializerID = 0;
2746
2747 // Workgroup size is handled differently (it goes into a constant)
2748 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2749 std::vector<bool> HasMDVec;
2750 uint32_t PrevXDimCst = 0xFFFFFFFF;
2751 uint32_t PrevYDimCst = 0xFFFFFFFF;
2752 uint32_t PrevZDimCst = 0xFFFFFFFF;
2753 for (Function &Func : *GV.getParent()) {
2754 if (Func.isDeclaration()) {
2755 continue;
2756 }
2757
2758 // We only need to check kernels.
2759 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2760 continue;
2761 }
2762
2763 if (const MDNode *MD =
2764 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2765 uint32_t CurXDimCst = static_cast<uint32_t>(
2766 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2767 uint32_t CurYDimCst = static_cast<uint32_t>(
2768 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2769 uint32_t CurZDimCst = static_cast<uint32_t>(
2770 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2771
2772 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2773 PrevZDimCst == 0xFFFFFFFF) {
2774 PrevXDimCst = CurXDimCst;
2775 PrevYDimCst = CurYDimCst;
2776 PrevZDimCst = CurZDimCst;
2777 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2778 CurZDimCst != PrevZDimCst) {
2779 llvm_unreachable(
2780 "reqd_work_group_size must be the same across all kernels");
2781 } else {
2782 continue;
2783 }
2784
2785 //
2786 // Generate OpConstantComposite.
2787 //
2788 // Ops[0] : Result Type ID
2789 // Ops[1] : Constant size for x dimension.
2790 // Ops[2] : Constant size for y dimension.
2791 // Ops[3] : Constant size for z dimension.
2792 SPIRVOperandList Ops;
2793
2794 uint32_t XDimCstID =
2795 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2796 uint32_t YDimCstID =
2797 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2798 uint32_t ZDimCstID =
2799 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2800
2801 InitializerID = nextID;
2802
David Neto257c3892018-04-11 13:19:45 -04002803 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2804 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002805
David Neto87846742018-04-11 17:36:22 -04002806 auto *Inst =
2807 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002808 SPIRVInstList.push_back(Inst);
2809
2810 HasMDVec.push_back(true);
2811 } else {
2812 HasMDVec.push_back(false);
2813 }
2814 }
2815
2816 // Check all kernels have same definitions for work_group_size.
2817 bool HasMD = false;
2818 if (!HasMDVec.empty()) {
2819 HasMD = HasMDVec[0];
2820 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2821 if (HasMD != HasMDVec[i]) {
2822 llvm_unreachable(
2823 "Kernels should have consistent work group size definition");
2824 }
2825 }
2826 }
2827
2828 // If all kernels do not have metadata for reqd_work_group_size, generate
2829 // OpSpecConstants for x/y/z dimension.
2830 if (!HasMD) {
2831 //
2832 // Generate OpSpecConstants for x/y/z dimension.
2833 //
2834 // Ops[0] : Result Type ID
2835 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2836 uint32_t XDimCstID = 0;
2837 uint32_t YDimCstID = 0;
2838 uint32_t ZDimCstID = 0;
2839
David Neto22f144c2017-06-12 14:26:21 -04002840 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002841 uint32_t result_type_id =
2842 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002843
David Neto257c3892018-04-11 13:19:45 -04002844 // X Dimension
2845 Ops << MkId(result_type_id) << MkNum(1);
2846 XDimCstID = nextID++;
2847 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002848 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002849
2850 // Y Dimension
2851 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002852 Ops << MkId(result_type_id) << MkNum(1);
2853 YDimCstID = nextID++;
2854 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002855 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002856
2857 // Z Dimension
2858 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002859 Ops << MkId(result_type_id) << MkNum(1);
2860 ZDimCstID = nextID++;
2861 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002862 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002863
David Neto257c3892018-04-11 13:19:45 -04002864 BuiltinDimVec.push_back(XDimCstID);
2865 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002866 BuiltinDimVec.push_back(ZDimCstID);
2867
David Neto22f144c2017-06-12 14:26:21 -04002868 //
2869 // Generate OpSpecConstantComposite.
2870 //
2871 // Ops[0] : Result Type ID
2872 // Ops[1] : Constant size for x dimension.
2873 // Ops[2] : Constant size for y dimension.
2874 // Ops[3] : Constant size for z dimension.
2875 InitializerID = nextID;
2876
2877 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002878 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2879 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002880
David Neto87846742018-04-11 17:36:22 -04002881 auto *Inst =
2882 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002883 SPIRVInstList.push_back(Inst);
2884 }
2885 }
2886
David Neto22f144c2017-06-12 14:26:21 -04002887 VMap[&GV] = nextID;
2888
2889 //
2890 // Generate OpVariable.
2891 //
2892 // GIDOps[0] : Result Type ID
2893 // GIDOps[1] : Storage Class
2894 SPIRVOperandList Ops;
2895
David Neto85082642018-03-24 06:55:20 -07002896 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002897 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002898
David Neto85082642018-03-24 06:55:20 -07002899 if (GV.hasInitializer()) {
2900 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002901 }
2902
David Neto85082642018-03-24 06:55:20 -07002903 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002904 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002905 clspv::Option::ModuleConstantsInStorageBuffer();
2906
2907 if (0 != InitializerID) {
2908 if (!module_scope_constant_external_init) {
2909 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002910 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002911 }
2912 }
2913 const uint32_t var_id = nextID++;
2914
David Neto87846742018-04-11 17:36:22 -04002915 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002916 SPIRVInstList.push_back(Inst);
2917
2918 // If we have a builtin.
2919 if (spv::BuiltInMax != BuiltinType) {
2920 // Find Insert Point for OpDecorate.
2921 auto DecoInsertPoint =
2922 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2923 [](SPIRVInstruction *Inst) -> bool {
2924 return Inst->getOpcode() != spv::OpDecorate &&
2925 Inst->getOpcode() != spv::OpMemberDecorate &&
2926 Inst->getOpcode() != spv::OpExtInstImport;
2927 });
2928 //
2929 // Generate OpDecorate.
2930 //
2931 // DOps[0] = Target ID
2932 // DOps[1] = Decoration (Builtin)
2933 // DOps[2] = BuiltIn ID
2934 uint32_t ResultID;
2935
2936 // WorkgroupSize is different, we decorate the constant composite that has
2937 // its value, rather than the variable that we use to access the value.
2938 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2939 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002940 // Save both the value and variable IDs for later.
2941 WorkgroupSizeValueID = InitializerID;
2942 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002943 } else {
2944 ResultID = VMap[&GV];
2945 }
2946
2947 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002948 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2949 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002950
David Neto87846742018-04-11 17:36:22 -04002951 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002952 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002953 } else if (module_scope_constant_external_init) {
2954 // This module scope constant is initialized from a storage buffer with data
2955 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002956 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002957
David Neto862b7d82018-06-14 18:48:37 -04002958 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002959 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2960 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002961 std::string hexbytes;
2962 llvm::raw_string_ostream str(hexbytes);
2963 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2964 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2965 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002966
2967 // Find Insert Point for OpDecorate.
2968 auto DecoInsertPoint =
2969 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2970 [](SPIRVInstruction *Inst) -> bool {
2971 return Inst->getOpcode() != spv::OpDecorate &&
2972 Inst->getOpcode() != spv::OpMemberDecorate &&
2973 Inst->getOpcode() != spv::OpExtInstImport;
2974 });
2975
David Neto257c3892018-04-11 13:19:45 -04002976 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002977 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002978 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2979 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002980 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002981
2982 // OpDecorate %var DescriptorSet <descriptor_set>
2983 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002984 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2985 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002986 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002987 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002988 }
2989}
2990
David Netoc6f3ab22018-04-06 18:02:31 -04002991void SPIRVProducerPass::GenerateWorkgroupVars() {
2992 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002993 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2994 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002995 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002996
2997 // Generate OpVariable.
2998 //
2999 // GIDOps[0] : Result Type ID
3000 // GIDOps[1] : Storage Class
3001 SPIRVOperandList Ops;
3002 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
3003
3004 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04003005 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003006 }
3007}
3008
David Neto862b7d82018-06-14 18:48:37 -04003009void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
3010 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04003011 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3012 return;
3013 }
David Neto862b7d82018-06-14 18:48:37 -04003014 // Gather the list of resources that are used by this function's arguments.
3015 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
3016
alan-bakerf5e5f692018-11-27 08:33:24 -05003017 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
3018 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04003019 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003020 std::string kind =
3021 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
3022 ? "pod_ubo"
3023 : argKind;
3024 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04003025 };
3026
3027 auto *fty = F.getType()->getPointerElementType();
3028 auto *func_ty = dyn_cast<FunctionType>(fty);
3029
3030 // If we've clustereed POD arguments, then argument details are in metadata.
3031 // If an argument maps to a resource variable, then get descriptor set and
3032 // binding from the resoure variable. Other info comes from the metadata.
3033 const auto *arg_map = F.getMetadata("kernel_arg_map");
3034 if (arg_map) {
3035 for (const auto &arg : arg_map->operands()) {
3036 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003037 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003038 const auto name =
3039 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3040 const auto old_index =
3041 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3042 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003043 const size_t new_index = static_cast<size_t>(
3044 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003045 const auto offset =
3046 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003047 const auto arg_size =
3048 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003049 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003050 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003051 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003052 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003053
3054 uint32_t descriptor_set = 0;
3055 uint32_t binding = 0;
3056 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3057 F.getName(),
3058 name,
3059 static_cast<uint32_t>(old_index),
3060 argKind,
3061 static_cast<uint32_t>(spec_id),
3062 // This will be set below for pointer-to-local args.
3063 0,
3064 static_cast<uint32_t>(offset),
3065 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003066 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003067 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3068 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3069 DL));
David Neto862b7d82018-06-14 18:48:37 -04003070 } else {
3071 auto *info = resource_var_at_index[new_index];
3072 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003073 descriptor_set = info->descriptor_set;
3074 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003075 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003076 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003077 }
3078 } else {
3079 // There is no argument map.
3080 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003081 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003082
3083 SmallVector<Argument *, 4> arguments;
3084 for (auto &arg : F.args()) {
3085 arguments.push_back(&arg);
3086 }
3087
3088 unsigned arg_index = 0;
3089 for (auto *info : resource_var_at_index) {
3090 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003091 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003092 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003093 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003094 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003095 }
3096
alan-bakerf5e5f692018-11-27 08:33:24 -05003097 // Local pointer arguments are unused in this case. Offset is always zero.
3098 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3099 F.getName(), arg->getName(),
3100 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3101 0, 0,
3102 0, arg_size};
3103 descriptorMapEntries->emplace_back(std::move(kernel_data),
3104 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003105 }
3106 arg_index++;
3107 }
3108 // Generate mappings for pointer-to-local arguments.
3109 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3110 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003111 auto where = LocalArgSpecIds.find(arg);
3112 if (where != LocalArgSpecIds.end()) {
3113 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003114 // Pod arguments members are unused in this case.
3115 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3116 F.getName(),
3117 arg->getName(),
3118 arg_index,
3119 ArgKind::Local,
3120 static_cast<uint32_t>(local_arg_info.spec_id),
3121 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3122 0,
3123 0};
3124 // Pointer-to-local arguments do not utilize descriptor set and binding.
3125 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003126 }
3127 }
3128 }
3129}
3130
David Neto22f144c2017-06-12 14:26:21 -04003131void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3132 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3133 ValueMapType &VMap = getValueMap();
3134 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003135 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3136 auto &GlobalConstArgSet = getGlobalConstArgSet();
3137
3138 FunctionType *FTy = F.getFunctionType();
3139
3140 //
David Neto22f144c2017-06-12 14:26:21 -04003141 // Generate OPFunction.
3142 //
3143
3144 // FOps[0] : Result Type ID
3145 // FOps[1] : Function Control
3146 // FOps[2] : Function Type ID
3147 SPIRVOperandList FOps;
3148
3149 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003150 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003151
3152 // Check function attributes for SPIRV Function Control.
3153 uint32_t FuncControl = spv::FunctionControlMaskNone;
3154 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3155 FuncControl |= spv::FunctionControlInlineMask;
3156 }
3157 if (F.hasFnAttribute(Attribute::NoInline)) {
3158 FuncControl |= spv::FunctionControlDontInlineMask;
3159 }
3160 // TODO: Check llvm attribute for Function Control Pure.
3161 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3162 FuncControl |= spv::FunctionControlPureMask;
3163 }
3164 // TODO: Check llvm attribute for Function Control Const.
3165 if (F.hasFnAttribute(Attribute::ReadNone)) {
3166 FuncControl |= spv::FunctionControlConstMask;
3167 }
3168
David Neto257c3892018-04-11 13:19:45 -04003169 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003170
3171 uint32_t FTyID;
3172 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3173 SmallVector<Type *, 4> NewFuncParamTys;
3174 FunctionType *NewFTy =
3175 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3176 FTyID = lookupType(NewFTy);
3177 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003178 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003179 if (GlobalConstFuncTyMap.count(FTy)) {
3180 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3181 } else {
3182 FTyID = lookupType(FTy);
3183 }
3184 }
3185
David Neto257c3892018-04-11 13:19:45 -04003186 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003187
3188 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3189 EntryPoints.push_back(std::make_pair(&F, nextID));
3190 }
3191
3192 VMap[&F] = nextID;
3193
David Neto482550a2018-03-24 05:21:07 -07003194 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003195 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3196 }
David Neto22f144c2017-06-12 14:26:21 -04003197 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003198 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003199 SPIRVInstList.push_back(FuncInst);
3200
3201 //
3202 // Generate OpFunctionParameter for Normal function.
3203 //
3204
3205 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3206 // Iterate Argument for name instead of param type from function type.
3207 unsigned ArgIdx = 0;
3208 for (Argument &Arg : F.args()) {
3209 VMap[&Arg] = nextID;
3210
3211 // ParamOps[0] : Result Type ID
3212 SPIRVOperandList ParamOps;
3213
3214 // Find SPIRV instruction for parameter type.
3215 uint32_t ParamTyID = lookupType(Arg.getType());
3216 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3217 if (GlobalConstFuncTyMap.count(FTy)) {
3218 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3219 Type *EleTy = PTy->getPointerElementType();
3220 Type *ArgTy =
3221 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3222 ParamTyID = lookupType(ArgTy);
3223 GlobalConstArgSet.insert(&Arg);
3224 }
3225 }
3226 }
David Neto257c3892018-04-11 13:19:45 -04003227 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003228
3229 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003230 auto *ParamInst =
3231 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003232 SPIRVInstList.push_back(ParamInst);
3233
3234 ArgIdx++;
3235 }
3236 }
3237}
3238
alan-bakerb6b09dc2018-11-08 16:59:28 -05003239void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003240 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3241 EntryPointVecType &EntryPoints = getEntryPointVec();
3242 ValueMapType &VMap = getValueMap();
3243 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3244 uint32_t &ExtInstImportID = getOpExtInstImportID();
3245 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3246
3247 // Set up insert point.
3248 auto InsertPoint = SPIRVInstList.begin();
3249
3250 //
3251 // Generate OpCapability
3252 //
3253 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3254
3255 // Ops[0] = Capability
3256 SPIRVOperandList Ops;
3257
David Neto87846742018-04-11 17:36:22 -04003258 auto *CapInst =
3259 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003260 SPIRVInstList.insert(InsertPoint, CapInst);
3261
3262 for (Type *Ty : getTypeList()) {
3263 // Find the i16 type.
3264 if (Ty->isIntegerTy(16)) {
3265 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003266 SPIRVInstList.insert(InsertPoint,
3267 new SPIRVInstruction(spv::OpCapability,
3268 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003269 } else if (Ty->isIntegerTy(64)) {
3270 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003271 SPIRVInstList.insert(InsertPoint,
3272 new SPIRVInstruction(spv::OpCapability,
3273 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003274 } else if (Ty->isHalfTy()) {
3275 // Generate OpCapability for half type.
3276 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003277 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3278 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003279 } else if (Ty->isDoubleTy()) {
3280 // Generate OpCapability for double type.
3281 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003282 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3283 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003284 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3285 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003286 if (STy->getName().equals("opencl.image2d_wo_t") ||
3287 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003288 // Generate OpCapability for write only image type.
3289 SPIRVInstList.insert(
3290 InsertPoint,
3291 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003292 spv::OpCapability,
3293 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003294 }
3295 }
3296 }
3297 }
3298
David Neto5c22a252018-03-15 16:07:41 -04003299 { // OpCapability ImageQuery
3300 bool hasImageQuery = false;
3301 for (const char *imageQuery : {
3302 "_Z15get_image_width14ocl_image2d_ro",
3303 "_Z15get_image_width14ocl_image2d_wo",
3304 "_Z16get_image_height14ocl_image2d_ro",
3305 "_Z16get_image_height14ocl_image2d_wo",
3306 }) {
3307 if (module.getFunction(imageQuery)) {
3308 hasImageQuery = true;
3309 break;
3310 }
3311 }
3312 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003313 auto *ImageQueryCapInst = new SPIRVInstruction(
3314 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003315 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3316 }
3317 }
3318
David Neto22f144c2017-06-12 14:26:21 -04003319 if (hasVariablePointers()) {
3320 //
David Neto22f144c2017-06-12 14:26:21 -04003321 // Generate OpCapability.
3322 //
3323 // Ops[0] = Capability
3324 //
3325 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003326 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003327
David Neto87846742018-04-11 17:36:22 -04003328 SPIRVInstList.insert(InsertPoint,
3329 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003330 } else if (hasVariablePointersStorageBuffer()) {
3331 //
3332 // Generate OpCapability.
3333 //
3334 // Ops[0] = Capability
3335 //
3336 Ops.clear();
3337 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003338
alan-baker5b86ed72019-02-15 08:26:50 -05003339 SPIRVInstList.insert(InsertPoint,
3340 new SPIRVInstruction(spv::OpCapability, Ops));
3341 }
3342
3343 // Always add the storage buffer extension
3344 {
David Neto22f144c2017-06-12 14:26:21 -04003345 //
3346 // Generate OpExtension.
3347 //
3348 // Ops[0] = Name (Literal String)
3349 //
alan-baker5b86ed72019-02-15 08:26:50 -05003350 auto *ExtensionInst = new SPIRVInstruction(
3351 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3352 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3353 }
David Neto22f144c2017-06-12 14:26:21 -04003354
alan-baker5b86ed72019-02-15 08:26:50 -05003355 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3356 //
3357 // Generate OpExtension.
3358 //
3359 // Ops[0] = Name (Literal String)
3360 //
3361 auto *ExtensionInst = new SPIRVInstruction(
3362 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3363 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003364 }
3365
3366 if (ExtInstImportID) {
3367 ++InsertPoint;
3368 }
3369
3370 //
3371 // Generate OpMemoryModel
3372 //
3373 // Memory model for Vulkan will always be GLSL450.
3374
3375 // Ops[0] = Addressing Model
3376 // Ops[1] = Memory Model
3377 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003378 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003379
David Neto87846742018-04-11 17:36:22 -04003380 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003381 SPIRVInstList.insert(InsertPoint, MemModelInst);
3382
3383 //
3384 // Generate OpEntryPoint
3385 //
3386 for (auto EntryPoint : EntryPoints) {
3387 // Ops[0] = Execution Model
3388 // Ops[1] = EntryPoint ID
3389 // Ops[2] = Name (Literal String)
3390 // ...
3391 //
3392 // TODO: Do we need to consider Interface ID for forward references???
3393 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003394 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003395 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3396 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003397
David Neto22f144c2017-06-12 14:26:21 -04003398 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003399 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003400 }
3401
David Neto87846742018-04-11 17:36:22 -04003402 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003403 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3404 }
3405
3406 for (auto EntryPoint : EntryPoints) {
3407 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3408 ->getMetadata("reqd_work_group_size")) {
3409
3410 if (!BuiltinDimVec.empty()) {
3411 llvm_unreachable(
3412 "Kernels should have consistent work group size definition");
3413 }
3414
3415 //
3416 // Generate OpExecutionMode
3417 //
3418
3419 // Ops[0] = Entry Point ID
3420 // Ops[1] = Execution Mode
3421 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3422 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003423 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003424
3425 uint32_t XDim = static_cast<uint32_t>(
3426 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3427 uint32_t YDim = static_cast<uint32_t>(
3428 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3429 uint32_t ZDim = static_cast<uint32_t>(
3430 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3431
David Neto257c3892018-04-11 13:19:45 -04003432 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003433
David Neto87846742018-04-11 17:36:22 -04003434 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003435 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3436 }
3437 }
3438
3439 //
3440 // Generate OpSource.
3441 //
3442 // Ops[0] = SourceLanguage ID
3443 // Ops[1] = Version (LiteralNum)
3444 //
3445 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003446 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003447
David Neto87846742018-04-11 17:36:22 -04003448 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003449 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3450
3451 if (!BuiltinDimVec.empty()) {
3452 //
3453 // Generate OpDecorates for x/y/z dimension.
3454 //
3455 // Ops[0] = Target ID
3456 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003457 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003458
3459 // X Dimension
3460 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003461 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003462 SPIRVInstList.insert(InsertPoint,
3463 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003464
3465 // Y Dimension
3466 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003467 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003468 SPIRVInstList.insert(InsertPoint,
3469 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003470
3471 // Z Dimension
3472 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003473 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003474 SPIRVInstList.insert(InsertPoint,
3475 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003476 }
3477}
3478
David Netob6e2e062018-04-25 10:32:06 -04003479void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3480 // Work around a driver bug. Initializers on Private variables might not
3481 // work. So the start of the kernel should store the initializer value to the
3482 // variables. Yes, *every* entry point pays this cost if *any* entry point
3483 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3484 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003485 // TODO(dneto): Remove this at some point once fixed drivers are widely
3486 // available.
David Netob6e2e062018-04-25 10:32:06 -04003487 if (WorkgroupSizeVarID) {
3488 assert(WorkgroupSizeValueID);
3489
3490 SPIRVOperandList Ops;
3491 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3492
3493 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3494 getSPIRVInstList().push_back(Inst);
3495 }
3496}
3497
David Neto22f144c2017-06-12 14:26:21 -04003498void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3499 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3500 ValueMapType &VMap = getValueMap();
3501
David Netob6e2e062018-04-25 10:32:06 -04003502 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003503
3504 for (BasicBlock &BB : F) {
3505 // Register BasicBlock to ValueMap.
3506 VMap[&BB] = nextID;
3507
3508 //
3509 // Generate OpLabel for Basic Block.
3510 //
3511 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003512 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003513 SPIRVInstList.push_back(Inst);
3514
David Neto6dcd4712017-06-23 11:06:47 -04003515 // OpVariable instructions must come first.
3516 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003517 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3518 // Allocating a pointer requires variable pointers.
3519 if (alloca->getAllocatedType()->isPointerTy()) {
3520 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3521 }
David Neto6dcd4712017-06-23 11:06:47 -04003522 GenerateInstruction(I);
3523 }
3524 }
3525
David Neto22f144c2017-06-12 14:26:21 -04003526 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003527 if (clspv::Option::HackInitializers()) {
3528 GenerateEntryPointInitialStores();
3529 }
David Neto22f144c2017-06-12 14:26:21 -04003530 }
3531
3532 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003533 if (!isa<AllocaInst>(I)) {
3534 GenerateInstruction(I);
3535 }
David Neto22f144c2017-06-12 14:26:21 -04003536 }
3537 }
3538}
3539
3540spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3541 const std::map<CmpInst::Predicate, spv::Op> Map = {
3542 {CmpInst::ICMP_EQ, spv::OpIEqual},
3543 {CmpInst::ICMP_NE, spv::OpINotEqual},
3544 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3545 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3546 {CmpInst::ICMP_ULT, spv::OpULessThan},
3547 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3548 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3549 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3550 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3551 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3552 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3553 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3554 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3555 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3556 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3557 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3558 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3559 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3560 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3561 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3562 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3563 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3564
3565 assert(0 != Map.count(I->getPredicate()));
3566
3567 return Map.at(I->getPredicate());
3568}
3569
3570spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3571 const std::map<unsigned, spv::Op> Map{
3572 {Instruction::Trunc, spv::OpUConvert},
3573 {Instruction::ZExt, spv::OpUConvert},
3574 {Instruction::SExt, spv::OpSConvert},
3575 {Instruction::FPToUI, spv::OpConvertFToU},
3576 {Instruction::FPToSI, spv::OpConvertFToS},
3577 {Instruction::UIToFP, spv::OpConvertUToF},
3578 {Instruction::SIToFP, spv::OpConvertSToF},
3579 {Instruction::FPTrunc, spv::OpFConvert},
3580 {Instruction::FPExt, spv::OpFConvert},
3581 {Instruction::BitCast, spv::OpBitcast}};
3582
3583 assert(0 != Map.count(I.getOpcode()));
3584
3585 return Map.at(I.getOpcode());
3586}
3587
3588spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003589 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003590 switch (I.getOpcode()) {
3591 default:
3592 break;
3593 case Instruction::Or:
3594 return spv::OpLogicalOr;
3595 case Instruction::And:
3596 return spv::OpLogicalAnd;
3597 case Instruction::Xor:
3598 return spv::OpLogicalNotEqual;
3599 }
3600 }
3601
alan-bakerb6b09dc2018-11-08 16:59:28 -05003602 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003603 {Instruction::Add, spv::OpIAdd},
3604 {Instruction::FAdd, spv::OpFAdd},
3605 {Instruction::Sub, spv::OpISub},
3606 {Instruction::FSub, spv::OpFSub},
3607 {Instruction::Mul, spv::OpIMul},
3608 {Instruction::FMul, spv::OpFMul},
3609 {Instruction::UDiv, spv::OpUDiv},
3610 {Instruction::SDiv, spv::OpSDiv},
3611 {Instruction::FDiv, spv::OpFDiv},
3612 {Instruction::URem, spv::OpUMod},
3613 {Instruction::SRem, spv::OpSRem},
3614 {Instruction::FRem, spv::OpFRem},
3615 {Instruction::Or, spv::OpBitwiseOr},
3616 {Instruction::Xor, spv::OpBitwiseXor},
3617 {Instruction::And, spv::OpBitwiseAnd},
3618 {Instruction::Shl, spv::OpShiftLeftLogical},
3619 {Instruction::LShr, spv::OpShiftRightLogical},
3620 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3621
3622 assert(0 != Map.count(I.getOpcode()));
3623
3624 return Map.at(I.getOpcode());
3625}
3626
3627void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3628 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3629 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003630 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3631 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3632
3633 // Register Instruction to ValueMap.
3634 if (0 == VMap[&I]) {
3635 VMap[&I] = nextID;
3636 }
3637
3638 switch (I.getOpcode()) {
3639 default: {
3640 if (Instruction::isCast(I.getOpcode())) {
3641 //
3642 // Generate SPIRV instructions for cast operators.
3643 //
3644
David Netod2de94a2017-08-28 17:27:47 -04003645 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003646 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003647 auto toI8 = Ty == Type::getInt8Ty(Context);
3648 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003649 // Handle zext, sext and uitofp with i1 type specially.
3650 if ((I.getOpcode() == Instruction::ZExt ||
3651 I.getOpcode() == Instruction::SExt ||
3652 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003653 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003654 //
3655 // Generate OpSelect.
3656 //
3657
3658 // Ops[0] = Result Type ID
3659 // Ops[1] = Condition ID
3660 // Ops[2] = True Constant ID
3661 // Ops[3] = False Constant ID
3662 SPIRVOperandList Ops;
3663
David Neto257c3892018-04-11 13:19:45 -04003664 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003665
David Neto22f144c2017-06-12 14:26:21 -04003666 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003667 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003668
3669 uint32_t TrueID = 0;
3670 if (I.getOpcode() == Instruction::ZExt) {
3671 APInt One(32, 1);
3672 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3673 } else if (I.getOpcode() == Instruction::SExt) {
3674 APInt MinusOne(32, UINT64_MAX, true);
3675 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3676 } else {
3677 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3678 }
David Neto257c3892018-04-11 13:19:45 -04003679 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003680
3681 uint32_t FalseID = 0;
3682 if (I.getOpcode() == Instruction::ZExt) {
3683 FalseID = VMap[Constant::getNullValue(I.getType())];
3684 } else if (I.getOpcode() == Instruction::SExt) {
3685 FalseID = VMap[Constant::getNullValue(I.getType())];
3686 } else {
3687 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3688 }
David Neto257c3892018-04-11 13:19:45 -04003689 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003690
David Neto87846742018-04-11 17:36:22 -04003691 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003692 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003693 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3694 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3695 // 8 bits.
3696 // Before:
3697 // %result = trunc i32 %a to i8
3698 // After
3699 // %result = OpBitwiseAnd %uint %a %uint_255
3700
3701 SPIRVOperandList Ops;
3702
David Neto257c3892018-04-11 13:19:45 -04003703 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003704
3705 Type *UintTy = Type::getInt32Ty(Context);
3706 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003707 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003708
David Neto87846742018-04-11 17:36:22 -04003709 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003710 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003711 } else {
3712 // Ops[0] = Result Type ID
3713 // Ops[1] = Source Value ID
3714 SPIRVOperandList Ops;
3715
David Neto257c3892018-04-11 13:19:45 -04003716 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003717
David Neto87846742018-04-11 17:36:22 -04003718 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003719 SPIRVInstList.push_back(Inst);
3720 }
3721 } else if (isa<BinaryOperator>(I)) {
3722 //
3723 // Generate SPIRV instructions for binary operators.
3724 //
3725
3726 // Handle xor with i1 type specially.
3727 if (I.getOpcode() == Instruction::Xor &&
3728 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003729 ((isa<ConstantInt>(I.getOperand(0)) &&
3730 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3731 (isa<ConstantInt>(I.getOperand(1)) &&
3732 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003733 //
3734 // Generate OpLogicalNot.
3735 //
3736 // Ops[0] = Result Type ID
3737 // Ops[1] = Operand
3738 SPIRVOperandList Ops;
3739
David Neto257c3892018-04-11 13:19:45 -04003740 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003741
3742 Value *CondV = I.getOperand(0);
3743 if (isa<Constant>(I.getOperand(0))) {
3744 CondV = I.getOperand(1);
3745 }
David Neto257c3892018-04-11 13:19:45 -04003746 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003747
David Neto87846742018-04-11 17:36:22 -04003748 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003749 SPIRVInstList.push_back(Inst);
3750 } else {
3751 // Ops[0] = Result Type ID
3752 // Ops[1] = Operand 0
3753 // Ops[2] = Operand 1
3754 SPIRVOperandList Ops;
3755
David Neto257c3892018-04-11 13:19:45 -04003756 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3757 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003758
David Neto87846742018-04-11 17:36:22 -04003759 auto *Inst =
3760 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003761 SPIRVInstList.push_back(Inst);
3762 }
3763 } else {
3764 I.print(errs());
3765 llvm_unreachable("Unsupported instruction???");
3766 }
3767 break;
3768 }
3769 case Instruction::GetElementPtr: {
3770 auto &GlobalConstArgSet = getGlobalConstArgSet();
3771
3772 //
3773 // Generate OpAccessChain.
3774 //
3775 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3776
3777 //
3778 // Generate OpAccessChain.
3779 //
3780
3781 // Ops[0] = Result Type ID
3782 // Ops[1] = Base ID
3783 // Ops[2] ... Ops[n] = Indexes ID
3784 SPIRVOperandList Ops;
3785
alan-bakerb6b09dc2018-11-08 16:59:28 -05003786 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003787 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3788 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3789 // Use pointer type with private address space for global constant.
3790 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003791 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003792 }
David Neto257c3892018-04-11 13:19:45 -04003793
3794 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003795
David Neto862b7d82018-06-14 18:48:37 -04003796 // Generate the base pointer.
3797 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003798
David Neto862b7d82018-06-14 18:48:37 -04003799 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003800
3801 //
3802 // Follows below rules for gep.
3803 //
David Neto862b7d82018-06-14 18:48:37 -04003804 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3805 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003806 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3807 // first index.
3808 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3809 // use gep's first index.
3810 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3811 // gep's first index.
3812 //
3813 spv::Op Opcode = spv::OpAccessChain;
3814 unsigned offset = 0;
3815 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003816 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003817 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003818 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003819 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003820 }
David Neto862b7d82018-06-14 18:48:37 -04003821 } else {
David Neto22f144c2017-06-12 14:26:21 -04003822 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003823 }
3824
3825 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003826 // Do we need to generate ArrayStride? Check against the GEP result type
3827 // rather than the pointer type of the base because when indexing into
3828 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3829 // for something else in the SPIR-V.
3830 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003831 auto address_space = ResultType->getAddressSpace();
3832 setVariablePointersCapabilities(address_space);
3833 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003834 case spv::StorageClassStorageBuffer:
3835 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003836 // Save the need to generate an ArrayStride decoration. But defer
3837 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003838 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003839 break;
3840 default:
3841 break;
David Neto1a1a0582017-07-07 12:01:44 -04003842 }
David Neto22f144c2017-06-12 14:26:21 -04003843 }
3844
3845 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003846 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003847 }
3848
David Neto87846742018-04-11 17:36:22 -04003849 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003850 SPIRVInstList.push_back(Inst);
3851 break;
3852 }
3853 case Instruction::ExtractValue: {
3854 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3855 // Ops[0] = Result Type ID
3856 // Ops[1] = Composite ID
3857 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3858 SPIRVOperandList Ops;
3859
David Neto257c3892018-04-11 13:19:45 -04003860 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003861
3862 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003863 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003864
3865 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003866 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003867 }
3868
David Neto87846742018-04-11 17:36:22 -04003869 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003870 SPIRVInstList.push_back(Inst);
3871 break;
3872 }
3873 case Instruction::InsertValue: {
3874 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3875 // Ops[0] = Result Type ID
3876 // Ops[1] = Object ID
3877 // Ops[2] = Composite ID
3878 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3879 SPIRVOperandList Ops;
3880
3881 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003882 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003883
3884 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003885 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003886
3887 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003888 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003889
3890 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003891 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003892 }
3893
David Neto87846742018-04-11 17:36:22 -04003894 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003895 SPIRVInstList.push_back(Inst);
3896 break;
3897 }
3898 case Instruction::Select: {
3899 //
3900 // Generate OpSelect.
3901 //
3902
3903 // Ops[0] = Result Type ID
3904 // Ops[1] = Condition ID
3905 // Ops[2] = True Constant ID
3906 // Ops[3] = False Constant ID
3907 SPIRVOperandList Ops;
3908
3909 // Find SPIRV instruction for parameter type.
3910 auto Ty = I.getType();
3911 if (Ty->isPointerTy()) {
3912 auto PointeeTy = Ty->getPointerElementType();
3913 if (PointeeTy->isStructTy() &&
3914 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3915 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003916 } else {
3917 // Selecting between pointers requires variable pointers.
3918 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3919 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3920 setVariablePointers(true);
3921 }
David Neto22f144c2017-06-12 14:26:21 -04003922 }
3923 }
3924
David Neto257c3892018-04-11 13:19:45 -04003925 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3926 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003927
David Neto87846742018-04-11 17:36:22 -04003928 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003929 SPIRVInstList.push_back(Inst);
3930 break;
3931 }
3932 case Instruction::ExtractElement: {
3933 // Handle <4 x i8> type manually.
3934 Type *CompositeTy = I.getOperand(0)->getType();
3935 if (is4xi8vec(CompositeTy)) {
3936 //
3937 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3938 // <4 x i8>.
3939 //
3940
3941 //
3942 // Generate OpShiftRightLogical
3943 //
3944 // Ops[0] = Result Type ID
3945 // Ops[1] = Operand 0
3946 // Ops[2] = Operand 1
3947 //
3948 SPIRVOperandList Ops;
3949
David Neto257c3892018-04-11 13:19:45 -04003950 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003951
3952 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003953 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003954
3955 uint32_t Op1ID = 0;
3956 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3957 // Handle constant index.
3958 uint64_t Idx = CI->getZExtValue();
3959 Value *ShiftAmount =
3960 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3961 Op1ID = VMap[ShiftAmount];
3962 } else {
3963 // Handle variable index.
3964 SPIRVOperandList TmpOps;
3965
David Neto257c3892018-04-11 13:19:45 -04003966 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3967 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003968
3969 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003970 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003971
3972 Op1ID = nextID;
3973
David Neto87846742018-04-11 17:36:22 -04003974 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003975 SPIRVInstList.push_back(TmpInst);
3976 }
David Neto257c3892018-04-11 13:19:45 -04003977 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003978
3979 uint32_t ShiftID = nextID;
3980
David Neto87846742018-04-11 17:36:22 -04003981 auto *Inst =
3982 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003983 SPIRVInstList.push_back(Inst);
3984
3985 //
3986 // Generate OpBitwiseAnd
3987 //
3988 // Ops[0] = Result Type ID
3989 // Ops[1] = Operand 0
3990 // Ops[2] = Operand 1
3991 //
3992 Ops.clear();
3993
David Neto257c3892018-04-11 13:19:45 -04003994 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003995
3996 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003997 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003998
David Neto9b2d6252017-09-06 15:47:37 -04003999 // Reset mapping for this value to the result of the bitwise and.
4000 VMap[&I] = nextID;
4001
David Neto87846742018-04-11 17:36:22 -04004002 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004003 SPIRVInstList.push_back(Inst);
4004 break;
4005 }
4006
4007 // Ops[0] = Result Type ID
4008 // Ops[1] = Composite ID
4009 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4010 SPIRVOperandList Ops;
4011
David Neto257c3892018-04-11 13:19:45 -04004012 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004013
4014 spv::Op Opcode = spv::OpCompositeExtract;
4015 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04004016 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04004017 } else {
David Neto257c3892018-04-11 13:19:45 -04004018 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004019 Opcode = spv::OpVectorExtractDynamic;
4020 }
4021
David Neto87846742018-04-11 17:36:22 -04004022 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004023 SPIRVInstList.push_back(Inst);
4024 break;
4025 }
4026 case Instruction::InsertElement: {
4027 // Handle <4 x i8> type manually.
4028 Type *CompositeTy = I.getOperand(0)->getType();
4029 if (is4xi8vec(CompositeTy)) {
4030 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4031 uint32_t CstFFID = VMap[CstFF];
4032
4033 uint32_t ShiftAmountID = 0;
4034 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4035 // Handle constant index.
4036 uint64_t Idx = CI->getZExtValue();
4037 Value *ShiftAmount =
4038 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4039 ShiftAmountID = VMap[ShiftAmount];
4040 } else {
4041 // Handle variable index.
4042 SPIRVOperandList TmpOps;
4043
David Neto257c3892018-04-11 13:19:45 -04004044 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4045 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004046
4047 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004048 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004049
4050 ShiftAmountID = nextID;
4051
David Neto87846742018-04-11 17:36:22 -04004052 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004053 SPIRVInstList.push_back(TmpInst);
4054 }
4055
4056 //
4057 // Generate mask operations.
4058 //
4059
4060 // ShiftLeft mask according to index of insertelement.
4061 SPIRVOperandList Ops;
4062
David Neto257c3892018-04-11 13:19:45 -04004063 const uint32_t ResTyID = lookupType(CompositeTy);
4064 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004065
4066 uint32_t MaskID = nextID;
4067
David Neto87846742018-04-11 17:36:22 -04004068 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004069 SPIRVInstList.push_back(Inst);
4070
4071 // Inverse mask.
4072 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004073 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004074
4075 uint32_t InvMaskID = nextID;
4076
David Neto87846742018-04-11 17:36:22 -04004077 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004078 SPIRVInstList.push_back(Inst);
4079
4080 // Apply mask.
4081 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004082 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004083
4084 uint32_t OrgValID = nextID;
4085
David Neto87846742018-04-11 17:36:22 -04004086 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004087 SPIRVInstList.push_back(Inst);
4088
4089 // Create correct value according to index of insertelement.
4090 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004091 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4092 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004093
4094 uint32_t InsertValID = nextID;
4095
David Neto87846742018-04-11 17:36:22 -04004096 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004097 SPIRVInstList.push_back(Inst);
4098
4099 // Insert value to original value.
4100 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004101 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004102
David Netoa394f392017-08-26 20:45:29 -04004103 VMap[&I] = nextID;
4104
David Neto87846742018-04-11 17:36:22 -04004105 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004106 SPIRVInstList.push_back(Inst);
4107
4108 break;
4109 }
4110
David Neto22f144c2017-06-12 14:26:21 -04004111 SPIRVOperandList Ops;
4112
James Priced26efea2018-06-09 23:28:32 +01004113 // Ops[0] = Result Type ID
4114 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004115
4116 spv::Op Opcode = spv::OpCompositeInsert;
4117 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004118 const auto value = CI->getZExtValue();
4119 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004120 // Ops[1] = Object ID
4121 // Ops[2] = Composite ID
4122 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004123 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004124 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004125 } else {
James Priced26efea2018-06-09 23:28:32 +01004126 // Ops[1] = Composite ID
4127 // Ops[2] = Object ID
4128 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004129 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004130 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004131 Opcode = spv::OpVectorInsertDynamic;
4132 }
4133
David Neto87846742018-04-11 17:36:22 -04004134 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004135 SPIRVInstList.push_back(Inst);
4136 break;
4137 }
4138 case Instruction::ShuffleVector: {
4139 // Ops[0] = Result Type ID
4140 // Ops[1] = Vector 1 ID
4141 // Ops[2] = Vector 2 ID
4142 // Ops[3] ... Ops[n] = Components (Literal Number)
4143 SPIRVOperandList Ops;
4144
David Neto257c3892018-04-11 13:19:45 -04004145 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4146 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004147
4148 uint64_t NumElements = 0;
4149 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4150 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4151
4152 if (Cst->isNullValue()) {
4153 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004154 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004155 }
4156 } else if (const ConstantDataSequential *CDS =
4157 dyn_cast<ConstantDataSequential>(Cst)) {
4158 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4159 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004160 const auto value = CDS->getElementAsInteger(i);
4161 assert(value <= UINT32_MAX);
4162 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004163 }
4164 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4165 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4166 auto Op = CV->getOperand(i);
4167
4168 uint32_t literal = 0;
4169
4170 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4171 literal = static_cast<uint32_t>(CI->getZExtValue());
4172 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4173 literal = 0xFFFFFFFFu;
4174 } else {
4175 Op->print(errs());
4176 llvm_unreachable("Unsupported element in ConstantVector!");
4177 }
4178
David Neto257c3892018-04-11 13:19:45 -04004179 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004180 }
4181 } else {
4182 Cst->print(errs());
4183 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4184 }
4185 }
4186
David Neto87846742018-04-11 17:36:22 -04004187 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004188 SPIRVInstList.push_back(Inst);
4189 break;
4190 }
4191 case Instruction::ICmp:
4192 case Instruction::FCmp: {
4193 CmpInst *CmpI = cast<CmpInst>(&I);
4194
David Netod4ca2e62017-07-06 18:47:35 -04004195 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004196 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004197 if (isa<PointerType>(ArgTy)) {
4198 CmpI->print(errs());
4199 std::string name = I.getParent()->getParent()->getName();
4200 errs()
4201 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4202 << "in function " << name << "\n";
4203 llvm_unreachable("Pointer equality check is invalid");
4204 break;
4205 }
4206
David Neto257c3892018-04-11 13:19:45 -04004207 // Ops[0] = Result Type ID
4208 // Ops[1] = Operand 1 ID
4209 // Ops[2] = Operand 2 ID
4210 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004211
David Neto257c3892018-04-11 13:19:45 -04004212 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4213 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004214
4215 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004216 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004217 SPIRVInstList.push_back(Inst);
4218 break;
4219 }
4220 case Instruction::Br: {
4221 // Branch instrucion is deferred because it needs label's ID. Record slot's
4222 // location on SPIRVInstructionList.
4223 DeferredInsts.push_back(
4224 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4225 break;
4226 }
4227 case Instruction::Switch: {
4228 I.print(errs());
4229 llvm_unreachable("Unsupported instruction???");
4230 break;
4231 }
4232 case Instruction::IndirectBr: {
4233 I.print(errs());
4234 llvm_unreachable("Unsupported instruction???");
4235 break;
4236 }
4237 case Instruction::PHI: {
4238 // Branch instrucion is deferred because it needs label's ID. Record slot's
4239 // location on SPIRVInstructionList.
4240 DeferredInsts.push_back(
4241 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4242 break;
4243 }
4244 case Instruction::Alloca: {
4245 //
4246 // Generate OpVariable.
4247 //
4248 // Ops[0] : Result Type ID
4249 // Ops[1] : Storage Class
4250 SPIRVOperandList Ops;
4251
David Neto257c3892018-04-11 13:19:45 -04004252 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004253
David Neto87846742018-04-11 17:36:22 -04004254 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004255 SPIRVInstList.push_back(Inst);
4256 break;
4257 }
4258 case Instruction::Load: {
4259 LoadInst *LD = cast<LoadInst>(&I);
4260 //
4261 // Generate OpLoad.
4262 //
alan-baker5b86ed72019-02-15 08:26:50 -05004263
4264 if (LD->getType()->isPointerTy()) {
4265 // Loading a pointer requires variable pointers.
4266 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4267 }
David Neto22f144c2017-06-12 14:26:21 -04004268
David Neto0a2f98d2017-09-15 19:38:40 -04004269 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004270 uint32_t PointerID = VMap[LD->getPointerOperand()];
4271
4272 // This is a hack to work around what looks like a driver bug.
4273 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004274 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4275 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004276 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004277 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004278 // Generate a bitwise-and of the original value with itself.
4279 // We should have been able to get away with just an OpCopyObject,
4280 // but we need something more complex to get past certain driver bugs.
4281 // This is ridiculous, but necessary.
4282 // TODO(dneto): Revisit this once drivers fix their bugs.
4283
4284 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004285 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4286 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004287
David Neto87846742018-04-11 17:36:22 -04004288 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004289 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004290 break;
4291 }
4292
4293 // This is the normal path. Generate a load.
4294
David Neto22f144c2017-06-12 14:26:21 -04004295 // Ops[0] = Result Type ID
4296 // Ops[1] = Pointer ID
4297 // Ops[2] ... Ops[n] = Optional Memory Access
4298 //
4299 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004300
David Neto22f144c2017-06-12 14:26:21 -04004301 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004302 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004303
David Neto87846742018-04-11 17:36:22 -04004304 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004305 SPIRVInstList.push_back(Inst);
4306 break;
4307 }
4308 case Instruction::Store: {
4309 StoreInst *ST = cast<StoreInst>(&I);
4310 //
4311 // Generate OpStore.
4312 //
4313
alan-baker5b86ed72019-02-15 08:26:50 -05004314 if (ST->getValueOperand()->getType()->isPointerTy()) {
4315 // Storing a pointer requires variable pointers.
4316 setVariablePointersCapabilities(
4317 ST->getValueOperand()->getType()->getPointerAddressSpace());
4318 }
4319
David Neto22f144c2017-06-12 14:26:21 -04004320 // Ops[0] = Pointer ID
4321 // Ops[1] = Object ID
4322 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4323 //
4324 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004325 SPIRVOperandList Ops;
4326 Ops << MkId(VMap[ST->getPointerOperand()])
4327 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004328
David Neto87846742018-04-11 17:36:22 -04004329 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004330 SPIRVInstList.push_back(Inst);
4331 break;
4332 }
4333 case Instruction::AtomicCmpXchg: {
4334 I.print(errs());
4335 llvm_unreachable("Unsupported instruction???");
4336 break;
4337 }
4338 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004339 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4340
4341 spv::Op opcode;
4342
4343 switch (AtomicRMW->getOperation()) {
4344 default:
4345 I.print(errs());
4346 llvm_unreachable("Unsupported instruction???");
4347 case llvm::AtomicRMWInst::Add:
4348 opcode = spv::OpAtomicIAdd;
4349 break;
4350 case llvm::AtomicRMWInst::Sub:
4351 opcode = spv::OpAtomicISub;
4352 break;
4353 case llvm::AtomicRMWInst::Xchg:
4354 opcode = spv::OpAtomicExchange;
4355 break;
4356 case llvm::AtomicRMWInst::Min:
4357 opcode = spv::OpAtomicSMin;
4358 break;
4359 case llvm::AtomicRMWInst::Max:
4360 opcode = spv::OpAtomicSMax;
4361 break;
4362 case llvm::AtomicRMWInst::UMin:
4363 opcode = spv::OpAtomicUMin;
4364 break;
4365 case llvm::AtomicRMWInst::UMax:
4366 opcode = spv::OpAtomicUMax;
4367 break;
4368 case llvm::AtomicRMWInst::And:
4369 opcode = spv::OpAtomicAnd;
4370 break;
4371 case llvm::AtomicRMWInst::Or:
4372 opcode = spv::OpAtomicOr;
4373 break;
4374 case llvm::AtomicRMWInst::Xor:
4375 opcode = spv::OpAtomicXor;
4376 break;
4377 }
4378
4379 //
4380 // Generate OpAtomic*.
4381 //
4382 SPIRVOperandList Ops;
4383
David Neto257c3892018-04-11 13:19:45 -04004384 Ops << MkId(lookupType(I.getType()))
4385 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004386
4387 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004388 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004389 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004390
4391 const auto ConstantMemorySemantics = ConstantInt::get(
4392 IntTy, spv::MemorySemanticsUniformMemoryMask |
4393 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004394 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004395
David Neto257c3892018-04-11 13:19:45 -04004396 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004397
4398 VMap[&I] = nextID;
4399
David Neto87846742018-04-11 17:36:22 -04004400 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004401 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004402 break;
4403 }
4404 case Instruction::Fence: {
4405 I.print(errs());
4406 llvm_unreachable("Unsupported instruction???");
4407 break;
4408 }
4409 case Instruction::Call: {
4410 CallInst *Call = dyn_cast<CallInst>(&I);
4411 Function *Callee = Call->getCalledFunction();
4412
Alan Baker202c8c72018-08-13 13:47:44 -04004413 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004414 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4415 // Generate an OpLoad
4416 SPIRVOperandList Ops;
4417 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004418
David Neto862b7d82018-06-14 18:48:37 -04004419 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4420 << MkId(ResourceVarDeferredLoadCalls[Call]);
4421
4422 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4423 SPIRVInstList.push_back(Inst);
4424 VMap[Call] = load_id;
4425 break;
4426
4427 } else {
4428 // This maps to an OpVariable we've already generated.
4429 // No code is generated for the call.
4430 }
4431 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004432 } else if (Callee->getName().startswith(
4433 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004434 // Don't codegen an instruction here, but instead map this call directly
4435 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004436 int spec_id = static_cast<int>(
4437 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004438 const auto &info = LocalSpecIdInfoMap[spec_id];
4439 VMap[Call] = info.variable_id;
4440 break;
David Neto862b7d82018-06-14 18:48:37 -04004441 }
4442
4443 // Sampler initializers become a load of the corresponding sampler.
4444
4445 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4446 // Map this to a load from the variable.
4447 const auto index_into_sampler_map =
4448 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4449
4450 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004451 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004452 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004453
David Neto257c3892018-04-11 13:19:45 -04004454 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004455 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4456 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004457
David Neto862b7d82018-06-14 18:48:37 -04004458 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004459 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004460 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004461 break;
4462 }
4463
4464 if (Callee->getName().startswith("spirv.atomic")) {
4465 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4466 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4467 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4468 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4469 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4470 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4471 .Case("spirv.atomic_compare_exchange",
4472 spv::OpAtomicCompareExchange)
4473 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4474 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4475 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4476 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4477 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4478 .Case("spirv.atomic_or", spv::OpAtomicOr)
4479 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4480 .Default(spv::OpNop);
4481
4482 //
4483 // Generate OpAtomic*.
4484 //
4485 SPIRVOperandList Ops;
4486
David Neto257c3892018-04-11 13:19:45 -04004487 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004488
4489 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004490 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004491 }
4492
4493 VMap[&I] = nextID;
4494
David Neto87846742018-04-11 17:36:22 -04004495 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004496 SPIRVInstList.push_back(Inst);
4497 break;
4498 }
4499
4500 if (Callee->getName().startswith("_Z3dot")) {
4501 // If the argument is a vector type, generate OpDot
4502 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4503 //
4504 // Generate OpDot.
4505 //
4506 SPIRVOperandList Ops;
4507
David Neto257c3892018-04-11 13:19:45 -04004508 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004509
4510 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004511 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004512 }
4513
4514 VMap[&I] = nextID;
4515
David Neto87846742018-04-11 17:36:22 -04004516 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004517 SPIRVInstList.push_back(Inst);
4518 } else {
4519 //
4520 // Generate OpFMul.
4521 //
4522 SPIRVOperandList Ops;
4523
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004525
4526 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004527 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004528 }
4529
4530 VMap[&I] = nextID;
4531
David Neto87846742018-04-11 17:36:22 -04004532 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004533 SPIRVInstList.push_back(Inst);
4534 }
4535 break;
4536 }
4537
David Neto8505ebf2017-10-13 18:50:50 -04004538 if (Callee->getName().startswith("_Z4fmod")) {
4539 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4540 // The sign for a non-zero result is taken from x.
4541 // (Try an example.)
4542 // So translate to OpFRem
4543
4544 SPIRVOperandList Ops;
4545
David Neto257c3892018-04-11 13:19:45 -04004546 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004547
4548 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004549 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004550 }
4551
4552 VMap[&I] = nextID;
4553
David Neto87846742018-04-11 17:36:22 -04004554 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004555 SPIRVInstList.push_back(Inst);
4556 break;
4557 }
4558
David Neto22f144c2017-06-12 14:26:21 -04004559 // spirv.store_null.* intrinsics become OpStore's.
4560 if (Callee->getName().startswith("spirv.store_null")) {
4561 //
4562 // Generate OpStore.
4563 //
4564
4565 // Ops[0] = Pointer ID
4566 // Ops[1] = Object ID
4567 // Ops[2] ... Ops[n]
4568 SPIRVOperandList Ops;
4569
4570 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004571 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004572 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004573
David Neto87846742018-04-11 17:36:22 -04004574 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004575
4576 break;
4577 }
4578
4579 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4580 if (Callee->getName().startswith("spirv.copy_memory")) {
4581 //
4582 // Generate OpCopyMemory.
4583 //
4584
4585 // Ops[0] = Dst ID
4586 // Ops[1] = Src ID
4587 // Ops[2] = Memory Access
4588 // Ops[3] = Alignment
4589
4590 auto IsVolatile =
4591 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4592
4593 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4594 : spv::MemoryAccessMaskNone;
4595
4596 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4597
4598 auto Alignment =
4599 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4600
David Neto257c3892018-04-11 13:19:45 -04004601 SPIRVOperandList Ops;
4602 Ops << MkId(VMap[Call->getArgOperand(0)])
4603 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4604 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004605
David Neto87846742018-04-11 17:36:22 -04004606 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004607
4608 SPIRVInstList.push_back(Inst);
4609
4610 break;
4611 }
4612
4613 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4614 // with unit.
4615 if (Callee->getName().equals("_Z3absj") ||
4616 Callee->getName().equals("_Z3absDv2_j") ||
4617 Callee->getName().equals("_Z3absDv3_j") ||
4618 Callee->getName().equals("_Z3absDv4_j")) {
4619 VMap[&I] = VMap[Call->getOperand(0)];
4620 break;
4621 }
4622
4623 // barrier is converted to OpControlBarrier
4624 if (Callee->getName().equals("__spirv_control_barrier")) {
4625 //
4626 // Generate OpControlBarrier.
4627 //
4628 // Ops[0] = Execution Scope ID
4629 // Ops[1] = Memory Scope ID
4630 // Ops[2] = Memory Semantics ID
4631 //
4632 Value *ExecutionScope = Call->getArgOperand(0);
4633 Value *MemoryScope = Call->getArgOperand(1);
4634 Value *MemorySemantics = Call->getArgOperand(2);
4635
David Neto257c3892018-04-11 13:19:45 -04004636 SPIRVOperandList Ops;
4637 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4638 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004639
David Neto87846742018-04-11 17:36:22 -04004640 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004641 break;
4642 }
4643
4644 // memory barrier is converted to OpMemoryBarrier
4645 if (Callee->getName().equals("__spirv_memory_barrier")) {
4646 //
4647 // Generate OpMemoryBarrier.
4648 //
4649 // Ops[0] = Memory Scope ID
4650 // Ops[1] = Memory Semantics ID
4651 //
4652 SPIRVOperandList Ops;
4653
David Neto257c3892018-04-11 13:19:45 -04004654 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4655 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004656
David Neto257c3892018-04-11 13:19:45 -04004657 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004658
David Neto87846742018-04-11 17:36:22 -04004659 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004660 SPIRVInstList.push_back(Inst);
4661 break;
4662 }
4663
4664 // isinf is converted to OpIsInf
4665 if (Callee->getName().equals("__spirv_isinff") ||
4666 Callee->getName().equals("__spirv_isinfDv2_f") ||
4667 Callee->getName().equals("__spirv_isinfDv3_f") ||
4668 Callee->getName().equals("__spirv_isinfDv4_f")) {
4669 //
4670 // Generate OpIsInf.
4671 //
4672 // Ops[0] = Result Type ID
4673 // Ops[1] = X ID
4674 //
4675 SPIRVOperandList Ops;
4676
David Neto257c3892018-04-11 13:19:45 -04004677 Ops << MkId(lookupType(I.getType()))
4678 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004679
4680 VMap[&I] = nextID;
4681
David Neto87846742018-04-11 17:36:22 -04004682 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004683 SPIRVInstList.push_back(Inst);
4684 break;
4685 }
4686
4687 // isnan is converted to OpIsNan
4688 if (Callee->getName().equals("__spirv_isnanf") ||
4689 Callee->getName().equals("__spirv_isnanDv2_f") ||
4690 Callee->getName().equals("__spirv_isnanDv3_f") ||
4691 Callee->getName().equals("__spirv_isnanDv4_f")) {
4692 //
4693 // Generate OpIsInf.
4694 //
4695 // Ops[0] = Result Type ID
4696 // Ops[1] = X ID
4697 //
4698 SPIRVOperandList Ops;
4699
David Neto257c3892018-04-11 13:19:45 -04004700 Ops << MkId(lookupType(I.getType()))
4701 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004702
4703 VMap[&I] = nextID;
4704
David Neto87846742018-04-11 17:36:22 -04004705 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004706 SPIRVInstList.push_back(Inst);
4707 break;
4708 }
4709
4710 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004711 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004712 //
4713 // Generate OpAll.
4714 //
4715 // Ops[0] = Result Type ID
4716 // Ops[1] = Vector ID
4717 //
4718 SPIRVOperandList Ops;
4719
David Neto257c3892018-04-11 13:19:45 -04004720 Ops << MkId(lookupType(I.getType()))
4721 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004722
4723 VMap[&I] = nextID;
4724
David Neto87846742018-04-11 17:36:22 -04004725 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004726 SPIRVInstList.push_back(Inst);
4727 break;
4728 }
4729
4730 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004731 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004732 //
4733 // Generate OpAny.
4734 //
4735 // Ops[0] = Result Type ID
4736 // Ops[1] = Vector ID
4737 //
4738 SPIRVOperandList Ops;
4739
David Neto257c3892018-04-11 13:19:45 -04004740 Ops << MkId(lookupType(I.getType()))
4741 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004742
4743 VMap[&I] = nextID;
4744
David Neto87846742018-04-11 17:36:22 -04004745 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004746 SPIRVInstList.push_back(Inst);
4747 break;
4748 }
4749
4750 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4751 // Additionally, OpTypeSampledImage is generated.
4752 if (Callee->getName().equals(
4753 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4754 Callee->getName().equals(
4755 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4756 //
4757 // Generate OpSampledImage.
4758 //
4759 // Ops[0] = Result Type ID
4760 // Ops[1] = Image ID
4761 // Ops[2] = Sampler ID
4762 //
4763 SPIRVOperandList Ops;
4764
4765 Value *Image = Call->getArgOperand(0);
4766 Value *Sampler = Call->getArgOperand(1);
4767 Value *Coordinate = Call->getArgOperand(2);
4768
4769 TypeMapType &OpImageTypeMap = getImageTypeMap();
4770 Type *ImageTy = Image->getType()->getPointerElementType();
4771 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004772 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004773 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004774
4775 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004776
4777 uint32_t SampledImageID = nextID;
4778
David Neto87846742018-04-11 17:36:22 -04004779 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004780 SPIRVInstList.push_back(Inst);
4781
4782 //
4783 // Generate OpImageSampleExplicitLod.
4784 //
4785 // Ops[0] = Result Type ID
4786 // Ops[1] = Sampled Image ID
4787 // Ops[2] = Coordinate ID
4788 // Ops[3] = Image Operands Type ID
4789 // Ops[4] ... Ops[n] = Operands ID
4790 //
4791 Ops.clear();
4792
David Neto257c3892018-04-11 13:19:45 -04004793 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4794 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004795
4796 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004797 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004798
4799 VMap[&I] = nextID;
4800
David Neto87846742018-04-11 17:36:22 -04004801 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004802 SPIRVInstList.push_back(Inst);
4803 break;
4804 }
4805
4806 // write_imagef is mapped to OpImageWrite.
4807 if (Callee->getName().equals(
4808 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4809 Callee->getName().equals(
4810 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4811 //
4812 // Generate OpImageWrite.
4813 //
4814 // Ops[0] = Image ID
4815 // Ops[1] = Coordinate ID
4816 // Ops[2] = Texel ID
4817 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4818 // Ops[4] ... Ops[n] = (Optional) Operands ID
4819 //
4820 SPIRVOperandList Ops;
4821
4822 Value *Image = Call->getArgOperand(0);
4823 Value *Coordinate = Call->getArgOperand(1);
4824 Value *Texel = Call->getArgOperand(2);
4825
4826 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004827 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004828 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004829 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004830
David Neto87846742018-04-11 17:36:22 -04004831 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004832 SPIRVInstList.push_back(Inst);
4833 break;
4834 }
4835
David Neto5c22a252018-03-15 16:07:41 -04004836 // get_image_width is mapped to OpImageQuerySize
4837 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4838 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4839 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4840 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4841 //
4842 // Generate OpImageQuerySize, then pull out the right component.
4843 // Assume 2D image for now.
4844 //
4845 // Ops[0] = Image ID
4846 //
4847 // %sizes = OpImageQuerySizes %uint2 %im
4848 // %result = OpCompositeExtract %uint %sizes 0-or-1
4849 SPIRVOperandList Ops;
4850
4851 // Implement:
4852 // %sizes = OpImageQuerySizes %uint2 %im
4853 uint32_t SizesTypeID =
4854 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004855 Value *Image = Call->getArgOperand(0);
4856 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004857 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004858
4859 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004860 auto *QueryInst =
4861 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004862 SPIRVInstList.push_back(QueryInst);
4863
4864 // Reset value map entry since we generated an intermediate instruction.
4865 VMap[&I] = nextID;
4866
4867 // Implement:
4868 // %result = OpCompositeExtract %uint %sizes 0-or-1
4869 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004870 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004871
4872 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004873 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004874
David Neto87846742018-04-11 17:36:22 -04004875 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004876 SPIRVInstList.push_back(Inst);
4877 break;
4878 }
4879
David Neto22f144c2017-06-12 14:26:21 -04004880 // Call instrucion is deferred because it needs function's ID. Record
4881 // slot's location on SPIRVInstructionList.
4882 DeferredInsts.push_back(
4883 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4884
David Neto3fbb4072017-10-16 11:28:14 -04004885 // Check whether the implementation of this call uses an extended
4886 // instruction plus one more value-producing instruction. If so, then
4887 // reserve the id for the extra value-producing slot.
4888 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4889 if (EInst != kGlslExtInstBad) {
4890 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004891 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004892 VMap[&I] = nextID;
4893 nextID++;
4894 }
4895 break;
4896 }
4897 case Instruction::Ret: {
4898 unsigned NumOps = I.getNumOperands();
4899 if (NumOps == 0) {
4900 //
4901 // Generate OpReturn.
4902 //
David Neto87846742018-04-11 17:36:22 -04004903 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004904 } else {
4905 //
4906 // Generate OpReturnValue.
4907 //
4908
4909 // Ops[0] = Return Value ID
4910 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004911
4912 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004913
David Neto87846742018-04-11 17:36:22 -04004914 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004915 SPIRVInstList.push_back(Inst);
4916 break;
4917 }
4918 break;
4919 }
4920 }
4921}
4922
4923void SPIRVProducerPass::GenerateFuncEpilogue() {
4924 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4925
4926 //
4927 // Generate OpFunctionEnd
4928 //
4929
David Neto87846742018-04-11 17:36:22 -04004930 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004931 SPIRVInstList.push_back(Inst);
4932}
4933
4934bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4935 LLVMContext &Context = Ty->getContext();
4936 if (Ty->isVectorTy()) {
4937 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4938 Ty->getVectorNumElements() == 4) {
4939 return true;
4940 }
4941 }
4942
4943 return false;
4944}
4945
David Neto257c3892018-04-11 13:19:45 -04004946uint32_t SPIRVProducerPass::GetI32Zero() {
4947 if (0 == constant_i32_zero_id_) {
4948 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4949 "defined in the SPIR-V module");
4950 }
4951 return constant_i32_zero_id_;
4952}
4953
David Neto22f144c2017-06-12 14:26:21 -04004954void SPIRVProducerPass::HandleDeferredInstruction() {
4955 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4956 ValueMapType &VMap = getValueMap();
4957 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4958
4959 for (auto DeferredInst = DeferredInsts.rbegin();
4960 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4961 Value *Inst = std::get<0>(*DeferredInst);
4962 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4963 if (InsertPoint != SPIRVInstList.end()) {
4964 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4965 ++InsertPoint;
4966 }
4967 }
4968
4969 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4970 // Check whether basic block, which has this branch instruction, is loop
4971 // header or not. If it is loop header, generate OpLoopMerge and
4972 // OpBranchConditional.
4973 Function *Func = Br->getParent()->getParent();
4974 DominatorTree &DT =
4975 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4976 const LoopInfo &LI =
4977 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4978
4979 BasicBlock *BrBB = Br->getParent();
4980 if (LI.isLoopHeader(BrBB)) {
4981 Value *ContinueBB = nullptr;
4982 Value *MergeBB = nullptr;
4983
4984 Loop *L = LI.getLoopFor(BrBB);
4985 MergeBB = L->getExitBlock();
4986 if (!MergeBB) {
4987 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4988 // has regions with single entry/exit. As a result, loop should not
4989 // have multiple exits.
4990 llvm_unreachable("Loop has multiple exits???");
4991 }
4992
4993 if (L->isLoopLatch(BrBB)) {
4994 ContinueBB = BrBB;
4995 } else {
4996 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4997 // block.
4998 BasicBlock *Header = L->getHeader();
4999 BasicBlock *Latch = L->getLoopLatch();
5000 for (BasicBlock *BB : L->blocks()) {
5001 if (BB == Header) {
5002 continue;
5003 }
5004
5005 // Check whether block dominates block with back-edge.
5006 if (DT.dominates(BB, Latch)) {
5007 ContinueBB = BB;
5008 }
5009 }
5010
5011 if (!ContinueBB) {
5012 llvm_unreachable("Wrong continue block from loop");
5013 }
5014 }
5015
5016 //
5017 // Generate OpLoopMerge.
5018 //
5019 // Ops[0] = Merge Block ID
5020 // Ops[1] = Continue Target ID
5021 // Ops[2] = Selection Control
5022 SPIRVOperandList Ops;
5023
5024 // StructurizeCFG pass already manipulated CFG. Just use false block of
5025 // branch instruction as merge block.
5026 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04005027 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04005028 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
5029 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005030
David Neto87846742018-04-11 17:36:22 -04005031 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005032 SPIRVInstList.insert(InsertPoint, MergeInst);
5033
5034 } else if (Br->isConditional()) {
5035 bool HasBackEdge = false;
5036
5037 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
5038 if (LI.isLoopHeader(Br->getSuccessor(i))) {
5039 HasBackEdge = true;
5040 }
5041 }
5042 if (!HasBackEdge) {
5043 //
5044 // Generate OpSelectionMerge.
5045 //
5046 // Ops[0] = Merge Block ID
5047 // Ops[1] = Selection Control
5048 SPIRVOperandList Ops;
5049
5050 // StructurizeCFG pass already manipulated CFG. Just use false block
5051 // of branch instruction as merge block.
5052 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005053 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005054
David Neto87846742018-04-11 17:36:22 -04005055 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005056 SPIRVInstList.insert(InsertPoint, MergeInst);
5057 }
5058 }
5059
5060 if (Br->isConditional()) {
5061 //
5062 // Generate OpBranchConditional.
5063 //
5064 // Ops[0] = Condition ID
5065 // Ops[1] = True Label ID
5066 // Ops[2] = False Label ID
5067 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5068 SPIRVOperandList Ops;
5069
5070 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005071 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005072 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005073
5074 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005075
David Neto87846742018-04-11 17:36:22 -04005076 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005077 SPIRVInstList.insert(InsertPoint, BrInst);
5078 } else {
5079 //
5080 // Generate OpBranch.
5081 //
5082 // Ops[0] = Target Label ID
5083 SPIRVOperandList Ops;
5084
5085 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005086 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005087
David Neto87846742018-04-11 17:36:22 -04005088 SPIRVInstList.insert(InsertPoint,
5089 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005090 }
5091 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005092 if (PHI->getType()->isPointerTy()) {
5093 // OpPhi on pointers requires variable pointers.
5094 setVariablePointersCapabilities(
5095 PHI->getType()->getPointerAddressSpace());
5096 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5097 setVariablePointers(true);
5098 }
5099 }
5100
David Neto22f144c2017-06-12 14:26:21 -04005101 //
5102 // Generate OpPhi.
5103 //
5104 // Ops[0] = Result Type ID
5105 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5106 SPIRVOperandList Ops;
5107
David Neto257c3892018-04-11 13:19:45 -04005108 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005109
David Neto22f144c2017-06-12 14:26:21 -04005110 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5111 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005112 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005113 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005114 }
5115
5116 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005117 InsertPoint,
5118 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005119 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5120 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005121 auto callee_name = Callee->getName();
5122 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005123
5124 if (EInst) {
5125 uint32_t &ExtInstImportID = getOpExtInstImportID();
5126
5127 //
5128 // Generate OpExtInst.
5129 //
5130
5131 // Ops[0] = Result Type ID
5132 // Ops[1] = Set ID (OpExtInstImport ID)
5133 // Ops[2] = Instruction Number (Literal Number)
5134 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5135 SPIRVOperandList Ops;
5136
David Neto862b7d82018-06-14 18:48:37 -04005137 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5138 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005139
David Neto22f144c2017-06-12 14:26:21 -04005140 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5141 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005142 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005143 }
5144
David Neto87846742018-04-11 17:36:22 -04005145 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5146 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005147 SPIRVInstList.insert(InsertPoint, ExtInst);
5148
David Neto3fbb4072017-10-16 11:28:14 -04005149 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5150 if (IndirectExtInst != kGlslExtInstBad) {
5151 // Generate one more instruction that uses the result of the extended
5152 // instruction. Its result id is one more than the id of the
5153 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005154 LLVMContext &Context =
5155 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005156
David Neto3fbb4072017-10-16 11:28:14 -04005157 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5158 &VMap, &SPIRVInstList, &InsertPoint](
5159 spv::Op opcode, Constant *constant) {
5160 //
5161 // Generate instruction like:
5162 // result = opcode constant <extinst-result>
5163 //
5164 // Ops[0] = Result Type ID
5165 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5166 // Ops[2] = Operand 1 ;; the result of the extended instruction
5167 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005168
David Neto3fbb4072017-10-16 11:28:14 -04005169 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005170 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005171
5172 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5173 constant = ConstantVector::getSplat(
5174 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5175 }
David Neto257c3892018-04-11 13:19:45 -04005176 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005177
5178 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005179 InsertPoint, new SPIRVInstruction(
5180 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005181 };
5182
5183 switch (IndirectExtInst) {
5184 case glsl::ExtInstFindUMsb: // Implementing clz
5185 generate_extra_inst(
5186 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5187 break;
5188 case glsl::ExtInstAcos: // Implementing acospi
5189 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005190 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005191 case glsl::ExtInstAtan2: // Implementing atan2pi
5192 generate_extra_inst(
5193 spv::OpFMul,
5194 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5195 break;
5196
5197 default:
5198 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005199 }
David Neto22f144c2017-06-12 14:26:21 -04005200 }
David Neto3fbb4072017-10-16 11:28:14 -04005201
David Neto862b7d82018-06-14 18:48:37 -04005202 } else if (callee_name.equals("_Z8popcounti") ||
5203 callee_name.equals("_Z8popcountj") ||
5204 callee_name.equals("_Z8popcountDv2_i") ||
5205 callee_name.equals("_Z8popcountDv3_i") ||
5206 callee_name.equals("_Z8popcountDv4_i") ||
5207 callee_name.equals("_Z8popcountDv2_j") ||
5208 callee_name.equals("_Z8popcountDv3_j") ||
5209 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005210 //
5211 // Generate OpBitCount
5212 //
5213 // Ops[0] = Result Type ID
5214 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005215 SPIRVOperandList Ops;
5216 Ops << MkId(lookupType(Call->getType()))
5217 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005218
5219 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005220 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005221 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005222
David Neto862b7d82018-06-14 18:48:37 -04005223 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005224
5225 // Generate an OpCompositeConstruct
5226 SPIRVOperandList Ops;
5227
5228 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005229 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005230
5231 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005232 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005233 }
5234
5235 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005236 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5237 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005238
Alan Baker202c8c72018-08-13 13:47:44 -04005239 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5240
5241 // We have already mapped the call's result value to an ID.
5242 // Don't generate any code now.
5243
5244 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005245
5246 // We have already mapped the call's result value to an ID.
5247 // Don't generate any code now.
5248
David Neto22f144c2017-06-12 14:26:21 -04005249 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005250 if (Call->getType()->isPointerTy()) {
5251 // Functions returning pointers require variable pointers.
5252 setVariablePointersCapabilities(
5253 Call->getType()->getPointerAddressSpace());
5254 }
5255
David Neto22f144c2017-06-12 14:26:21 -04005256 //
5257 // Generate OpFunctionCall.
5258 //
5259
5260 // Ops[0] = Result Type ID
5261 // Ops[1] = Callee Function ID
5262 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5263 SPIRVOperandList Ops;
5264
David Neto862b7d82018-06-14 18:48:37 -04005265 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005266
5267 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005268 if (CalleeID == 0) {
5269 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005270 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005271 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5272 // causes an infinite loop. Instead, go ahead and generate
5273 // the bad function call. A validator will catch the 0-Id.
5274 // llvm_unreachable("Can't translate function call");
5275 }
David Neto22f144c2017-06-12 14:26:21 -04005276
David Neto257c3892018-04-11 13:19:45 -04005277 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005278
David Neto22f144c2017-06-12 14:26:21 -04005279 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5280 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005281 auto *operand = Call->getOperand(i);
5282 if (operand->getType()->isPointerTy()) {
5283 auto sc =
5284 GetStorageClass(operand->getType()->getPointerAddressSpace());
5285 if (sc == spv::StorageClassStorageBuffer) {
5286 // Passing SSBO by reference requires variable pointers storage
5287 // buffer.
5288 setVariablePointersStorageBuffer(true);
5289 } else if (sc == spv::StorageClassWorkgroup) {
5290 // Workgroup references require variable pointers if they are not
5291 // memory object declarations.
5292 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5293 // Workgroup accessor represents a variable reference.
5294 if (!operand_call->getCalledFunction()->getName().startswith(
5295 clspv::WorkgroupAccessorFunction()))
5296 setVariablePointers(true);
5297 } else {
5298 // Arguments are function parameters.
5299 if (!isa<Argument>(operand))
5300 setVariablePointers(true);
5301 }
5302 }
5303 }
5304 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005305 }
5306
David Neto87846742018-04-11 17:36:22 -04005307 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5308 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005309 SPIRVInstList.insert(InsertPoint, CallInst);
5310 }
5311 }
5312 }
5313}
5314
David Neto1a1a0582017-07-07 12:01:44 -04005315void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005316 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005317 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005318 }
David Neto1a1a0582017-07-07 12:01:44 -04005319
5320 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005321
5322 // Find an iterator pointing just past the last decoration.
5323 bool seen_decorations = false;
5324 auto DecoInsertPoint =
5325 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5326 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5327 const bool is_decoration =
5328 Inst->getOpcode() == spv::OpDecorate ||
5329 Inst->getOpcode() == spv::OpMemberDecorate;
5330 if (is_decoration) {
5331 seen_decorations = true;
5332 return false;
5333 } else {
5334 return seen_decorations;
5335 }
5336 });
5337
David Netoc6f3ab22018-04-06 18:02:31 -04005338 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5339 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005340 for (auto *type : getTypesNeedingArrayStride()) {
5341 Type *elemTy = nullptr;
5342 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5343 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005344 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005345 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005346 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005347 elemTy = seqTy->getSequentialElementType();
5348 } else {
5349 errs() << "Unhandled strided type " << *type << "\n";
5350 llvm_unreachable("Unhandled strided type");
5351 }
David Neto1a1a0582017-07-07 12:01:44 -04005352
5353 // Ops[0] = Target ID
5354 // Ops[1] = Decoration (ArrayStride)
5355 // Ops[2] = Stride number (Literal Number)
5356 SPIRVOperandList Ops;
5357
David Neto85082642018-03-24 06:55:20 -07005358 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005359 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005360
5361 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5362 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005363
David Neto87846742018-04-11 17:36:22 -04005364 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005365 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5366 }
David Netoc6f3ab22018-04-06 18:02:31 -04005367
5368 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005369 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5370 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005371 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005372 SPIRVOperandList Ops;
5373 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5374 << MkNum(arg_info.spec_id);
5375 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005376 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005377 }
David Neto1a1a0582017-07-07 12:01:44 -04005378}
5379
David Neto22f144c2017-06-12 14:26:21 -04005380glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5381 return StringSwitch<glsl::ExtInst>(Name)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005382 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5383 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5384 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5385 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005386 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5387 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5388 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5389 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005390 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5391 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5392 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5393 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005394 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5395 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5396 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5397 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5398 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5399 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5400 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5401 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5402 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5403 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5404 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5405 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005406 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5407 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5408 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5409 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5410 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5411 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5412 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5413 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005414 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5415 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5416 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5417 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5418 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5419 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5420 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5421 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005422 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5423 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5424 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5425 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5426 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5427 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5428 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5429 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005430 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5431 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5432 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5433 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5434 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005435 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5436 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5437 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5438 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5439 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5440 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5441 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5442 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005443 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5444 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5445 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5446 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5447 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5448 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5449 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5450 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005451 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5452 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5453 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5454 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5455 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5456 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5457 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5458 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005459 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5460 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5461 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5462 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5463 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5464 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5465 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5466 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5467 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5468 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5469 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5470 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5471 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5472 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5473 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5474 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5475 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5476 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5477 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5478 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5479 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5480 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5481 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5482 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5483 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5484 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5485 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5486 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5487 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5488 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5489 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5490 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5491 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5492 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5493 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5494 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5495 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5496 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5497 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5498 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5499 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005500 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005501 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5502 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5503 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5504 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5505 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5506 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5507 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5508 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5509 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5510 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5511 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5512 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5513 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5514 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5515 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5516 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5517 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005518 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005519 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005520 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005521 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005522 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005523 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5524 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005525 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005526 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5527 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5528 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005529 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5530 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5531 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5532 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005533 .Default(kGlslExtInstBad);
5534}
5535
5536glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5537 // Check indirect cases.
5538 return StringSwitch<glsl::ExtInst>(Name)
5539 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5540 // Use exact match on float arg because these need a multiply
5541 // of a constant of the right floating point type.
5542 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5543 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5544 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5545 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5546 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5547 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5548 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5549 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005550 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5551 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5552 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5553 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005554 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5555 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5556 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5557 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5558 .Default(kGlslExtInstBad);
5559}
5560
alan-bakerb6b09dc2018-11-08 16:59:28 -05005561glsl::ExtInst
5562SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005563 auto direct = getExtInstEnum(Name);
5564 if (direct != kGlslExtInstBad)
5565 return direct;
5566 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005567}
5568
5569void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5570 out << "%" << Inst->getResultID();
5571}
5572
5573void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5574 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5575 out << "\t" << spv::getOpName(Opcode);
5576}
5577
5578void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5579 SPIRVOperandType OpTy = Op->getType();
5580 switch (OpTy) {
5581 default: {
5582 llvm_unreachable("Unsupported SPIRV Operand Type???");
5583 break;
5584 }
5585 case SPIRVOperandType::NUMBERID: {
5586 out << "%" << Op->getNumID();
5587 break;
5588 }
5589 case SPIRVOperandType::LITERAL_STRING: {
5590 out << "\"" << Op->getLiteralStr() << "\"";
5591 break;
5592 }
5593 case SPIRVOperandType::LITERAL_INTEGER: {
5594 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005595 auto Words = Op->getLiteralNum();
5596 auto NumWords = Words.size();
5597
5598 if (NumWords == 1) {
5599 out << Words[0];
5600 } else if (NumWords == 2) {
5601 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5602 out << Val;
5603 } else {
5604 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005605 }
5606 break;
5607 }
5608 case SPIRVOperandType::LITERAL_FLOAT: {
5609 // TODO: Handle LiteralNum carefully.
5610 for (auto Word : Op->getLiteralNum()) {
5611 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5612 SmallString<8> Str;
5613 APF.toString(Str, 6, 2);
5614 out << Str;
5615 }
5616 break;
5617 }
5618 }
5619}
5620
5621void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5622 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5623 out << spv::getCapabilityName(Cap);
5624}
5625
5626void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5627 auto LiteralNum = Op->getLiteralNum();
5628 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5629 out << glsl::getExtInstName(Ext);
5630}
5631
5632void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5633 spv::AddressingModel AddrModel =
5634 static_cast<spv::AddressingModel>(Op->getNumID());
5635 out << spv::getAddressingModelName(AddrModel);
5636}
5637
5638void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5639 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5640 out << spv::getMemoryModelName(MemModel);
5641}
5642
5643void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5644 spv::ExecutionModel ExecModel =
5645 static_cast<spv::ExecutionModel>(Op->getNumID());
5646 out << spv::getExecutionModelName(ExecModel);
5647}
5648
5649void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5650 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5651 out << spv::getExecutionModeName(ExecMode);
5652}
5653
5654void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005655 spv::SourceLanguage SourceLang =
5656 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005657 out << spv::getSourceLanguageName(SourceLang);
5658}
5659
5660void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5661 spv::FunctionControlMask FuncCtrl =
5662 static_cast<spv::FunctionControlMask>(Op->getNumID());
5663 out << spv::getFunctionControlName(FuncCtrl);
5664}
5665
5666void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5667 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5668 out << getStorageClassName(StClass);
5669}
5670
5671void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5672 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5673 out << getDecorationName(Deco);
5674}
5675
5676void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5677 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5678 out << getBuiltInName(BIn);
5679}
5680
5681void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5682 spv::SelectionControlMask BIn =
5683 static_cast<spv::SelectionControlMask>(Op->getNumID());
5684 out << getSelectionControlName(BIn);
5685}
5686
5687void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5688 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5689 out << getLoopControlName(BIn);
5690}
5691
5692void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5693 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5694 out << getDimName(DIM);
5695}
5696
5697void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5698 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5699 out << getImageFormatName(Format);
5700}
5701
5702void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5703 out << spv::getMemoryAccessName(
5704 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5705}
5706
5707void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5708 auto LiteralNum = Op->getLiteralNum();
5709 spv::ImageOperandsMask Type =
5710 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5711 out << getImageOperandsName(Type);
5712}
5713
5714void SPIRVProducerPass::WriteSPIRVAssembly() {
5715 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5716
5717 for (auto Inst : SPIRVInstList) {
5718 SPIRVOperandList Ops = Inst->getOperands();
5719 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5720
5721 switch (Opcode) {
5722 default: {
5723 llvm_unreachable("Unsupported SPIRV instruction");
5724 break;
5725 }
5726 case spv::OpCapability: {
5727 // Ops[0] = Capability
5728 PrintOpcode(Inst);
5729 out << " ";
5730 PrintCapability(Ops[0]);
5731 out << "\n";
5732 break;
5733 }
5734 case spv::OpMemoryModel: {
5735 // Ops[0] = Addressing Model
5736 // Ops[1] = Memory Model
5737 PrintOpcode(Inst);
5738 out << " ";
5739 PrintAddrModel(Ops[0]);
5740 out << " ";
5741 PrintMemModel(Ops[1]);
5742 out << "\n";
5743 break;
5744 }
5745 case spv::OpEntryPoint: {
5746 // Ops[0] = Execution Model
5747 // Ops[1] = EntryPoint ID
5748 // Ops[2] = Name (Literal String)
5749 // Ops[3] ... Ops[n] = Interface ID
5750 PrintOpcode(Inst);
5751 out << " ";
5752 PrintExecModel(Ops[0]);
5753 for (uint32_t i = 1; i < Ops.size(); i++) {
5754 out << " ";
5755 PrintOperand(Ops[i]);
5756 }
5757 out << "\n";
5758 break;
5759 }
5760 case spv::OpExecutionMode: {
5761 // Ops[0] = Entry Point ID
5762 // Ops[1] = Execution Mode
5763 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5764 PrintOpcode(Inst);
5765 out << " ";
5766 PrintOperand(Ops[0]);
5767 out << " ";
5768 PrintExecMode(Ops[1]);
5769 for (uint32_t i = 2; i < Ops.size(); i++) {
5770 out << " ";
5771 PrintOperand(Ops[i]);
5772 }
5773 out << "\n";
5774 break;
5775 }
5776 case spv::OpSource: {
5777 // Ops[0] = SourceLanguage ID
5778 // Ops[1] = Version (LiteralNum)
5779 PrintOpcode(Inst);
5780 out << " ";
5781 PrintSourceLanguage(Ops[0]);
5782 out << " ";
5783 PrintOperand(Ops[1]);
5784 out << "\n";
5785 break;
5786 }
5787 case spv::OpDecorate: {
5788 // Ops[0] = Target ID
5789 // Ops[1] = Decoration (Block or BufferBlock)
5790 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5791 PrintOpcode(Inst);
5792 out << " ";
5793 PrintOperand(Ops[0]);
5794 out << " ";
5795 PrintDecoration(Ops[1]);
5796 // Handle BuiltIn OpDecorate specially.
5797 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5798 out << " ";
5799 PrintBuiltIn(Ops[2]);
5800 } else {
5801 for (uint32_t i = 2; i < Ops.size(); i++) {
5802 out << " ";
5803 PrintOperand(Ops[i]);
5804 }
5805 }
5806 out << "\n";
5807 break;
5808 }
5809 case spv::OpMemberDecorate: {
5810 // Ops[0] = Structure Type ID
5811 // Ops[1] = Member Index(Literal Number)
5812 // Ops[2] = Decoration
5813 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5814 PrintOpcode(Inst);
5815 out << " ";
5816 PrintOperand(Ops[0]);
5817 out << " ";
5818 PrintOperand(Ops[1]);
5819 out << " ";
5820 PrintDecoration(Ops[2]);
5821 for (uint32_t i = 3; i < Ops.size(); i++) {
5822 out << " ";
5823 PrintOperand(Ops[i]);
5824 }
5825 out << "\n";
5826 break;
5827 }
5828 case spv::OpTypePointer: {
5829 // Ops[0] = Storage Class
5830 // Ops[1] = Element Type ID
5831 PrintResID(Inst);
5832 out << " = ";
5833 PrintOpcode(Inst);
5834 out << " ";
5835 PrintStorageClass(Ops[0]);
5836 out << " ";
5837 PrintOperand(Ops[1]);
5838 out << "\n";
5839 break;
5840 }
5841 case spv::OpTypeImage: {
5842 // Ops[0] = Sampled Type ID
5843 // Ops[1] = Dim ID
5844 // Ops[2] = Depth (Literal Number)
5845 // Ops[3] = Arrayed (Literal Number)
5846 // Ops[4] = MS (Literal Number)
5847 // Ops[5] = Sampled (Literal Number)
5848 // Ops[6] = Image Format ID
5849 PrintResID(Inst);
5850 out << " = ";
5851 PrintOpcode(Inst);
5852 out << " ";
5853 PrintOperand(Ops[0]);
5854 out << " ";
5855 PrintDimensionality(Ops[1]);
5856 out << " ";
5857 PrintOperand(Ops[2]);
5858 out << " ";
5859 PrintOperand(Ops[3]);
5860 out << " ";
5861 PrintOperand(Ops[4]);
5862 out << " ";
5863 PrintOperand(Ops[5]);
5864 out << " ";
5865 PrintImageFormat(Ops[6]);
5866 out << "\n";
5867 break;
5868 }
5869 case spv::OpFunction: {
5870 // Ops[0] : Result Type ID
5871 // Ops[1] : Function Control
5872 // Ops[2] : Function Type ID
5873 PrintResID(Inst);
5874 out << " = ";
5875 PrintOpcode(Inst);
5876 out << " ";
5877 PrintOperand(Ops[0]);
5878 out << " ";
5879 PrintFuncCtrl(Ops[1]);
5880 out << " ";
5881 PrintOperand(Ops[2]);
5882 out << "\n";
5883 break;
5884 }
5885 case spv::OpSelectionMerge: {
5886 // Ops[0] = Merge Block ID
5887 // Ops[1] = Selection Control
5888 PrintOpcode(Inst);
5889 out << " ";
5890 PrintOperand(Ops[0]);
5891 out << " ";
5892 PrintSelectionControl(Ops[1]);
5893 out << "\n";
5894 break;
5895 }
5896 case spv::OpLoopMerge: {
5897 // Ops[0] = Merge Block ID
5898 // Ops[1] = Continue Target ID
5899 // Ops[2] = Selection Control
5900 PrintOpcode(Inst);
5901 out << " ";
5902 PrintOperand(Ops[0]);
5903 out << " ";
5904 PrintOperand(Ops[1]);
5905 out << " ";
5906 PrintLoopControl(Ops[2]);
5907 out << "\n";
5908 break;
5909 }
5910 case spv::OpImageSampleExplicitLod: {
5911 // Ops[0] = Result Type ID
5912 // Ops[1] = Sampled Image ID
5913 // Ops[2] = Coordinate ID
5914 // Ops[3] = Image Operands Type ID
5915 // Ops[4] ... Ops[n] = Operands ID
5916 PrintResID(Inst);
5917 out << " = ";
5918 PrintOpcode(Inst);
5919 for (uint32_t i = 0; i < 3; i++) {
5920 out << " ";
5921 PrintOperand(Ops[i]);
5922 }
5923 out << " ";
5924 PrintImageOperandsType(Ops[3]);
5925 for (uint32_t i = 4; i < Ops.size(); i++) {
5926 out << " ";
5927 PrintOperand(Ops[i]);
5928 }
5929 out << "\n";
5930 break;
5931 }
5932 case spv::OpVariable: {
5933 // Ops[0] : Result Type ID
5934 // Ops[1] : Storage Class
5935 // Ops[2] ... Ops[n] = Initializer IDs
5936 PrintResID(Inst);
5937 out << " = ";
5938 PrintOpcode(Inst);
5939 out << " ";
5940 PrintOperand(Ops[0]);
5941 out << " ";
5942 PrintStorageClass(Ops[1]);
5943 for (uint32_t i = 2; i < Ops.size(); i++) {
5944 out << " ";
5945 PrintOperand(Ops[i]);
5946 }
5947 out << "\n";
5948 break;
5949 }
5950 case spv::OpExtInst: {
5951 // Ops[0] = Result Type ID
5952 // Ops[1] = Set ID (OpExtInstImport ID)
5953 // Ops[2] = Instruction Number (Literal Number)
5954 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5955 PrintResID(Inst);
5956 out << " = ";
5957 PrintOpcode(Inst);
5958 out << " ";
5959 PrintOperand(Ops[0]);
5960 out << " ";
5961 PrintOperand(Ops[1]);
5962 out << " ";
5963 PrintExtInst(Ops[2]);
5964 for (uint32_t i = 3; i < Ops.size(); i++) {
5965 out << " ";
5966 PrintOperand(Ops[i]);
5967 }
5968 out << "\n";
5969 break;
5970 }
5971 case spv::OpCopyMemory: {
5972 // Ops[0] = Addressing Model
5973 // Ops[1] = Memory Model
5974 PrintOpcode(Inst);
5975 out << " ";
5976 PrintOperand(Ops[0]);
5977 out << " ";
5978 PrintOperand(Ops[1]);
5979 out << " ";
5980 PrintMemoryAccess(Ops[2]);
5981 out << " ";
5982 PrintOperand(Ops[3]);
5983 out << "\n";
5984 break;
5985 }
5986 case spv::OpExtension:
5987 case spv::OpControlBarrier:
5988 case spv::OpMemoryBarrier:
5989 case spv::OpBranch:
5990 case spv::OpBranchConditional:
5991 case spv::OpStore:
5992 case spv::OpImageWrite:
5993 case spv::OpReturnValue:
5994 case spv::OpReturn:
5995 case spv::OpFunctionEnd: {
5996 PrintOpcode(Inst);
5997 for (uint32_t i = 0; i < Ops.size(); i++) {
5998 out << " ";
5999 PrintOperand(Ops[i]);
6000 }
6001 out << "\n";
6002 break;
6003 }
6004 case spv::OpExtInstImport:
6005 case spv::OpTypeRuntimeArray:
6006 case spv::OpTypeStruct:
6007 case spv::OpTypeSampler:
6008 case spv::OpTypeSampledImage:
6009 case spv::OpTypeInt:
6010 case spv::OpTypeFloat:
6011 case spv::OpTypeArray:
6012 case spv::OpTypeVector:
6013 case spv::OpTypeBool:
6014 case spv::OpTypeVoid:
6015 case spv::OpTypeFunction:
6016 case spv::OpFunctionParameter:
6017 case spv::OpLabel:
6018 case spv::OpPhi:
6019 case spv::OpLoad:
6020 case spv::OpSelect:
6021 case spv::OpAccessChain:
6022 case spv::OpPtrAccessChain:
6023 case spv::OpInBoundsAccessChain:
6024 case spv::OpUConvert:
6025 case spv::OpSConvert:
6026 case spv::OpConvertFToU:
6027 case spv::OpConvertFToS:
6028 case spv::OpConvertUToF:
6029 case spv::OpConvertSToF:
6030 case spv::OpFConvert:
6031 case spv::OpConvertPtrToU:
6032 case spv::OpConvertUToPtr:
6033 case spv::OpBitcast:
6034 case spv::OpIAdd:
6035 case spv::OpFAdd:
6036 case spv::OpISub:
6037 case spv::OpFSub:
6038 case spv::OpIMul:
6039 case spv::OpFMul:
6040 case spv::OpUDiv:
6041 case spv::OpSDiv:
6042 case spv::OpFDiv:
6043 case spv::OpUMod:
6044 case spv::OpSRem:
6045 case spv::OpFRem:
6046 case spv::OpBitwiseOr:
6047 case spv::OpBitwiseXor:
6048 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006049 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006050 case spv::OpShiftLeftLogical:
6051 case spv::OpShiftRightLogical:
6052 case spv::OpShiftRightArithmetic:
6053 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006054 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006055 case spv::OpCompositeExtract:
6056 case spv::OpVectorExtractDynamic:
6057 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006058 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006059 case spv::OpVectorInsertDynamic:
6060 case spv::OpVectorShuffle:
6061 case spv::OpIEqual:
6062 case spv::OpINotEqual:
6063 case spv::OpUGreaterThan:
6064 case spv::OpUGreaterThanEqual:
6065 case spv::OpULessThan:
6066 case spv::OpULessThanEqual:
6067 case spv::OpSGreaterThan:
6068 case spv::OpSGreaterThanEqual:
6069 case spv::OpSLessThan:
6070 case spv::OpSLessThanEqual:
6071 case spv::OpFOrdEqual:
6072 case spv::OpFOrdGreaterThan:
6073 case spv::OpFOrdGreaterThanEqual:
6074 case spv::OpFOrdLessThan:
6075 case spv::OpFOrdLessThanEqual:
6076 case spv::OpFOrdNotEqual:
6077 case spv::OpFUnordEqual:
6078 case spv::OpFUnordGreaterThan:
6079 case spv::OpFUnordGreaterThanEqual:
6080 case spv::OpFUnordLessThan:
6081 case spv::OpFUnordLessThanEqual:
6082 case spv::OpFUnordNotEqual:
6083 case spv::OpSampledImage:
6084 case spv::OpFunctionCall:
6085 case spv::OpConstantTrue:
6086 case spv::OpConstantFalse:
6087 case spv::OpConstant:
6088 case spv::OpSpecConstant:
6089 case spv::OpConstantComposite:
6090 case spv::OpSpecConstantComposite:
6091 case spv::OpConstantNull:
6092 case spv::OpLogicalOr:
6093 case spv::OpLogicalAnd:
6094 case spv::OpLogicalNot:
6095 case spv::OpLogicalNotEqual:
6096 case spv::OpUndef:
6097 case spv::OpIsInf:
6098 case spv::OpIsNan:
6099 case spv::OpAny:
6100 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04006101 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006102 case spv::OpAtomicIAdd:
6103 case spv::OpAtomicISub:
6104 case spv::OpAtomicExchange:
6105 case spv::OpAtomicIIncrement:
6106 case spv::OpAtomicIDecrement:
6107 case spv::OpAtomicCompareExchange:
6108 case spv::OpAtomicUMin:
6109 case spv::OpAtomicSMin:
6110 case spv::OpAtomicUMax:
6111 case spv::OpAtomicSMax:
6112 case spv::OpAtomicAnd:
6113 case spv::OpAtomicOr:
6114 case spv::OpAtomicXor:
6115 case spv::OpDot: {
6116 PrintResID(Inst);
6117 out << " = ";
6118 PrintOpcode(Inst);
6119 for (uint32_t i = 0; i < Ops.size(); i++) {
6120 out << " ";
6121 PrintOperand(Ops[i]);
6122 }
6123 out << "\n";
6124 break;
6125 }
6126 }
6127 }
6128}
6129
6130void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006131 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006132}
6133
6134void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6135 WriteOneWord(Inst->getResultID());
6136}
6137
6138void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6139 // High 16 bit : Word Count
6140 // Low 16 bit : Opcode
6141 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006142 const uint32_t count = Inst->getWordCount();
6143 if (count > 65535) {
6144 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6145 llvm_unreachable("Word count too high");
6146 }
David Neto22f144c2017-06-12 14:26:21 -04006147 Word |= Inst->getWordCount() << 16;
6148 WriteOneWord(Word);
6149}
6150
6151void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6152 SPIRVOperandType OpTy = Op->getType();
6153 switch (OpTy) {
6154 default: {
6155 llvm_unreachable("Unsupported SPIRV Operand Type???");
6156 break;
6157 }
6158 case SPIRVOperandType::NUMBERID: {
6159 WriteOneWord(Op->getNumID());
6160 break;
6161 }
6162 case SPIRVOperandType::LITERAL_STRING: {
6163 std::string Str = Op->getLiteralStr();
6164 const char *Data = Str.c_str();
6165 size_t WordSize = Str.size() / 4;
6166 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6167 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6168 }
6169
6170 uint32_t Remainder = Str.size() % 4;
6171 uint32_t LastWord = 0;
6172 if (Remainder) {
6173 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6174 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6175 }
6176 }
6177
6178 WriteOneWord(LastWord);
6179 break;
6180 }
6181 case SPIRVOperandType::LITERAL_INTEGER:
6182 case SPIRVOperandType::LITERAL_FLOAT: {
6183 auto LiteralNum = Op->getLiteralNum();
6184 // TODO: Handle LiteranNum carefully.
6185 for (auto Word : LiteralNum) {
6186 WriteOneWord(Word);
6187 }
6188 break;
6189 }
6190 }
6191}
6192
6193void SPIRVProducerPass::WriteSPIRVBinary() {
6194 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6195
6196 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006197 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006198 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6199
6200 switch (Opcode) {
6201 default: {
David Neto5c22a252018-03-15 16:07:41 -04006202 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006203 llvm_unreachable("Unsupported SPIRV instruction");
6204 break;
6205 }
6206 case spv::OpCapability:
6207 case spv::OpExtension:
6208 case spv::OpMemoryModel:
6209 case spv::OpEntryPoint:
6210 case spv::OpExecutionMode:
6211 case spv::OpSource:
6212 case spv::OpDecorate:
6213 case spv::OpMemberDecorate:
6214 case spv::OpBranch:
6215 case spv::OpBranchConditional:
6216 case spv::OpSelectionMerge:
6217 case spv::OpLoopMerge:
6218 case spv::OpStore:
6219 case spv::OpImageWrite:
6220 case spv::OpReturnValue:
6221 case spv::OpControlBarrier:
6222 case spv::OpMemoryBarrier:
6223 case spv::OpReturn:
6224 case spv::OpFunctionEnd:
6225 case spv::OpCopyMemory: {
6226 WriteWordCountAndOpcode(Inst);
6227 for (uint32_t i = 0; i < Ops.size(); i++) {
6228 WriteOperand(Ops[i]);
6229 }
6230 break;
6231 }
6232 case spv::OpTypeBool:
6233 case spv::OpTypeVoid:
6234 case spv::OpTypeSampler:
6235 case spv::OpLabel:
6236 case spv::OpExtInstImport:
6237 case spv::OpTypePointer:
6238 case spv::OpTypeRuntimeArray:
6239 case spv::OpTypeStruct:
6240 case spv::OpTypeImage:
6241 case spv::OpTypeSampledImage:
6242 case spv::OpTypeInt:
6243 case spv::OpTypeFloat:
6244 case spv::OpTypeArray:
6245 case spv::OpTypeVector:
6246 case spv::OpTypeFunction: {
6247 WriteWordCountAndOpcode(Inst);
6248 WriteResultID(Inst);
6249 for (uint32_t i = 0; i < Ops.size(); i++) {
6250 WriteOperand(Ops[i]);
6251 }
6252 break;
6253 }
6254 case spv::OpFunction:
6255 case spv::OpFunctionParameter:
6256 case spv::OpAccessChain:
6257 case spv::OpPtrAccessChain:
6258 case spv::OpInBoundsAccessChain:
6259 case spv::OpUConvert:
6260 case spv::OpSConvert:
6261 case spv::OpConvertFToU:
6262 case spv::OpConvertFToS:
6263 case spv::OpConvertUToF:
6264 case spv::OpConvertSToF:
6265 case spv::OpFConvert:
6266 case spv::OpConvertPtrToU:
6267 case spv::OpConvertUToPtr:
6268 case spv::OpBitcast:
6269 case spv::OpIAdd:
6270 case spv::OpFAdd:
6271 case spv::OpISub:
6272 case spv::OpFSub:
6273 case spv::OpIMul:
6274 case spv::OpFMul:
6275 case spv::OpUDiv:
6276 case spv::OpSDiv:
6277 case spv::OpFDiv:
6278 case spv::OpUMod:
6279 case spv::OpSRem:
6280 case spv::OpFRem:
6281 case spv::OpBitwiseOr:
6282 case spv::OpBitwiseXor:
6283 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006284 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006285 case spv::OpShiftLeftLogical:
6286 case spv::OpShiftRightLogical:
6287 case spv::OpShiftRightArithmetic:
6288 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006289 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006290 case spv::OpCompositeExtract:
6291 case spv::OpVectorExtractDynamic:
6292 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006293 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006294 case spv::OpVectorInsertDynamic:
6295 case spv::OpVectorShuffle:
6296 case spv::OpIEqual:
6297 case spv::OpINotEqual:
6298 case spv::OpUGreaterThan:
6299 case spv::OpUGreaterThanEqual:
6300 case spv::OpULessThan:
6301 case spv::OpULessThanEqual:
6302 case spv::OpSGreaterThan:
6303 case spv::OpSGreaterThanEqual:
6304 case spv::OpSLessThan:
6305 case spv::OpSLessThanEqual:
6306 case spv::OpFOrdEqual:
6307 case spv::OpFOrdGreaterThan:
6308 case spv::OpFOrdGreaterThanEqual:
6309 case spv::OpFOrdLessThan:
6310 case spv::OpFOrdLessThanEqual:
6311 case spv::OpFOrdNotEqual:
6312 case spv::OpFUnordEqual:
6313 case spv::OpFUnordGreaterThan:
6314 case spv::OpFUnordGreaterThanEqual:
6315 case spv::OpFUnordLessThan:
6316 case spv::OpFUnordLessThanEqual:
6317 case spv::OpFUnordNotEqual:
6318 case spv::OpExtInst:
6319 case spv::OpIsInf:
6320 case spv::OpIsNan:
6321 case spv::OpAny:
6322 case spv::OpAll:
6323 case spv::OpUndef:
6324 case spv::OpConstantNull:
6325 case spv::OpLogicalOr:
6326 case spv::OpLogicalAnd:
6327 case spv::OpLogicalNot:
6328 case spv::OpLogicalNotEqual:
6329 case spv::OpConstantComposite:
6330 case spv::OpSpecConstantComposite:
6331 case spv::OpConstantTrue:
6332 case spv::OpConstantFalse:
6333 case spv::OpConstant:
6334 case spv::OpSpecConstant:
6335 case spv::OpVariable:
6336 case spv::OpFunctionCall:
6337 case spv::OpSampledImage:
6338 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006339 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006340 case spv::OpSelect:
6341 case spv::OpPhi:
6342 case spv::OpLoad:
6343 case spv::OpAtomicIAdd:
6344 case spv::OpAtomicISub:
6345 case spv::OpAtomicExchange:
6346 case spv::OpAtomicIIncrement:
6347 case spv::OpAtomicIDecrement:
6348 case spv::OpAtomicCompareExchange:
6349 case spv::OpAtomicUMin:
6350 case spv::OpAtomicSMin:
6351 case spv::OpAtomicUMax:
6352 case spv::OpAtomicSMax:
6353 case spv::OpAtomicAnd:
6354 case spv::OpAtomicOr:
6355 case spv::OpAtomicXor:
6356 case spv::OpDot: {
6357 WriteWordCountAndOpcode(Inst);
6358 WriteOperand(Ops[0]);
6359 WriteResultID(Inst);
6360 for (uint32_t i = 1; i < Ops.size(); i++) {
6361 WriteOperand(Ops[i]);
6362 }
6363 break;
6364 }
6365 }
6366 }
6367}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006368
alan-bakerb6b09dc2018-11-08 16:59:28 -05006369bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006370 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006371 case Type::HalfTyID:
6372 case Type::FloatTyID:
6373 case Type::DoubleTyID:
6374 case Type::IntegerTyID:
6375 case Type::VectorTyID:
6376 return true;
6377 case Type::PointerTyID: {
6378 const PointerType *pointer_type = cast<PointerType>(type);
6379 if (pointer_type->getPointerAddressSpace() !=
6380 AddressSpace::UniformConstant) {
6381 auto pointee_type = pointer_type->getPointerElementType();
6382 if (pointee_type->isStructTy() &&
6383 cast<StructType>(pointee_type)->isOpaque()) {
6384 // Images and samplers are not nullable.
6385 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006386 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006387 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006388 return true;
6389 }
6390 case Type::ArrayTyID:
6391 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6392 case Type::StructTyID: {
6393 const StructType *struct_type = cast<StructType>(type);
6394 // Images and samplers are not nullable.
6395 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006396 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006397 for (const auto element : struct_type->elements()) {
6398 if (!IsTypeNullable(element))
6399 return false;
6400 }
6401 return true;
6402 }
6403 default:
6404 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006405 }
6406}
Alan Bakerfcda9482018-10-02 17:09:59 -04006407
6408void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6409 if (auto *offsets_md =
6410 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6411 // Metdata is stored as key-value pair operands. The first element of each
6412 // operand is the type and the second is a vector of offsets.
6413 for (const auto *operand : offsets_md->operands()) {
6414 const auto *pair = cast<MDTuple>(operand);
6415 auto *type =
6416 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6417 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6418 std::vector<uint32_t> offsets;
6419 for (const Metadata *offset_md : offset_vector->operands()) {
6420 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006421 offsets.push_back(static_cast<uint32_t>(
6422 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006423 }
6424 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6425 }
6426 }
6427
6428 if (auto *sizes_md =
6429 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6430 // Metadata is stored as key-value pair operands. The first element of each
6431 // operand is the type and the second is a triple of sizes: type size in
6432 // bits, store size and alloc size.
6433 for (const auto *operand : sizes_md->operands()) {
6434 const auto *pair = cast<MDTuple>(operand);
6435 auto *type =
6436 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6437 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6438 uint64_t type_size_in_bits =
6439 cast<ConstantInt>(
6440 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6441 ->getZExtValue();
6442 uint64_t type_store_size =
6443 cast<ConstantInt>(
6444 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6445 ->getZExtValue();
6446 uint64_t type_alloc_size =
6447 cast<ConstantInt>(
6448 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6449 ->getZExtValue();
6450 RemappedUBOTypeSizes.insert(std::make_pair(
6451 type, std::make_tuple(type_size_in_bits, type_store_size,
6452 type_alloc_size)));
6453 }
6454 }
6455}
6456
6457uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6458 const DataLayout &DL) {
6459 auto iter = RemappedUBOTypeSizes.find(type);
6460 if (iter != RemappedUBOTypeSizes.end()) {
6461 return std::get<0>(iter->second);
6462 }
6463
6464 return DL.getTypeSizeInBits(type);
6465}
6466
6467uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6468 auto iter = RemappedUBOTypeSizes.find(type);
6469 if (iter != RemappedUBOTypeSizes.end()) {
6470 return std::get<1>(iter->second);
6471 }
6472
6473 return DL.getTypeStoreSize(type);
6474}
6475
6476uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6477 auto iter = RemappedUBOTypeSizes.find(type);
6478 if (iter != RemappedUBOTypeSizes.end()) {
6479 return std::get<2>(iter->second);
6480 }
6481
6482 return DL.getTypeAllocSize(type);
6483}
alan-baker5b86ed72019-02-15 08:26:50 -05006484
6485void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6486 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6487 setVariablePointersStorageBuffer(true);
6488 } else {
6489 setVariablePointers(true);
6490 }
6491}
6492
6493Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6494 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6495 return GetBasePointer(gep->getPointerOperand());
6496 }
6497
6498 // Conservatively return |v|.
6499 return v;
6500}
6501
6502bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6503 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6504 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6505 if (lhs_call->getCalledFunction()->getName().startswith(
6506 clspv::ResourceAccessorFunction()) &&
6507 rhs_call->getCalledFunction()->getName().startswith(
6508 clspv::ResourceAccessorFunction())) {
6509 // For resource accessors, match descriptor set and binding.
6510 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6511 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6512 return true;
6513 } else if (lhs_call->getCalledFunction()->getName().startswith(
6514 clspv::WorkgroupAccessorFunction()) &&
6515 rhs_call->getCalledFunction()->getName().startswith(
6516 clspv::WorkgroupAccessorFunction())) {
6517 // For workgroup resources, match spec id.
6518 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6519 return true;
6520 }
6521 }
6522 }
6523
6524 return false;
6525}
6526
6527bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6528 assert(inst->getType()->isPointerTy());
6529 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6530 spv::StorageClassStorageBuffer);
6531 const bool hack_undef = clspv::Option::HackUndef();
6532 if (auto *select = dyn_cast<SelectInst>(inst)) {
6533 auto *true_base = GetBasePointer(select->getTrueValue());
6534 auto *false_base = GetBasePointer(select->getFalseValue());
6535
6536 if (true_base == false_base)
6537 return true;
6538
6539 // If either the true or false operand is a null, then we satisfy the same
6540 // object constraint.
6541 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6542 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6543 return true;
6544 }
6545
6546 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6547 if (false_cst->isNullValue() ||
6548 (hack_undef && isa<UndefValue>(false_base)))
6549 return true;
6550 }
6551
6552 if (sameResource(true_base, false_base))
6553 return true;
6554 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6555 Value *value = nullptr;
6556 bool ok = true;
6557 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6558 auto *base = GetBasePointer(phi->getIncomingValue(i));
6559 // Null values satisfy the constraint of selecting of selecting from the
6560 // same object.
6561 if (!value) {
6562 if (auto *cst = dyn_cast<Constant>(base)) {
6563 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6564 value = base;
6565 } else {
6566 value = base;
6567 }
6568 } else if (base != value) {
6569 if (auto *base_cst = dyn_cast<Constant>(base)) {
6570 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6571 continue;
6572 }
6573
6574 if (sameResource(value, base))
6575 continue;
6576
6577 // Values don't represent the same base.
6578 ok = false;
6579 }
6580 }
6581
6582 return ok;
6583 }
6584
6585 // Conservatively return false.
6586 return false;
6587}