blob: f1afcaef8e18e41a89f1a60b5c263df7f54835cd [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"
David Neto85082642018-03-24 06:55:20 -070049#include "clspv/spirv_c_strings.hpp"
50#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040051
David Neto4feb7a42017-10-06 17:29:42 -040052#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070053#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040054#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040055#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040056#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040057#include "Passes.h"
David Neto48f56a42017-10-06 16:44:25 -040058
David Neto22f144c2017-06-12 14:26:21 -040059#if defined(_MSC_VER)
60#pragma warning(pop)
61#endif
62
63using namespace llvm;
64using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040065using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040066
67namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040068
David Neto862b7d82018-06-14 18:48:37 -040069cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
70 cl::desc("Show resource variable creation"));
71
72// These hacks exist to help transition code generation algorithms
73// without making huge noise in detailed test output.
74const bool Hack_generate_runtime_array_stride_early = true;
75
David Neto3fbb4072017-10-16 11:28:14 -040076// The value of 1/pi. This value is from MSDN
77// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
78const double kOneOverPi = 0.318309886183790671538;
79const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
80
alan-bakerb6b09dc2018-11-08 16:59:28 -050081const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040082
David Neto22f144c2017-06-12 14:26:21 -040083enum SPIRVOperandType {
84 NUMBERID,
85 LITERAL_INTEGER,
86 LITERAL_STRING,
87 LITERAL_FLOAT
88};
89
90struct SPIRVOperand {
91 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
92 : Type(Ty), LiteralNum(1, Num) {}
93 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
94 : Type(Ty), LiteralStr(Str) {}
95 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
96 : Type(Ty), LiteralStr(Str) {}
97 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
98 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
99
100 SPIRVOperandType getType() { return Type; };
101 uint32_t getNumID() { return LiteralNum[0]; };
102 std::string getLiteralStr() { return LiteralStr; };
103 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
104
David Neto87846742018-04-11 17:36:22 -0400105 uint32_t GetNumWords() const {
106 switch (Type) {
107 case NUMBERID:
108 return 1;
109 case LITERAL_INTEGER:
110 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400111 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400112 case LITERAL_STRING:
113 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400114 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400115 }
116 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
117 }
118
David Neto22f144c2017-06-12 14:26:21 -0400119private:
120 SPIRVOperandType Type;
121 std::string LiteralStr;
122 SmallVector<uint32_t, 4> LiteralNum;
123};
124
David Netoc6f3ab22018-04-06 18:02:31 -0400125class SPIRVOperandList {
126public:
127 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500128 SPIRVOperandList(const SPIRVOperandList &other) = delete;
129 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400130 contents_ = std::move(other.contents_);
131 other.contents_.clear();
132 }
133 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
134 : contents_(init.begin(), init.end()) {}
135 operator ArrayRef<SPIRVOperand *>() { return contents_; }
136 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500137 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400138 size_t size() const { return contents_.size(); }
139 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
140
David Neto87846742018-04-11 17:36:22 -0400141 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
142 return contents_;
143 }
144
David Netoc6f3ab22018-04-06 18:02:31 -0400145private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500146 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400147};
148
149SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
150 list.push_back(elem);
151 return list;
152}
153
alan-bakerb6b09dc2018-11-08 16:59:28 -0500154SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400155 return new SPIRVOperand(LITERAL_INTEGER, num);
156}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500157SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400158 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
159}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500160SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400161 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
162}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500163SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
164SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400165 return new SPIRVOperand(LITERAL_STRING, str);
166}
David Netoc6f3ab22018-04-06 18:02:31 -0400167
David Neto22f144c2017-06-12 14:26:21 -0400168struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400169 // Create an instruction with an opcode and no result ID, and with the given
170 // operands. This computes its own word count.
171 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
172 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
173 Operands(Ops.begin(), Ops.end()) {
174 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400175 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400176 }
177 }
178 // Create an instruction with an opcode and a no-zero result ID, and
179 // with the given operands. This computes its own word count.
180 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400181 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400182 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
183 Operands(Ops.begin(), Ops.end()) {
184 if (ResID == 0) {
185 llvm_unreachable("Result ID of 0 was provided");
186 }
187 for (auto *operand : Ops) {
188 WordCount += operand->GetNumWords();
189 }
190 }
David Neto22f144c2017-06-12 14:26:21 -0400191
David Netoee2660d2018-06-28 16:31:29 -0400192 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400193 uint16_t getOpcode() const { return Opcode; }
194 uint32_t getResultID() const { return ResultID; }
195 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
196
197private:
David Netoee2660d2018-06-28 16:31:29 -0400198 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400199 uint16_t Opcode;
200 uint32_t ResultID;
201 SmallVector<SPIRVOperand *, 4> Operands;
202};
203
204struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400205 typedef DenseMap<Type *, uint32_t> TypeMapType;
206 typedef UniqueVector<Type *> TypeList;
207 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400208 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400209 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
210 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400211 // A vector of tuples, each of which is:
212 // - the LLVM instruction that we will later generate SPIR-V code for
213 // - where the SPIR-V instruction should be inserted
214 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400215 typedef std::vector<
216 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
217 DeferredInstVecType;
218 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
219 GlobalConstFuncMapType;
220
David Neto44795152017-07-13 15:45:28 -0400221 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500222 raw_pwrite_stream &out,
223 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400224 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
225 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400226 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400227 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500228 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500230 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
231 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
232 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
233 }
David Neto22f144c2017-06-12 14:26:21 -0400234
235 void getAnalysisUsage(AnalysisUsage &AU) const override {
236 AU.addRequired<DominatorTreeWrapperPass>();
237 AU.addRequired<LoopInfoWrapperPass>();
238 }
239
240 virtual bool runOnModule(Module &module) override;
241
242 // output the SPIR-V header block
243 void outputHeader();
244
245 // patch the SPIR-V header block
246 void patchHeader();
247
248 uint32_t lookupType(Type *Ty) {
249 if (Ty->isPointerTy() &&
250 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
251 auto PointeeTy = Ty->getPointerElementType();
252 if (PointeeTy->isStructTy() &&
253 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
254 Ty = PointeeTy;
255 }
256 }
257
David Neto862b7d82018-06-14 18:48:37 -0400258 auto where = TypeMap.find(Ty);
259 if (where == TypeMap.end()) {
260 if (Ty) {
261 errs() << "Unhandled type " << *Ty << "\n";
262 } else {
263 errs() << "Unhandled type (null)\n";
264 }
David Netoe439d702018-03-23 13:14:08 -0700265 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400266 }
267
David Neto862b7d82018-06-14 18:48:37 -0400268 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400269 }
270 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
271 TypeList &getTypeList() { return Types; };
272 ValueList &getConstantList() { return Constants; };
273 ValueMapType &getValueMap() { return ValueMap; }
274 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
275 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400276 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
277 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
278 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
279 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
280 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500281 bool hasVariablePointersStorageBuffer() {
282 return HasVariablePointersStorageBuffer;
283 }
284 void setVariablePointersStorageBuffer(bool Val) {
285 HasVariablePointersStorageBuffer = Val;
286 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400287 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400288 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500289 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
290 return samplerMap;
291 }
David Neto22f144c2017-06-12 14:26:21 -0400292 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
293 return GlobalConstFuncTypeMap;
294 }
295 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
296 return GlobalConstArgumentSet;
297 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500298 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400299
David Netoc6f3ab22018-04-06 18:02:31 -0400300 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500301 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
302 // *not* be converted to a storage buffer, replace each such global variable
303 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400304 void FindGlobalConstVars(Module &M, const DataLayout &DL);
305 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
306 // ModuleOrderedResourceVars.
307 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400308 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400309 bool FindExtInst(Module &M);
310 void FindTypePerGlobalVar(GlobalVariable &GV);
311 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400312 void FindTypesForSamplerMap(Module &M);
313 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500314 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
315 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400316 void FindType(Type *Ty);
317 void FindConstantPerGlobalVar(GlobalVariable &GV);
318 void FindConstantPerFunc(Function &F);
319 void FindConstant(Value *V);
320 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400321 // Generates instructions for SPIR-V types corresponding to the LLVM types
322 // saved in the |Types| member. A type follows its subtypes. IDs are
323 // allocated sequentially starting with the current value of nextID, and
324 // with a type following its subtypes. Also updates nextID to just beyond
325 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500326 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400327 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400328 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400329 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400330 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400331 // Generate descriptor map entries for resource variables associated with
332 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500333 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400334 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400335 // Generate OpVariables for %clspv.resource.var.* calls.
336 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400337 void GenerateFuncPrologue(Function &F);
338 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400339 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400340 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
341 spv::Op GetSPIRVCastOpcode(Instruction &I);
342 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
343 void GenerateInstruction(Instruction &I);
344 void GenerateFuncEpilogue();
345 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500346 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400347 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400348 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
349 // have been created.
350 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400351 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400352 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400353 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400354 // Returns the GLSL extended instruction enum that the given function
355 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400356 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400357 // Returns the GLSL extended instruction enum indirectly used by the given
358 // function. That is, to implement the given function, we use an extended
359 // instruction plus one more instruction. If none, then returns the 0 value,
360 // i.e. GLSLstd4580Bad.
361 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
362 // Returns the single GLSL extended instruction used directly or
363 // indirectly by the given function call.
364 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400365 void PrintResID(SPIRVInstruction *Inst);
366 void PrintOpcode(SPIRVInstruction *Inst);
367 void PrintOperand(SPIRVOperand *Op);
368 void PrintCapability(SPIRVOperand *Op);
369 void PrintExtInst(SPIRVOperand *Op);
370 void PrintAddrModel(SPIRVOperand *Op);
371 void PrintMemModel(SPIRVOperand *Op);
372 void PrintExecModel(SPIRVOperand *Op);
373 void PrintExecMode(SPIRVOperand *Op);
374 void PrintSourceLanguage(SPIRVOperand *Op);
375 void PrintFuncCtrl(SPIRVOperand *Op);
376 void PrintStorageClass(SPIRVOperand *Op);
377 void PrintDecoration(SPIRVOperand *Op);
378 void PrintBuiltIn(SPIRVOperand *Op);
379 void PrintSelectionControl(SPIRVOperand *Op);
380 void PrintLoopControl(SPIRVOperand *Op);
381 void PrintDimensionality(SPIRVOperand *Op);
382 void PrintImageFormat(SPIRVOperand *Op);
383 void PrintMemoryAccess(SPIRVOperand *Op);
384 void PrintImageOperandsType(SPIRVOperand *Op);
385 void WriteSPIRVAssembly();
386 void WriteOneWord(uint32_t Word);
387 void WriteResultID(SPIRVInstruction *Inst);
388 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
389 void WriteOperand(SPIRVOperand *Op);
390 void WriteSPIRVBinary();
391
Alan Baker9bf93fb2018-08-28 16:59:26 -0400392 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500393 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400394
Alan Bakerfcda9482018-10-02 17:09:59 -0400395 // Populate UBO remapped type maps.
396 void PopulateUBOTypeMaps(Module &module);
397
398 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
399 // uses the internal map, otherwise it falls back on the data layout.
400 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
401 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
402 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
403
alan-baker5b86ed72019-02-15 08:26:50 -0500404 // Returns the base pointer of |v|.
405 Value *GetBasePointer(Value *v);
406
407 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
408 // |address_space|.
409 void setVariablePointersCapabilities(unsigned address_space);
410
411 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
412 // variable.
413 bool sameResource(Value *lhs, Value *rhs) const;
414
415 // Returns true if |inst| is phi or select that selects from the same
416 // structure (or null).
417 bool selectFromSameObject(Instruction *inst);
418
alan-bakere9308012019-03-15 10:25:13 -0400419 // Returns true if |Arg| is called with a coherent resource.
420 bool CalledWithCoherentResource(Argument &Arg);
421
David Neto22f144c2017-06-12 14:26:21 -0400422private:
423 static char ID;
David Neto44795152017-07-13 15:45:28 -0400424 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400425 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400426
427 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
428 // convert to other formats on demand?
429
430 // When emitting a C initialization list, the WriteSPIRVBinary method
431 // will actually write its words to this vector via binaryTempOut.
432 SmallVector<char, 100> binaryTempUnderlyingVector;
433 raw_svector_ostream binaryTempOut;
434
435 // Binary output writes to this stream, which might be |out| or
436 // |binaryTempOut|. It's the latter when we really want to write a C
437 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400438 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500439 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400440 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400441 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400442 uint64_t patchBoundOffset;
443 uint32_t nextID;
444
David Neto19a1bad2017-08-25 15:01:41 -0400445 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400446 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400447 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400448 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400449 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400450 TypeList Types;
451 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400452 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400453 ValueMapType ValueMap;
454 ValueMapType AllocatedValueMap;
455 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400456
David Neto22f144c2017-06-12 14:26:21 -0400457 EntryPointVecType EntryPointVec;
458 DeferredInstVecType DeferredInstVec;
459 ValueList EntryPointInterfacesVec;
460 uint32_t OpExtInstImportID;
461 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500462 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400463 bool HasVariablePointers;
464 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500465 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700466
467 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700468 // will map F's type to (G, index of the parameter), where in a first phase
469 // G is F's type. During FindTypePerFunc, G will be changed to F's type
470 // but replacing the pointer-to-constant parameter with
471 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700472 // TODO(dneto): This doesn't seem general enough? A function might have
473 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400474 GlobalConstFuncMapType GlobalConstFuncTypeMap;
475 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400476 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700477 // or array types, and which point into transparent memory (StorageBuffer
478 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400479 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700480 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400481
482 // This is truly ugly, but works around what look like driver bugs.
483 // For get_local_size, an earlier part of the flow has created a module-scope
484 // variable in Private address space to hold the value for the workgroup
485 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
486 // When this is present, save the IDs of the initializer value and variable
487 // in these two variables. We only ever do a vector load from it, and
488 // when we see one of those, substitute just the value of the intializer.
489 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700490 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400491 uint32_t WorkgroupSizeValueID;
492 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400493
David Neto862b7d82018-06-14 18:48:37 -0400494 // Bookkeeping for mapping kernel arguments to resource variables.
495 struct ResourceVarInfo {
496 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400497 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400498 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400499 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400500 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
501 const int index; // Index into ResourceVarInfoList
502 const unsigned descriptor_set;
503 const unsigned binding;
504 Function *const var_fn; // The @clspv.resource.var.* function.
505 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400506 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400507 const unsigned addr_space; // The LLVM address space
508 // The SPIR-V ID of the OpVariable. Not populated at construction time.
509 uint32_t var_id = 0;
510 };
511 // A list of resource var info. Each one correponds to a module-scope
512 // resource variable we will have to create. Resource var indices are
513 // indices into this vector.
514 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
515 // This is a vector of pointers of all the resource vars, but ordered by
516 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500517 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400518 // Map a function to the ordered list of resource variables it uses, one for
519 // each argument. If an argument does not use a resource variable, it
520 // will have a null pointer entry.
521 using FunctionToResourceVarsMapType =
522 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
523 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
524
525 // What LLVM types map to SPIR-V types needing layout? These are the
526 // arrays and structures supporting storage buffers and uniform buffers.
527 TypeList TypesNeedingLayout;
528 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
529 UniqueVector<StructType *> StructTypesNeedingBlock;
530 // For a call that represents a load from an opaque type (samplers, images),
531 // map it to the variable id it should load from.
532 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700533
Alan Baker202c8c72018-08-13 13:47:44 -0400534 // One larger than the maximum used SpecId for pointer-to-local arguments.
535 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400536 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500537 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400538 LocalArgList LocalArgs;
539 // Information about a pointer-to-local argument.
540 struct LocalArgInfo {
541 // The SPIR-V ID of the array variable.
542 uint32_t variable_id;
543 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500544 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400545 // The ID of the array type.
546 uint32_t array_size_id;
547 // The ID of the array type.
548 uint32_t array_type_id;
549 // The ID of the pointer to the array type.
550 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400551 // The specialization constant ID of the array size.
552 int spec_id;
553 };
Alan Baker202c8c72018-08-13 13:47:44 -0400554 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500555 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400556 // A mapping from SpecId to its LocalArgInfo.
557 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400558 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500559 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400560 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500561 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
562 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400563
564 // The ID of 32-bit integer zero constant. This is only valid after
565 // GenerateSPIRVConstants has run.
566 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400567};
568
569char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400570
alan-bakerb6b09dc2018-11-08 16:59:28 -0500571} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400572
573namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500574ModulePass *createSPIRVProducerPass(
575 raw_pwrite_stream &out,
576 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
577 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
578 bool outputCInitList) {
579 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
580 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400581}
David Netoc2c368d2017-06-30 16:50:17 -0400582} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400583
584bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400585 binaryOut = outputCInitList ? &binaryTempOut : &out;
586
David Neto257c3892018-04-11 13:19:45 -0400587 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
588
Alan Bakerfcda9482018-10-02 17:09:59 -0400589 PopulateUBOTypeMaps(module);
590
David Neto22f144c2017-06-12 14:26:21 -0400591 // SPIR-V always begins with its header information
592 outputHeader();
593
David Netoc6f3ab22018-04-06 18:02:31 -0400594 const DataLayout &DL = module.getDataLayout();
595
David Neto22f144c2017-06-12 14:26:21 -0400596 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400597 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400598
David Neto22f144c2017-06-12 14:26:21 -0400599 // Collect information on global variables too.
600 for (GlobalVariable &GV : module.globals()) {
601 // If the GV is one of our special __spirv_* variables, remove the
602 // initializer as it was only placed there to force LLVM to not throw the
603 // value away.
604 if (GV.getName().startswith("__spirv_")) {
605 GV.setInitializer(nullptr);
606 }
607
608 // Collect types' information from global variable.
609 FindTypePerGlobalVar(GV);
610
611 // Collect constant information from global variable.
612 FindConstantPerGlobalVar(GV);
613
614 // If the variable is an input, entry points need to know about it.
615 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400616 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400617 }
618 }
619
620 // If there are extended instructions, generate OpExtInstImport.
621 if (FindExtInst(module)) {
622 GenerateExtInstImport();
623 }
624
625 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400626 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400627
628 // Generate SPIRV constants.
629 GenerateSPIRVConstants();
630
631 // If we have a sampler map, we might have literal samplers to generate.
632 if (0 < getSamplerMap().size()) {
633 GenerateSamplers(module);
634 }
635
636 // Generate SPIRV variables.
637 for (GlobalVariable &GV : module.globals()) {
638 GenerateGlobalVar(GV);
639 }
David Neto862b7d82018-06-14 18:48:37 -0400640 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400641 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400642
643 // Generate SPIRV instructions for each function.
644 for (Function &F : module) {
645 if (F.isDeclaration()) {
646 continue;
647 }
648
David Neto862b7d82018-06-14 18:48:37 -0400649 GenerateDescriptorMapInfo(DL, F);
650
David Neto22f144c2017-06-12 14:26:21 -0400651 // Generate Function Prologue.
652 GenerateFuncPrologue(F);
653
654 // Generate SPIRV instructions for function body.
655 GenerateFuncBody(F);
656
657 // Generate Function Epilogue.
658 GenerateFuncEpilogue();
659 }
660
661 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400662 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400663
664 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400665 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400666
667 if (outputAsm) {
668 WriteSPIRVAssembly();
669 } else {
670 WriteSPIRVBinary();
671 }
672
673 // We need to patch the SPIR-V header to set bound correctly.
674 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400675
676 if (outputCInitList) {
677 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400678 std::ostringstream os;
679
David Neto57fb0b92017-08-04 15:35:09 -0400680 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400681 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400682 os << ",\n";
683 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400684 first = false;
685 };
686
687 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400688 const std::string str(binaryTempOut.str());
689 for (unsigned i = 0; i < str.size(); i += 4) {
690 const uint32_t a = static_cast<unsigned char>(str[i]);
691 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
692 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
693 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
694 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400695 }
696 os << "}\n";
697 out << os.str();
698 }
699
David Neto22f144c2017-06-12 14:26:21 -0400700 return false;
701}
702
703void SPIRVProducerPass::outputHeader() {
704 if (outputAsm) {
705 // for ASM output the header goes into 5 comments at the beginning of the
706 // file
707 out << "; SPIR-V\n";
708
709 // the major version number is in the 2nd highest byte
710 const uint32_t major = (spv::Version >> 16) & 0xFF;
711
712 // the minor version number is in the 2nd lowest byte
713 const uint32_t minor = (spv::Version >> 8) & 0xFF;
714 out << "; Version: " << major << "." << minor << "\n";
715
716 // use Codeplay's vendor ID
717 out << "; Generator: Codeplay; 0\n";
718
719 out << "; Bound: ";
720
721 // we record where we need to come back to and patch in the bound value
722 patchBoundOffset = out.tell();
723
724 // output one space per digit for the max size of a 32 bit unsigned integer
725 // (which is the maximum ID we could possibly be using)
726 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
727 out << " ";
728 }
729
730 out << "\n";
731
732 out << "; Schema: 0\n";
733 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400734 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500735 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400736 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500737 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400738
739 // use Codeplay's vendor ID
740 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400741 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400742
743 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400744 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400745
746 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400747 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400748
749 // output the schema (reserved for use and must be 0)
750 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400751 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400752 }
753}
754
755void SPIRVProducerPass::patchHeader() {
756 if (outputAsm) {
757 // get the string representation of the max bound used (nextID will be the
758 // max ID used)
759 auto asString = std::to_string(nextID);
760 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
761 } else {
762 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400763 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
764 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400765 }
766}
767
David Netoc6f3ab22018-04-06 18:02:31 -0400768void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400769 // This function generates LLVM IR for function such as global variable for
770 // argument, constant and pointer type for argument access. These information
771 // is artificial one because we need Vulkan SPIR-V output. This function is
772 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400773 LLVMContext &Context = M.getContext();
774
David Neto862b7d82018-06-14 18:48:37 -0400775 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400776
David Neto862b7d82018-06-14 18:48:37 -0400777 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400778
779 bool HasWorkGroupBuiltin = false;
780 for (GlobalVariable &GV : M.globals()) {
781 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
782 if (spv::BuiltInWorkgroupSize == BuiltinType) {
783 HasWorkGroupBuiltin = true;
784 }
785 }
786
David Neto862b7d82018-06-14 18:48:37 -0400787 FindTypesForSamplerMap(M);
788 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400789 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400790
David Neto862b7d82018-06-14 18:48:37 -0400791 // These function calls need a <2 x i32> as an intermediate result but not
792 // the final result.
793 std::unordered_set<std::string> NeedsIVec2{
794 "_Z15get_image_width14ocl_image2d_ro",
795 "_Z15get_image_width14ocl_image2d_wo",
796 "_Z16get_image_height14ocl_image2d_ro",
797 "_Z16get_image_height14ocl_image2d_wo",
798 };
799
David Neto22f144c2017-06-12 14:26:21 -0400800 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000801 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400802 continue;
803 }
804
805 for (BasicBlock &BB : F) {
806 for (Instruction &I : BB) {
807 if (I.getOpcode() == Instruction::ZExt ||
808 I.getOpcode() == Instruction::SExt ||
809 I.getOpcode() == Instruction::UIToFP) {
810 // If there is zext with i1 type, it will be changed to OpSelect. The
811 // OpSelect needs constant 0 and 1 so the constants are added here.
812
813 auto OpTy = I.getOperand(0)->getType();
814
Kévin Petit24272b62018-10-18 19:16:12 +0000815 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400816 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400817 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000818 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400819 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400820 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000821 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400822 } else {
823 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
824 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
825 }
826 }
827 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400828 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400829
830 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400831 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400832 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400833 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400834 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
835 TypeMapType &OpImageTypeMap = getImageTypeMap();
836 Type *ImageTy =
837 Call->getArgOperand(0)->getType()->getPointerElementType();
838 OpImageTypeMap[ImageTy] = 0;
839
840 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
841 }
David Neto5c22a252018-03-15 16:07:41 -0400842
David Neto862b7d82018-06-14 18:48:37 -0400843 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400844 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
845 }
David Neto22f144c2017-06-12 14:26:21 -0400846 }
847 }
848 }
849
Kévin Petitabef4522019-03-27 13:08:01 +0000850 // More things to do on kernel functions
851 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
852 if (const MDNode *MD =
853 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
854 // We generate constants if the WorkgroupSize builtin is being used.
855 if (HasWorkGroupBuiltin) {
856 // Collect constant information for work group size.
857 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
858 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
859 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400860 }
861 }
862 }
863
864 if (M.getTypeByName("opencl.image2d_ro_t") ||
865 M.getTypeByName("opencl.image2d_wo_t") ||
866 M.getTypeByName("opencl.image3d_ro_t") ||
867 M.getTypeByName("opencl.image3d_wo_t")) {
868 // Assume Image type's sampled type is float type.
869 FindType(Type::getFloatTy(Context));
870 }
871
872 // Collect types' information from function.
873 FindTypePerFunc(F);
874
875 // Collect constant information from function.
876 FindConstantPerFunc(F);
877 }
878}
879
David Neto862b7d82018-06-14 18:48:37 -0400880void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400881 clspv::NormalizeGlobalVariables(M);
882
David Neto862b7d82018-06-14 18:48:37 -0400883 SmallVector<GlobalVariable *, 8> GVList;
884 SmallVector<GlobalVariable *, 8> DeadGVList;
885 for (GlobalVariable &GV : M.globals()) {
886 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
887 if (GV.use_empty()) {
888 DeadGVList.push_back(&GV);
889 } else {
890 GVList.push_back(&GV);
891 }
892 }
893 }
894
895 // Remove dead global __constant variables.
896 for (auto GV : DeadGVList) {
897 GV->eraseFromParent();
898 }
899 DeadGVList.clear();
900
901 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
902 // For now, we only support a single storage buffer.
903 if (GVList.size() > 0) {
904 assert(GVList.size() == 1);
905 const auto *GV = GVList[0];
906 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400907 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400908 const size_t kConstantMaxSize = 65536;
909 if (constants_byte_size > kConstantMaxSize) {
910 outs() << "Max __constant capacity of " << kConstantMaxSize
911 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
912 llvm_unreachable("Max __constant capacity exceeded");
913 }
914 }
915 } else {
916 // Change global constant variable's address space to ModuleScopePrivate.
917 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
918 for (auto GV : GVList) {
919 // Create new gv with ModuleScopePrivate address space.
920 Type *NewGVTy = GV->getType()->getPointerElementType();
921 GlobalVariable *NewGV = new GlobalVariable(
922 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
923 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
924 NewGV->takeName(GV);
925
926 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
927 SmallVector<User *, 8> CandidateUsers;
928
929 auto record_called_function_type_as_user =
930 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
931 // Find argument index.
932 unsigned index = 0;
933 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
934 if (gv == call->getOperand(i)) {
935 // TODO(dneto): Should we break here?
936 index = i;
937 }
938 }
939
940 // Record function type with global constant.
941 GlobalConstFuncTyMap[call->getFunctionType()] =
942 std::make_pair(call->getFunctionType(), index);
943 };
944
945 for (User *GVU : GVUsers) {
946 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
947 record_called_function_type_as_user(GV, Call);
948 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
949 // Check GEP users.
950 for (User *GEPU : GEP->users()) {
951 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
952 record_called_function_type_as_user(GEP, GEPCall);
953 }
954 }
955 }
956
957 CandidateUsers.push_back(GVU);
958 }
959
960 for (User *U : CandidateUsers) {
961 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500962 if (!isa<Constant>(U)) {
963 // #254: Can't change operands of a constant, but this shouldn't be
964 // something that sticks around in the module.
965 U->replaceUsesOfWith(GV, NewGV);
966 }
David Neto862b7d82018-06-14 18:48:37 -0400967 }
968
969 // Delete original gv.
970 GV->eraseFromParent();
971 }
972 }
973}
974
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100975void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400976 ResourceVarInfoList.clear();
977 FunctionToResourceVarsMap.clear();
978 ModuleOrderedResourceVars.reset();
979 // Normally, there is one resource variable per clspv.resource.var.*
980 // function, since that is unique'd by arg type and index. By design,
981 // we can share these resource variables across kernels because all
982 // kernels use the same descriptor set.
983 //
984 // But if the user requested distinct descriptor sets per kernel, then
985 // the descriptor allocator has made different (set,binding) pairs for
986 // the same (type,arg_index) pair. Since we can decorate a resource
987 // variable with only exactly one DescriptorSet and Binding, we are
988 // forced in this case to make distinct resource variables whenever
989 // the same clspv.reource.var.X function is seen with disintct
990 // (set,binding) values.
991 const bool always_distinct_sets =
992 clspv::Option::DistinctKernelDescriptorSets();
993 for (Function &F : M) {
994 // Rely on the fact the resource var functions have a stable ordering
995 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400996 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400997 // Find all calls to this function with distinct set and binding pairs.
998 // Save them in ResourceVarInfoList.
999
1000 // Determine uniqueness of the (set,binding) pairs only withing this
1001 // one resource-var builtin function.
1002 using SetAndBinding = std::pair<unsigned, unsigned>;
1003 // Maps set and binding to the resource var info.
1004 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1005 bool first_use = true;
1006 for (auto &U : F.uses()) {
1007 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1008 const auto set = unsigned(
1009 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1010 const auto binding = unsigned(
1011 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1012 const auto arg_kind = clspv::ArgKind(
1013 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1014 const auto arg_index = unsigned(
1015 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001016 const auto coherent = unsigned(
1017 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001018
1019 // Find or make the resource var info for this combination.
1020 ResourceVarInfo *rv = nullptr;
1021 if (always_distinct_sets) {
1022 // Make a new resource var any time we see a different
1023 // (set,binding) pair.
1024 SetAndBinding key{set, binding};
1025 auto where = set_and_binding_map.find(key);
1026 if (where == set_and_binding_map.end()) {
1027 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001028 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001029 ResourceVarInfoList.emplace_back(rv);
1030 set_and_binding_map[key] = rv;
1031 } else {
1032 rv = where->second;
1033 }
1034 } else {
1035 // The default is to make exactly one resource for each
1036 // clspv.resource.var.* function.
1037 if (first_use) {
1038 first_use = false;
1039 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001040 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001041 ResourceVarInfoList.emplace_back(rv);
1042 } else {
1043 rv = ResourceVarInfoList.back().get();
1044 }
1045 }
1046
1047 // Now populate FunctionToResourceVarsMap.
1048 auto &mapping =
1049 FunctionToResourceVarsMap[call->getParent()->getParent()];
1050 while (mapping.size() <= arg_index) {
1051 mapping.push_back(nullptr);
1052 }
1053 mapping[arg_index] = rv;
1054 }
1055 }
1056 }
1057 }
1058
1059 // Populate ModuleOrderedResourceVars.
1060 for (Function &F : M) {
1061 auto where = FunctionToResourceVarsMap.find(&F);
1062 if (where != FunctionToResourceVarsMap.end()) {
1063 for (auto &rv : where->second) {
1064 if (rv != nullptr) {
1065 ModuleOrderedResourceVars.insert(rv);
1066 }
1067 }
1068 }
1069 }
1070 if (ShowResourceVars) {
1071 for (auto *info : ModuleOrderedResourceVars) {
1072 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1073 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1074 << "\n";
1075 }
1076 }
1077}
1078
David Neto22f144c2017-06-12 14:26:21 -04001079bool SPIRVProducerPass::FindExtInst(Module &M) {
1080 LLVMContext &Context = M.getContext();
1081 bool HasExtInst = false;
1082
1083 for (Function &F : M) {
1084 for (BasicBlock &BB : F) {
1085 for (Instruction &I : BB) {
1086 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1087 Function *Callee = Call->getCalledFunction();
1088 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001089 auto callee_name = Callee->getName();
1090 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1091 const glsl::ExtInst IndirectEInst =
1092 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001093
David Neto3fbb4072017-10-16 11:28:14 -04001094 HasExtInst |=
1095 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1096
1097 if (IndirectEInst) {
1098 // Register extra constants if needed.
1099
1100 // Registers a type and constant for computing the result of the
1101 // given instruction. If the result of the instruction is a vector,
1102 // then make a splat vector constant with the same number of
1103 // elements.
1104 auto register_constant = [this, &I](Constant *constant) {
1105 FindType(constant->getType());
1106 FindConstant(constant);
1107 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1108 // Register the splat vector of the value with the same
1109 // width as the result of the instruction.
1110 auto *vec_constant = ConstantVector::getSplat(
1111 static_cast<unsigned>(vectorTy->getNumElements()),
1112 constant);
1113 FindConstant(vec_constant);
1114 FindType(vec_constant->getType());
1115 }
1116 };
1117 switch (IndirectEInst) {
1118 case glsl::ExtInstFindUMsb:
1119 // clz needs OpExtInst and OpISub with constant 31, or splat
1120 // vector of 31. Add it to the constant list here.
1121 register_constant(
1122 ConstantInt::get(Type::getInt32Ty(Context), 31));
1123 break;
1124 case glsl::ExtInstAcos:
1125 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001126 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001127 case glsl::ExtInstAtan2:
1128 // We need 1/pi for acospi, asinpi, atan2pi.
1129 register_constant(
1130 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1131 break;
1132 default:
1133 assert(false && "internally inconsistent");
1134 }
David Neto22f144c2017-06-12 14:26:21 -04001135 }
1136 }
1137 }
1138 }
1139 }
1140
1141 return HasExtInst;
1142}
1143
1144void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1145 // Investigate global variable's type.
1146 FindType(GV.getType());
1147}
1148
1149void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1150 // Investigate function's type.
1151 FunctionType *FTy = F.getFunctionType();
1152
1153 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1154 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001155 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001156 if (GlobalConstFuncTyMap.count(FTy)) {
1157 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1158 SmallVector<Type *, 4> NewFuncParamTys;
1159 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1160 Type *ParamTy = FTy->getParamType(i);
1161 if (i == GVCstArgIdx) {
1162 Type *EleTy = ParamTy->getPointerElementType();
1163 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1164 }
1165
1166 NewFuncParamTys.push_back(ParamTy);
1167 }
1168
1169 FunctionType *NewFTy =
1170 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1171 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1172 FTy = NewFTy;
1173 }
1174
1175 FindType(FTy);
1176 } else {
1177 // As kernel functions do not have parameters, create new function type and
1178 // add it to type map.
1179 SmallVector<Type *, 4> NewFuncParamTys;
1180 FunctionType *NewFTy =
1181 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1182 FindType(NewFTy);
1183 }
1184
1185 // Investigate instructions' type in function body.
1186 for (BasicBlock &BB : F) {
1187 for (Instruction &I : BB) {
1188 if (isa<ShuffleVectorInst>(I)) {
1189 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1190 // Ignore type for mask of shuffle vector instruction.
1191 if (i == 2) {
1192 continue;
1193 }
1194
1195 Value *Op = I.getOperand(i);
1196 if (!isa<MetadataAsValue>(Op)) {
1197 FindType(Op->getType());
1198 }
1199 }
1200
1201 FindType(I.getType());
1202 continue;
1203 }
1204
David Neto862b7d82018-06-14 18:48:37 -04001205 CallInst *Call = dyn_cast<CallInst>(&I);
1206
1207 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001208 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001209 // This is a fake call representing access to a resource variable.
1210 // We handle that elsewhere.
1211 continue;
1212 }
1213
Alan Baker202c8c72018-08-13 13:47:44 -04001214 if (Call && Call->getCalledFunction()->getName().startswith(
1215 clspv::WorkgroupAccessorFunction())) {
1216 // This is a fake call representing access to a workgroup variable.
1217 // We handle that elsewhere.
1218 continue;
1219 }
1220
David Neto22f144c2017-06-12 14:26:21 -04001221 // Work through the operands of the instruction.
1222 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1223 Value *const Op = I.getOperand(i);
1224 // If any of the operands is a constant, find the type!
1225 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1226 FindType(Op->getType());
1227 }
1228 }
1229
1230 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001231 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001232 // Avoid to check call instruction's type.
1233 break;
1234 }
Alan Baker202c8c72018-08-13 13:47:44 -04001235 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1236 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1237 clspv::WorkgroupAccessorFunction())) {
1238 // This is a fake call representing access to a workgroup variable.
1239 // We handle that elsewhere.
1240 continue;
1241 }
1242 }
David Neto22f144c2017-06-12 14:26:21 -04001243 if (!isa<MetadataAsValue>(&Op)) {
1244 FindType(Op->getType());
1245 continue;
1246 }
1247 }
1248
David Neto22f144c2017-06-12 14:26:21 -04001249 // We don't want to track the type of this call as we are going to replace
1250 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001251 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001252 Call->getCalledFunction()->getName())) {
1253 continue;
1254 }
1255
1256 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1257 // If gep's base operand has ModuleScopePrivate address space, make gep
1258 // return ModuleScopePrivate address space.
1259 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1260 // Add pointer type with private address space for global constant to
1261 // type list.
1262 Type *EleTy = I.getType()->getPointerElementType();
1263 Type *NewPTy =
1264 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1265
1266 FindType(NewPTy);
1267 continue;
1268 }
1269 }
1270
1271 FindType(I.getType());
1272 }
1273 }
1274}
1275
David Neto862b7d82018-06-14 18:48:37 -04001276void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1277 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001278 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001279 0 < getSamplerMap().size()) {
1280 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1281 if (!SamplerStructTy) {
1282 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1283 }
1284
1285 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1286
1287 FindType(SamplerTy);
1288 }
1289}
1290
1291void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1292 // Record types so they are generated.
1293 TypesNeedingLayout.reset();
1294 StructTypesNeedingBlock.reset();
1295
1296 // To match older clspv codegen, generate the float type first if required
1297 // for images.
1298 for (const auto *info : ModuleOrderedResourceVars) {
1299 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1300 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1301 // We need "float" for the sampled component type.
1302 FindType(Type::getFloatTy(M.getContext()));
1303 // We only need to find it once.
1304 break;
1305 }
1306 }
1307
1308 for (const auto *info : ModuleOrderedResourceVars) {
1309 Type *type = info->var_fn->getReturnType();
1310
1311 switch (info->arg_kind) {
1312 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001313 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001314 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1315 StructTypesNeedingBlock.insert(sty);
1316 } else {
1317 errs() << *type << "\n";
1318 llvm_unreachable("Buffer arguments must map to structures!");
1319 }
1320 break;
1321 case clspv::ArgKind::Pod:
1322 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1323 StructTypesNeedingBlock.insert(sty);
1324 } else {
1325 errs() << *type << "\n";
1326 llvm_unreachable("POD arguments must map to structures!");
1327 }
1328 break;
1329 case clspv::ArgKind::ReadOnlyImage:
1330 case clspv::ArgKind::WriteOnlyImage:
1331 case clspv::ArgKind::Sampler:
1332 // Sampler and image types map to the pointee type but
1333 // in the uniform constant address space.
1334 type = PointerType::get(type->getPointerElementType(),
1335 clspv::AddressSpace::UniformConstant);
1336 break;
1337 default:
1338 break;
1339 }
1340
1341 // The converted type is the type of the OpVariable we will generate.
1342 // If the pointee type is an array of size zero, FindType will convert it
1343 // to a runtime array.
1344 FindType(type);
1345 }
1346
1347 // Traverse the arrays and structures underneath each Block, and
1348 // mark them as needing layout.
1349 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1350 StructTypesNeedingBlock.end());
1351 while (!work_list.empty()) {
1352 Type *type = work_list.back();
1353 work_list.pop_back();
1354 TypesNeedingLayout.insert(type);
1355 switch (type->getTypeID()) {
1356 case Type::ArrayTyID:
1357 work_list.push_back(type->getArrayElementType());
1358 if (!Hack_generate_runtime_array_stride_early) {
1359 // Remember this array type for deferred decoration.
1360 TypesNeedingArrayStride.insert(type);
1361 }
1362 break;
1363 case Type::StructTyID:
1364 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1365 work_list.push_back(elem_ty);
1366 }
1367 default:
1368 // This type and its contained types don't get layout.
1369 break;
1370 }
1371 }
1372}
1373
Alan Baker202c8c72018-08-13 13:47:44 -04001374void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1375 // The SpecId assignment for pointer-to-local arguments is recorded in
1376 // module-level metadata. Translate that information into local argument
1377 // information.
1378 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001379 if (!nmd)
1380 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001381 for (auto operand : nmd->operands()) {
1382 MDTuple *tuple = cast<MDTuple>(operand);
1383 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1384 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001385 ConstantAsMetadata *arg_index_md =
1386 cast<ConstantAsMetadata>(tuple->getOperand(1));
1387 int arg_index = static_cast<int>(
1388 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1389 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001390
1391 ConstantAsMetadata *spec_id_md =
1392 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001393 int spec_id = static_cast<int>(
1394 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001395
1396 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1397 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001398 if (LocalSpecIdInfoMap.count(spec_id))
1399 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001400
1401 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1402 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1403 nextID + 1, nextID + 2,
1404 nextID + 3, spec_id};
1405 LocalSpecIdInfoMap[spec_id] = info;
1406 nextID += 4;
1407
1408 // Ensure the types necessary for this argument get generated.
1409 Type *IdxTy = Type::getInt32Ty(M.getContext());
1410 FindConstant(ConstantInt::get(IdxTy, 0));
1411 FindType(IdxTy);
1412 FindType(arg->getType());
1413 }
1414}
1415
David Neto22f144c2017-06-12 14:26:21 -04001416void SPIRVProducerPass::FindType(Type *Ty) {
1417 TypeList &TyList = getTypeList();
1418
1419 if (0 != TyList.idFor(Ty)) {
1420 return;
1421 }
1422
1423 if (Ty->isPointerTy()) {
1424 auto AddrSpace = Ty->getPointerAddressSpace();
1425 if ((AddressSpace::Constant == AddrSpace) ||
1426 (AddressSpace::Global == AddrSpace)) {
1427 auto PointeeTy = Ty->getPointerElementType();
1428
1429 if (PointeeTy->isStructTy() &&
1430 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1431 FindType(PointeeTy);
1432 auto ActualPointerTy =
1433 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1434 FindType(ActualPointerTy);
1435 return;
1436 }
1437 }
1438 }
1439
David Neto862b7d82018-06-14 18:48:37 -04001440 // By convention, LLVM array type with 0 elements will map to
1441 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1442 // has a constant number of elements. We need to support type of the
1443 // constant.
1444 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1445 if (arrayTy->getNumElements() > 0) {
1446 LLVMContext &Context = Ty->getContext();
1447 FindType(Type::getInt32Ty(Context));
1448 }
David Neto22f144c2017-06-12 14:26:21 -04001449 }
1450
1451 for (Type *SubTy : Ty->subtypes()) {
1452 FindType(SubTy);
1453 }
1454
1455 TyList.insert(Ty);
1456}
1457
1458void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1459 // If the global variable has a (non undef) initializer.
1460 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001461 // Generate the constant if it's not the initializer to a module scope
1462 // constant that we will expect in a storage buffer.
1463 const bool module_scope_constant_external_init =
1464 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1465 clspv::Option::ModuleConstantsInStorageBuffer();
1466 if (!module_scope_constant_external_init) {
1467 FindConstant(GV.getInitializer());
1468 }
David Neto22f144c2017-06-12 14:26:21 -04001469 }
1470}
1471
1472void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1473 // Investigate constants in function body.
1474 for (BasicBlock &BB : F) {
1475 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001476 if (auto *call = dyn_cast<CallInst>(&I)) {
1477 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001478 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001479 // We've handled these constants elsewhere, so skip it.
1480 continue;
1481 }
Alan Baker202c8c72018-08-13 13:47:44 -04001482 if (name.startswith(clspv::ResourceAccessorFunction())) {
1483 continue;
1484 }
1485 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001486 continue;
1487 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001488 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1489 // Skip the first operand that has the SPIR-V Opcode
1490 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1491 if (isa<Constant>(I.getOperand(i)) &&
1492 !isa<GlobalValue>(I.getOperand(i))) {
1493 FindConstant(I.getOperand(i));
1494 }
1495 }
1496 continue;
1497 }
David Neto22f144c2017-06-12 14:26:21 -04001498 }
1499
1500 if (isa<AllocaInst>(I)) {
1501 // Alloca instruction has constant for the number of element. Ignore it.
1502 continue;
1503 } else if (isa<ShuffleVectorInst>(I)) {
1504 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1505 // Ignore constant for mask of shuffle vector instruction.
1506 if (i == 2) {
1507 continue;
1508 }
1509
1510 if (isa<Constant>(I.getOperand(i)) &&
1511 !isa<GlobalValue>(I.getOperand(i))) {
1512 FindConstant(I.getOperand(i));
1513 }
1514 }
1515
1516 continue;
1517 } else if (isa<InsertElementInst>(I)) {
1518 // Handle InsertElement with <4 x i8> specially.
1519 Type *CompositeTy = I.getOperand(0)->getType();
1520 if (is4xi8vec(CompositeTy)) {
1521 LLVMContext &Context = CompositeTy->getContext();
1522 if (isa<Constant>(I.getOperand(0))) {
1523 FindConstant(I.getOperand(0));
1524 }
1525
1526 if (isa<Constant>(I.getOperand(1))) {
1527 FindConstant(I.getOperand(1));
1528 }
1529
1530 // Add mask constant 0xFF.
1531 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1532 FindConstant(CstFF);
1533
1534 // Add shift amount constant.
1535 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1536 uint64_t Idx = CI->getZExtValue();
1537 Constant *CstShiftAmount =
1538 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1539 FindConstant(CstShiftAmount);
1540 }
1541
1542 continue;
1543 }
1544
1545 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1546 // Ignore constant for index of InsertElement instruction.
1547 if (i == 2) {
1548 continue;
1549 }
1550
1551 if (isa<Constant>(I.getOperand(i)) &&
1552 !isa<GlobalValue>(I.getOperand(i))) {
1553 FindConstant(I.getOperand(i));
1554 }
1555 }
1556
1557 continue;
1558 } else if (isa<ExtractElementInst>(I)) {
1559 // Handle ExtractElement with <4 x i8> specially.
1560 Type *CompositeTy = I.getOperand(0)->getType();
1561 if (is4xi8vec(CompositeTy)) {
1562 LLVMContext &Context = CompositeTy->getContext();
1563 if (isa<Constant>(I.getOperand(0))) {
1564 FindConstant(I.getOperand(0));
1565 }
1566
1567 // Add mask constant 0xFF.
1568 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1569 FindConstant(CstFF);
1570
1571 // Add shift amount constant.
1572 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1573 uint64_t Idx = CI->getZExtValue();
1574 Constant *CstShiftAmount =
1575 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1576 FindConstant(CstShiftAmount);
1577 } else {
1578 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1579 FindConstant(Cst8);
1580 }
1581
1582 continue;
1583 }
1584
1585 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1586 // Ignore constant for index of ExtractElement instruction.
1587 if (i == 1) {
1588 continue;
1589 }
1590
1591 if (isa<Constant>(I.getOperand(i)) &&
1592 !isa<GlobalValue>(I.getOperand(i))) {
1593 FindConstant(I.getOperand(i));
1594 }
1595 }
1596
1597 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001598 } else if ((Instruction::Xor == I.getOpcode()) &&
1599 I.getType()->isIntegerTy(1)) {
1600 // We special case for Xor where the type is i1 and one of the arguments
1601 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1602 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001603 bool foundConstantTrue = false;
1604 for (Use &Op : I.operands()) {
1605 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1606 auto CI = cast<ConstantInt>(Op);
1607
1608 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001609 // If we already found the true constant, we might (probably only
1610 // on -O0) have an OpLogicalNot which is taking a constant
1611 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001612 FindConstant(Op);
1613 } else {
1614 foundConstantTrue = true;
1615 }
1616 }
1617 }
1618
1619 continue;
David Netod2de94a2017-08-28 17:27:47 -04001620 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001621 // Special case if i8 is not generally handled.
1622 if (!clspv::Option::Int8Support()) {
1623 // For truncation to i8 we mask against 255.
1624 Type *ToTy = I.getType();
1625 if (8u == ToTy->getPrimitiveSizeInBits()) {
1626 LLVMContext &Context = ToTy->getContext();
1627 Constant *Cst255 =
1628 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1629 FindConstant(Cst255);
1630 }
David Netod2de94a2017-08-28 17:27:47 -04001631 }
Neil Henning39672102017-09-29 14:33:13 +01001632 } else if (isa<AtomicRMWInst>(I)) {
1633 LLVMContext &Context = I.getContext();
1634
1635 FindConstant(
1636 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1637 FindConstant(ConstantInt::get(
1638 Type::getInt32Ty(Context),
1639 spv::MemorySemanticsUniformMemoryMask |
1640 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001641 }
1642
1643 for (Use &Op : I.operands()) {
1644 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1645 FindConstant(Op);
1646 }
1647 }
1648 }
1649 }
1650}
1651
1652void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001653 ValueList &CstList = getConstantList();
1654
David Netofb9a7972017-08-25 17:08:24 -04001655 // If V is already tracked, ignore it.
1656 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001657 return;
1658 }
1659
David Neto862b7d82018-06-14 18:48:37 -04001660 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1661 return;
1662 }
1663
David Neto22f144c2017-06-12 14:26:21 -04001664 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001665 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001666
1667 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001668 if (is4xi8vec(CstTy)) {
1669 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001670 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001671 }
1672 }
1673
1674 if (Cst->getNumOperands()) {
1675 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1676 ++I) {
1677 FindConstant(*I);
1678 }
1679
David Netofb9a7972017-08-25 17:08:24 -04001680 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001681 return;
1682 } else if (const ConstantDataSequential *CDS =
1683 dyn_cast<ConstantDataSequential>(Cst)) {
1684 // Add constants for each element to constant list.
1685 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1686 Constant *EleCst = CDS->getElementAsConstant(i);
1687 FindConstant(EleCst);
1688 }
1689 }
1690
1691 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001692 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001693 }
1694}
1695
1696spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1697 switch (AddrSpace) {
1698 default:
1699 llvm_unreachable("Unsupported OpenCL address space");
1700 case AddressSpace::Private:
1701 return spv::StorageClassFunction;
1702 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001703 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001704 case AddressSpace::Constant:
1705 return clspv::Option::ConstantArgsInUniformBuffer()
1706 ? spv::StorageClassUniform
1707 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001708 case AddressSpace::Input:
1709 return spv::StorageClassInput;
1710 case AddressSpace::Local:
1711 return spv::StorageClassWorkgroup;
1712 case AddressSpace::UniformConstant:
1713 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001714 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001715 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001716 case AddressSpace::ModuleScopePrivate:
1717 return spv::StorageClassPrivate;
1718 }
1719}
1720
David Neto862b7d82018-06-14 18:48:37 -04001721spv::StorageClass
1722SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1723 switch (arg_kind) {
1724 case clspv::ArgKind::Buffer:
1725 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001726 case clspv::ArgKind::BufferUBO:
1727 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001728 case clspv::ArgKind::Pod:
1729 return clspv::Option::PodArgsInUniformBuffer()
1730 ? spv::StorageClassUniform
1731 : spv::StorageClassStorageBuffer;
1732 case clspv::ArgKind::Local:
1733 return spv::StorageClassWorkgroup;
1734 case clspv::ArgKind::ReadOnlyImage:
1735 case clspv::ArgKind::WriteOnlyImage:
1736 case clspv::ArgKind::Sampler:
1737 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001738 default:
1739 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001740 }
1741}
1742
David Neto22f144c2017-06-12 14:26:21 -04001743spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1744 return StringSwitch<spv::BuiltIn>(Name)
1745 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1746 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1747 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1748 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1749 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1750 .Default(spv::BuiltInMax);
1751}
1752
1753void SPIRVProducerPass::GenerateExtInstImport() {
1754 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1755 uint32_t &ExtInstImportID = getOpExtInstImportID();
1756
1757 //
1758 // Generate OpExtInstImport.
1759 //
1760 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001761 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001762 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1763 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001764}
1765
alan-bakerb6b09dc2018-11-08 16:59:28 -05001766void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1767 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001768 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1769 ValueMapType &VMap = getValueMap();
1770 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001771 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001772
1773 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1774 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1775 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1776
1777 for (Type *Ty : getTypeList()) {
1778 // Update TypeMap with nextID for reference later.
1779 TypeMap[Ty] = nextID;
1780
1781 switch (Ty->getTypeID()) {
1782 default: {
1783 Ty->print(errs());
1784 llvm_unreachable("Unsupported type???");
1785 break;
1786 }
1787 case Type::MetadataTyID:
1788 case Type::LabelTyID: {
1789 // Ignore these types.
1790 break;
1791 }
1792 case Type::PointerTyID: {
1793 PointerType *PTy = cast<PointerType>(Ty);
1794 unsigned AddrSpace = PTy->getAddressSpace();
1795
1796 // For the purposes of our Vulkan SPIR-V type system, constant and global
1797 // are conflated.
1798 bool UseExistingOpTypePointer = false;
1799 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001800 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1801 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001802 // Check to see if we already created this type (for instance, if we
1803 // had a constant <type>* and a global <type>*, the type would be
1804 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001805 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1806 if (0 < TypeMap.count(GlobalTy)) {
1807 TypeMap[PTy] = TypeMap[GlobalTy];
1808 UseExistingOpTypePointer = true;
1809 break;
1810 }
David Neto22f144c2017-06-12 14:26:21 -04001811 }
1812 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001813 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1814 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001815
alan-bakerb6b09dc2018-11-08 16:59:28 -05001816 // Check to see if we already created this type (for instance, if we
1817 // had a constant <type>* and a global <type>*, the type would be
1818 // created by one of these types, and shared by both).
1819 auto ConstantTy =
1820 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001821 if (0 < TypeMap.count(ConstantTy)) {
1822 TypeMap[PTy] = TypeMap[ConstantTy];
1823 UseExistingOpTypePointer = true;
1824 }
David Neto22f144c2017-06-12 14:26:21 -04001825 }
1826 }
1827
David Neto862b7d82018-06-14 18:48:37 -04001828 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001829
David Neto862b7d82018-06-14 18:48:37 -04001830 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001831 //
1832 // Generate OpTypePointer.
1833 //
1834
1835 // OpTypePointer
1836 // Ops[0] = Storage Class
1837 // Ops[1] = Element Type ID
1838 SPIRVOperandList Ops;
1839
David Neto257c3892018-04-11 13:19:45 -04001840 Ops << MkNum(GetStorageClass(AddrSpace))
1841 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001842
David Neto87846742018-04-11 17:36:22 -04001843 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001844 SPIRVInstList.push_back(Inst);
1845 }
David Neto22f144c2017-06-12 14:26:21 -04001846 break;
1847 }
1848 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001849 StructType *STy = cast<StructType>(Ty);
1850
1851 // Handle sampler type.
1852 if (STy->isOpaque()) {
1853 if (STy->getName().equals("opencl.sampler_t")) {
1854 //
1855 // Generate OpTypeSampler
1856 //
1857 // Empty Ops.
1858 SPIRVOperandList Ops;
1859
David Neto87846742018-04-11 17:36:22 -04001860 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001861 SPIRVInstList.push_back(Inst);
1862 break;
1863 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1864 STy->getName().equals("opencl.image2d_wo_t") ||
1865 STy->getName().equals("opencl.image3d_ro_t") ||
1866 STy->getName().equals("opencl.image3d_wo_t")) {
1867 //
1868 // Generate OpTypeImage
1869 //
1870 // Ops[0] = Sampled Type ID
1871 // Ops[1] = Dim ID
1872 // Ops[2] = Depth (Literal Number)
1873 // Ops[3] = Arrayed (Literal Number)
1874 // Ops[4] = MS (Literal Number)
1875 // Ops[5] = Sampled (Literal Number)
1876 // Ops[6] = Image Format ID
1877 //
1878 SPIRVOperandList Ops;
1879
1880 // TODO: Changed Sampled Type according to situations.
1881 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001882 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001883
1884 spv::Dim DimID = spv::Dim2D;
1885 if (STy->getName().equals("opencl.image3d_ro_t") ||
1886 STy->getName().equals("opencl.image3d_wo_t")) {
1887 DimID = spv::Dim3D;
1888 }
David Neto257c3892018-04-11 13:19:45 -04001889 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001890
1891 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001892 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001893
1894 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001895 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001896
1897 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001898 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001899
1900 // TODO: Set up Sampled.
1901 //
1902 // From Spec
1903 //
1904 // 0 indicates this is only known at run time, not at compile time
1905 // 1 indicates will be used with sampler
1906 // 2 indicates will be used without a sampler (a storage image)
1907 uint32_t Sampled = 1;
1908 if (STy->getName().equals("opencl.image2d_wo_t") ||
1909 STy->getName().equals("opencl.image3d_wo_t")) {
1910 Sampled = 2;
1911 }
David Neto257c3892018-04-11 13:19:45 -04001912 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001913
1914 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001915 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001916
David Neto87846742018-04-11 17:36:22 -04001917 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001918 SPIRVInstList.push_back(Inst);
1919 break;
1920 }
1921 }
1922
1923 //
1924 // Generate OpTypeStruct
1925 //
1926 // Ops[0] ... Ops[n] = Member IDs
1927 SPIRVOperandList Ops;
1928
1929 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001930 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001931 }
1932
David Neto22f144c2017-06-12 14:26:21 -04001933 uint32_t STyID = nextID;
1934
alan-bakerb6b09dc2018-11-08 16:59:28 -05001935 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001936 SPIRVInstList.push_back(Inst);
1937
1938 // Generate OpMemberDecorate.
1939 auto DecoInsertPoint =
1940 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1941 [](SPIRVInstruction *Inst) -> bool {
1942 return Inst->getOpcode() != spv::OpDecorate &&
1943 Inst->getOpcode() != spv::OpMemberDecorate &&
1944 Inst->getOpcode() != spv::OpExtInstImport;
1945 });
1946
David Netoc463b372017-08-10 15:32:21 -04001947 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001948 // Search for the correct offsets if this type was remapped.
1949 std::vector<uint32_t> *offsets = nullptr;
1950 auto iter = RemappedUBOTypeOffsets.find(STy);
1951 if (iter != RemappedUBOTypeOffsets.end()) {
1952 offsets = &iter->second;
1953 }
David Netoc463b372017-08-10 15:32:21 -04001954
David Neto862b7d82018-06-14 18:48:37 -04001955 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001956 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1957 MemberIdx++) {
1958 // Ops[0] = Structure Type ID
1959 // Ops[1] = Member Index(Literal Number)
1960 // Ops[2] = Decoration (Offset)
1961 // Ops[3] = Byte Offset (Literal Number)
1962 Ops.clear();
1963
David Neto257c3892018-04-11 13:19:45 -04001964 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001965
alan-bakerb6b09dc2018-11-08 16:59:28 -05001966 auto ByteOffset =
1967 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001968 if (offsets) {
1969 ByteOffset = (*offsets)[MemberIdx];
1970 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001971 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001972 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001973 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001974
David Neto87846742018-04-11 17:36:22 -04001975 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001976 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001977 }
1978
1979 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001980 if (StructTypesNeedingBlock.idFor(STy)) {
1981 Ops.clear();
1982 // Use Block decorations with StorageBuffer storage class.
1983 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001984
David Neto862b7d82018-06-14 18:48:37 -04001985 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1986 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001987 }
1988 break;
1989 }
1990 case Type::IntegerTyID: {
1991 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1992
1993 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001994 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001995 SPIRVInstList.push_back(Inst);
1996 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001997 if (!clspv::Option::Int8Support()) {
1998 // i8 is added to TypeMap as i32.
1999 // No matter what LLVM type is requested first, always alias the
2000 // second one's SPIR-V type to be the same as the one we generated
2001 // first.
2002 unsigned aliasToWidth = 0;
2003 if (BitWidth == 8) {
2004 aliasToWidth = 32;
2005 BitWidth = 32;
2006 } else if (BitWidth == 32) {
2007 aliasToWidth = 8;
2008 }
2009 if (aliasToWidth) {
2010 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2011 auto where = TypeMap.find(otherType);
2012 if (where == TypeMap.end()) {
2013 // Go ahead and make it, but also map the other type to it.
2014 TypeMap[otherType] = nextID;
2015 } else {
2016 // Alias this SPIR-V type the existing type.
2017 TypeMap[Ty] = where->second;
2018 break;
2019 }
David Neto391aeb12017-08-26 15:51:58 -04002020 }
David Neto22f144c2017-06-12 14:26:21 -04002021 }
2022
David Neto257c3892018-04-11 13:19:45 -04002023 SPIRVOperandList Ops;
2024 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002025
2026 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002027 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002028 }
2029 break;
2030 }
2031 case Type::HalfTyID:
2032 case Type::FloatTyID:
2033 case Type::DoubleTyID: {
2034 SPIRVOperand *WidthOp = new SPIRVOperand(
2035 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2036
2037 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002038 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002039 break;
2040 }
2041 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002042 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002043 const uint64_t Length = ArrTy->getArrayNumElements();
2044 if (Length == 0) {
2045 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002046
David Neto862b7d82018-06-14 18:48:37 -04002047 // Only generate the type once.
2048 // TODO(dneto): Can it ever be generated more than once?
2049 // Doesn't LLVM type uniqueness guarantee we'll only see this
2050 // once?
2051 Type *EleTy = ArrTy->getArrayElementType();
2052 if (OpRuntimeTyMap.count(EleTy) == 0) {
2053 uint32_t OpTypeRuntimeArrayID = nextID;
2054 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002055
David Neto862b7d82018-06-14 18:48:37 -04002056 //
2057 // Generate OpTypeRuntimeArray.
2058 //
David Neto22f144c2017-06-12 14:26:21 -04002059
David Neto862b7d82018-06-14 18:48:37 -04002060 // OpTypeRuntimeArray
2061 // Ops[0] = Element Type ID
2062 SPIRVOperandList Ops;
2063 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002064
David Neto862b7d82018-06-14 18:48:37 -04002065 SPIRVInstList.push_back(
2066 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002067
David Neto862b7d82018-06-14 18:48:37 -04002068 if (Hack_generate_runtime_array_stride_early) {
2069 // Generate OpDecorate.
2070 auto DecoInsertPoint = std::find_if(
2071 SPIRVInstList.begin(), SPIRVInstList.end(),
2072 [](SPIRVInstruction *Inst) -> bool {
2073 return Inst->getOpcode() != spv::OpDecorate &&
2074 Inst->getOpcode() != spv::OpMemberDecorate &&
2075 Inst->getOpcode() != spv::OpExtInstImport;
2076 });
David Neto22f144c2017-06-12 14:26:21 -04002077
David Neto862b7d82018-06-14 18:48:37 -04002078 // Ops[0] = Target ID
2079 // Ops[1] = Decoration (ArrayStride)
2080 // Ops[2] = Stride Number(Literal Number)
2081 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002082
David Neto862b7d82018-06-14 18:48:37 -04002083 Ops << MkId(OpTypeRuntimeArrayID)
2084 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002085 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002086
David Neto862b7d82018-06-14 18:48:37 -04002087 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2088 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2089 }
2090 }
David Neto22f144c2017-06-12 14:26:21 -04002091
David Neto862b7d82018-06-14 18:48:37 -04002092 } else {
David Neto22f144c2017-06-12 14:26:21 -04002093
David Neto862b7d82018-06-14 18:48:37 -04002094 //
2095 // Generate OpConstant and OpTypeArray.
2096 //
2097
2098 //
2099 // Generate OpConstant for array length.
2100 //
2101 // Ops[0] = Result Type ID
2102 // Ops[1] .. Ops[n] = Values LiteralNumber
2103 SPIRVOperandList Ops;
2104
2105 Type *LengthTy = Type::getInt32Ty(Context);
2106 uint32_t ResTyID = lookupType(LengthTy);
2107 Ops << MkId(ResTyID);
2108
2109 assert(Length < UINT32_MAX);
2110 Ops << MkNum(static_cast<uint32_t>(Length));
2111
2112 // Add constant for length to constant list.
2113 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2114 AllocatedVMap[CstLength] = nextID;
2115 VMap[CstLength] = nextID;
2116 uint32_t LengthID = nextID;
2117
2118 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2119 SPIRVInstList.push_back(CstInst);
2120
2121 // Remember to generate ArrayStride later
2122 getTypesNeedingArrayStride().insert(Ty);
2123
2124 //
2125 // Generate OpTypeArray.
2126 //
2127 // Ops[0] = Element Type ID
2128 // Ops[1] = Array Length Constant ID
2129 Ops.clear();
2130
2131 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2132 Ops << MkId(EleTyID) << MkId(LengthID);
2133
2134 // Update TypeMap with nextID.
2135 TypeMap[Ty] = nextID;
2136
2137 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2138 SPIRVInstList.push_back(ArrayInst);
2139 }
David Neto22f144c2017-06-12 14:26:21 -04002140 break;
2141 }
2142 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002143 // <4 x i8> is changed to i32 if i8 is not generally supported.
2144 if (!clspv::Option::Int8Support() &&
2145 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002146 if (Ty->getVectorNumElements() == 4) {
2147 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2148 break;
2149 } else {
2150 Ty->print(errs());
2151 llvm_unreachable("Support above i8 vector type");
2152 }
2153 }
2154
2155 // Ops[0] = Component Type ID
2156 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002157 SPIRVOperandList Ops;
2158 Ops << MkId(lookupType(Ty->getVectorElementType()))
2159 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002160
alan-bakerb6b09dc2018-11-08 16:59:28 -05002161 SPIRVInstruction *inst =
2162 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002163 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002164 break;
2165 }
2166 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002167 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002168 SPIRVInstList.push_back(Inst);
2169 break;
2170 }
2171 case Type::FunctionTyID: {
2172 // Generate SPIRV instruction for function type.
2173 FunctionType *FTy = cast<FunctionType>(Ty);
2174
2175 // Ops[0] = Return Type ID
2176 // Ops[1] ... Ops[n] = Parameter Type IDs
2177 SPIRVOperandList Ops;
2178
2179 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002180 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002181
2182 // Find SPIRV instructions for parameter types
2183 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2184 // Find SPIRV instruction for parameter type.
2185 auto ParamTy = FTy->getParamType(k);
2186 if (ParamTy->isPointerTy()) {
2187 auto PointeeTy = ParamTy->getPointerElementType();
2188 if (PointeeTy->isStructTy() &&
2189 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2190 ParamTy = PointeeTy;
2191 }
2192 }
2193
David Netoc6f3ab22018-04-06 18:02:31 -04002194 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002195 }
2196
David Neto87846742018-04-11 17:36:22 -04002197 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002198 SPIRVInstList.push_back(Inst);
2199 break;
2200 }
2201 }
2202 }
2203
2204 // Generate OpTypeSampledImage.
2205 TypeMapType &OpImageTypeMap = getImageTypeMap();
2206 for (auto &ImageType : OpImageTypeMap) {
2207 //
2208 // Generate OpTypeSampledImage.
2209 //
2210 // Ops[0] = Image Type ID
2211 //
2212 SPIRVOperandList Ops;
2213
2214 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002215 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002216
2217 // Update OpImageTypeMap.
2218 ImageType.second = nextID;
2219
David Neto87846742018-04-11 17:36:22 -04002220 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002221 SPIRVInstList.push_back(Inst);
2222 }
David Netoc6f3ab22018-04-06 18:02:31 -04002223
2224 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002225 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2226 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002227 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002228
2229 // Generate the spec constant.
2230 SPIRVOperandList Ops;
2231 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002232 SPIRVInstList.push_back(
2233 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002234
2235 // Generate the array type.
2236 Ops.clear();
2237 // The element type must have been created.
2238 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2239 assert(elem_ty_id);
2240 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2241
2242 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002243 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002244
2245 Ops.clear();
2246 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002247 SPIRVInstList.push_back(new SPIRVInstruction(
2248 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002249 }
David Neto22f144c2017-06-12 14:26:21 -04002250}
2251
2252void SPIRVProducerPass::GenerateSPIRVConstants() {
2253 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2254 ValueMapType &VMap = getValueMap();
2255 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2256 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002257 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002258
2259 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002260 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002261 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002262
2263 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002264 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002265 continue;
2266 }
2267
David Netofb9a7972017-08-25 17:08:24 -04002268 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002269 VMap[Cst] = nextID;
2270
2271 //
2272 // Generate OpConstant.
2273 //
2274
2275 // Ops[0] = Result Type ID
2276 // Ops[1] .. Ops[n] = Values LiteralNumber
2277 SPIRVOperandList Ops;
2278
David Neto257c3892018-04-11 13:19:45 -04002279 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002280
2281 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002282 spv::Op Opcode = spv::OpNop;
2283
2284 if (isa<UndefValue>(Cst)) {
2285 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002286 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002287 if (hack_undef && IsTypeNullable(Cst->getType())) {
2288 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002289 }
David Neto22f144c2017-06-12 14:26:21 -04002290 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2291 unsigned BitWidth = CI->getBitWidth();
2292 if (BitWidth == 1) {
2293 // If the bitwidth of constant is 1, generate OpConstantTrue or
2294 // OpConstantFalse.
2295 if (CI->getZExtValue()) {
2296 // Ops[0] = Result Type ID
2297 Opcode = spv::OpConstantTrue;
2298 } else {
2299 // Ops[0] = Result Type ID
2300 Opcode = spv::OpConstantFalse;
2301 }
David Neto22f144c2017-06-12 14:26:21 -04002302 } else {
2303 auto V = CI->getZExtValue();
2304 LiteralNum.push_back(V & 0xFFFFFFFF);
2305
2306 if (BitWidth > 32) {
2307 LiteralNum.push_back(V >> 32);
2308 }
2309
2310 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002311
David Neto257c3892018-04-11 13:19:45 -04002312 Ops << MkInteger(LiteralNum);
2313
2314 if (BitWidth == 32 && V == 0) {
2315 constant_i32_zero_id_ = nextID;
2316 }
David Neto22f144c2017-06-12 14:26:21 -04002317 }
2318 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2319 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2320 Type *CFPTy = CFP->getType();
2321 if (CFPTy->isFloatTy()) {
2322 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002323 } else if (CFPTy->isDoubleTy()) {
2324 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2325 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002326 } else {
2327 CFPTy->print(errs());
2328 llvm_unreachable("Implement this ConstantFP Type");
2329 }
2330
2331 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002332
David Neto257c3892018-04-11 13:19:45 -04002333 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002334 } else if (isa<ConstantDataSequential>(Cst) &&
2335 cast<ConstantDataSequential>(Cst)->isString()) {
2336 Cst->print(errs());
2337 llvm_unreachable("Implement this Constant");
2338
2339 } else if (const ConstantDataSequential *CDS =
2340 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002341 // Let's convert <4 x i8> constant to int constant specially.
2342 // This case occurs when all the values are specified as constant
2343 // ints.
2344 Type *CstTy = Cst->getType();
2345 if (is4xi8vec(CstTy)) {
2346 LLVMContext &Context = CstTy->getContext();
2347
2348 //
2349 // Generate OpConstant with OpTypeInt 32 0.
2350 //
Neil Henning39672102017-09-29 14:33:13 +01002351 uint32_t IntValue = 0;
2352 for (unsigned k = 0; k < 4; k++) {
2353 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002354 IntValue = (IntValue << 8) | (Val & 0xffu);
2355 }
2356
2357 Type *i32 = Type::getInt32Ty(Context);
2358 Constant *CstInt = ConstantInt::get(i32, IntValue);
2359 // If this constant is already registered on VMap, use it.
2360 if (VMap.count(CstInt)) {
2361 uint32_t CstID = VMap[CstInt];
2362 VMap[Cst] = CstID;
2363 continue;
2364 }
2365
David Neto257c3892018-04-11 13:19:45 -04002366 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002367
David Neto87846742018-04-11 17:36:22 -04002368 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002369 SPIRVInstList.push_back(CstInst);
2370
2371 continue;
2372 }
2373
2374 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002375 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2376 Constant *EleCst = CDS->getElementAsConstant(k);
2377 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002378 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002379 }
2380
2381 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002382 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2383 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002384 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002385 Type *CstTy = Cst->getType();
2386 if (is4xi8vec(CstTy)) {
2387 LLVMContext &Context = CstTy->getContext();
2388
2389 //
2390 // Generate OpConstant with OpTypeInt 32 0.
2391 //
Neil Henning39672102017-09-29 14:33:13 +01002392 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002393 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2394 I != E; ++I) {
2395 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002396 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002397 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2398 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002399 }
David Neto49351ac2017-08-26 17:32:20 -04002400 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002401 }
2402
David Neto49351ac2017-08-26 17:32:20 -04002403 Type *i32 = Type::getInt32Ty(Context);
2404 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002405 // If this constant is already registered on VMap, use it.
2406 if (VMap.count(CstInt)) {
2407 uint32_t CstID = VMap[CstInt];
2408 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002409 continue;
David Neto22f144c2017-06-12 14:26:21 -04002410 }
2411
David Neto257c3892018-04-11 13:19:45 -04002412 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002413
David Neto87846742018-04-11 17:36:22 -04002414 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002415 SPIRVInstList.push_back(CstInst);
2416
David Neto19a1bad2017-08-25 15:01:41 -04002417 continue;
David Neto22f144c2017-06-12 14:26:21 -04002418 }
2419
2420 // We use a constant composite in SPIR-V for our constant aggregate in
2421 // LLVM.
2422 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002423
2424 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2425 // Look up the ID of the element of this aggregate (which we will
2426 // previously have created a constant for).
2427 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2428
2429 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002430 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002431 }
2432 } else if (Cst->isNullValue()) {
2433 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002434 } else {
2435 Cst->print(errs());
2436 llvm_unreachable("Unsupported Constant???");
2437 }
2438
alan-baker5b86ed72019-02-15 08:26:50 -05002439 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2440 // Null pointer requires variable pointers.
2441 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2442 }
2443
David Neto87846742018-04-11 17:36:22 -04002444 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002445 SPIRVInstList.push_back(CstInst);
2446 }
2447}
2448
2449void SPIRVProducerPass::GenerateSamplers(Module &M) {
2450 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002451
alan-bakerb6b09dc2018-11-08 16:59:28 -05002452 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002453 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002454 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002455 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2456 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002457
David Neto862b7d82018-06-14 18:48:37 -04002458 // We might have samplers in the sampler map that are not used
2459 // in the translation unit. We need to allocate variables
2460 // for them and bindings too.
2461 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002462
Kévin Petitdf71de32019-04-09 14:09:50 +01002463 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002464 if (!var_fn)
2465 return;
David Neto862b7d82018-06-14 18:48:37 -04002466 for (auto user : var_fn->users()) {
2467 // Populate SamplerLiteralToDescriptorSetMap and
2468 // SamplerLiteralToBindingMap.
2469 //
2470 // Look for calls like
2471 // call %opencl.sampler_t addrspace(2)*
2472 // @clspv.sampler.var.literal(
2473 // i32 descriptor,
2474 // i32 binding,
2475 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002476 if (auto *call = dyn_cast<CallInst>(user)) {
2477 const size_t index_into_sampler_map = static_cast<size_t>(
2478 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002479 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002480 errs() << "Out of bounds index to sampler map: "
2481 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002482 llvm_unreachable("bad sampler init: out of bounds");
2483 }
2484
2485 auto sampler_value = sampler_map[index_into_sampler_map].first;
2486 const auto descriptor_set = static_cast<unsigned>(
2487 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2488 const auto binding = static_cast<unsigned>(
2489 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2490
2491 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2492 SamplerLiteralToBindingMap[sampler_value] = binding;
2493 used_bindings.insert(binding);
2494 }
2495 }
2496
2497 unsigned index = 0;
2498 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002499 // Generate OpVariable.
2500 //
2501 // GIDOps[0] : Result Type ID
2502 // GIDOps[1] : Storage Class
2503 SPIRVOperandList Ops;
2504
David Neto257c3892018-04-11 13:19:45 -04002505 Ops << MkId(lookupType(SamplerTy))
2506 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002507
David Neto862b7d82018-06-14 18:48:37 -04002508 auto sampler_var_id = nextID++;
2509 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002510 SPIRVInstList.push_back(Inst);
2511
David Neto862b7d82018-06-14 18:48:37 -04002512 SamplerMapIndexToIDMap[index] = sampler_var_id;
2513 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002514
2515 // Find Insert Point for OpDecorate.
2516 auto DecoInsertPoint =
2517 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2518 [](SPIRVInstruction *Inst) -> bool {
2519 return Inst->getOpcode() != spv::OpDecorate &&
2520 Inst->getOpcode() != spv::OpMemberDecorate &&
2521 Inst->getOpcode() != spv::OpExtInstImport;
2522 });
2523
2524 // Ops[0] = Target ID
2525 // Ops[1] = Decoration (DescriptorSet)
2526 // Ops[2] = LiteralNumber according to Decoration
2527 Ops.clear();
2528
David Neto862b7d82018-06-14 18:48:37 -04002529 unsigned descriptor_set;
2530 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002531 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2532 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002533 // This sampler is not actually used. Find the next one.
2534 for (binding = 0; used_bindings.count(binding); binding++)
2535 ;
2536 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2537 used_bindings.insert(binding);
2538 } else {
2539 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2540 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2541 }
2542
2543 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2544 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002545
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002546 version0::DescriptorMapEntry::SamplerData sampler_data = {
2547 SamplerLiteral.first};
2548 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set,
2549 binding);
David Neto22f144c2017-06-12 14:26:21 -04002550
David Neto87846742018-04-11 17:36:22 -04002551 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002552 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2553
2554 // Ops[0] = Target ID
2555 // Ops[1] = Decoration (Binding)
2556 // Ops[2] = LiteralNumber according to Decoration
2557 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002558 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2559 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002560
David Neto87846742018-04-11 17:36:22 -04002561 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002562 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002563
2564 index++;
David Neto22f144c2017-06-12 14:26:21 -04002565 }
David Neto862b7d82018-06-14 18:48:37 -04002566}
David Neto22f144c2017-06-12 14:26:21 -04002567
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002568void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002569 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2570 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002571
David Neto862b7d82018-06-14 18:48:37 -04002572 // Generate variables. Make one for each of resource var info object.
2573 for (auto *info : ModuleOrderedResourceVars) {
2574 Type *type = info->var_fn->getReturnType();
2575 // Remap the address space for opaque types.
2576 switch (info->arg_kind) {
2577 case clspv::ArgKind::Sampler:
2578 case clspv::ArgKind::ReadOnlyImage:
2579 case clspv::ArgKind::WriteOnlyImage:
2580 type = PointerType::get(type->getPointerElementType(),
2581 clspv::AddressSpace::UniformConstant);
2582 break;
2583 default:
2584 break;
2585 }
David Neto22f144c2017-06-12 14:26:21 -04002586
David Neto862b7d82018-06-14 18:48:37 -04002587 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002588
David Neto862b7d82018-06-14 18:48:37 -04002589 const auto type_id = lookupType(type);
2590 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2591 SPIRVOperandList Ops;
2592 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002593
David Neto862b7d82018-06-14 18:48:37 -04002594 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2595 SPIRVInstList.push_back(Inst);
2596
2597 // Map calls to the variable-builtin-function.
2598 for (auto &U : info->var_fn->uses()) {
2599 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2600 const auto set = unsigned(
2601 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2602 const auto binding = unsigned(
2603 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2604 if (set == info->descriptor_set && binding == info->binding) {
2605 switch (info->arg_kind) {
2606 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002607 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002608 case clspv::ArgKind::Pod:
2609 // The call maps to the variable directly.
2610 VMap[call] = info->var_id;
2611 break;
2612 case clspv::ArgKind::Sampler:
2613 case clspv::ArgKind::ReadOnlyImage:
2614 case clspv::ArgKind::WriteOnlyImage:
2615 // The call maps to a load we generate later.
2616 ResourceVarDeferredLoadCalls[call] = info->var_id;
2617 break;
2618 default:
2619 llvm_unreachable("Unhandled arg kind");
2620 }
2621 }
David Neto22f144c2017-06-12 14:26:21 -04002622 }
David Neto862b7d82018-06-14 18:48:37 -04002623 }
2624 }
David Neto22f144c2017-06-12 14:26:21 -04002625
David Neto862b7d82018-06-14 18:48:37 -04002626 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002627
David Neto862b7d82018-06-14 18:48:37 -04002628 // Find Insert Point for OpDecorate.
2629 auto DecoInsertPoint =
2630 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2631 [](SPIRVInstruction *Inst) -> bool {
2632 return Inst->getOpcode() != spv::OpDecorate &&
2633 Inst->getOpcode() != spv::OpMemberDecorate &&
2634 Inst->getOpcode() != spv::OpExtInstImport;
2635 });
2636
2637 SPIRVOperandList Ops;
2638 for (auto *info : ModuleOrderedResourceVars) {
2639 // Decorate with DescriptorSet and Binding.
2640 Ops.clear();
2641 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2642 << MkNum(info->descriptor_set);
2643 SPIRVInstList.insert(DecoInsertPoint,
2644 new SPIRVInstruction(spv::OpDecorate, Ops));
2645
2646 Ops.clear();
2647 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2648 << MkNum(info->binding);
2649 SPIRVInstList.insert(DecoInsertPoint,
2650 new SPIRVInstruction(spv::OpDecorate, Ops));
2651
alan-bakere9308012019-03-15 10:25:13 -04002652 if (info->coherent) {
2653 // Decorate with Coherent if required for the variable.
2654 Ops.clear();
2655 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2656 SPIRVInstList.insert(DecoInsertPoint,
2657 new SPIRVInstruction(spv::OpDecorate, Ops));
2658 }
2659
David Neto862b7d82018-06-14 18:48:37 -04002660 // Generate NonWritable and NonReadable
2661 switch (info->arg_kind) {
2662 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002663 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002664 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2665 clspv::AddressSpace::Constant) {
2666 Ops.clear();
2667 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2668 SPIRVInstList.insert(DecoInsertPoint,
2669 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002670 }
David Neto862b7d82018-06-14 18:48:37 -04002671 break;
David Neto862b7d82018-06-14 18:48:37 -04002672 case clspv::ArgKind::WriteOnlyImage:
2673 Ops.clear();
2674 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2675 SPIRVInstList.insert(DecoInsertPoint,
2676 new SPIRVInstruction(spv::OpDecorate, Ops));
2677 break;
2678 default:
2679 break;
David Neto22f144c2017-06-12 14:26:21 -04002680 }
2681 }
2682}
2683
2684void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002685 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002686 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2687 ValueMapType &VMap = getValueMap();
2688 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002689 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002690
2691 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2692 Type *Ty = GV.getType();
2693 PointerType *PTy = cast<PointerType>(Ty);
2694
2695 uint32_t InitializerID = 0;
2696
2697 // Workgroup size is handled differently (it goes into a constant)
2698 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2699 std::vector<bool> HasMDVec;
2700 uint32_t PrevXDimCst = 0xFFFFFFFF;
2701 uint32_t PrevYDimCst = 0xFFFFFFFF;
2702 uint32_t PrevZDimCst = 0xFFFFFFFF;
2703 for (Function &Func : *GV.getParent()) {
2704 if (Func.isDeclaration()) {
2705 continue;
2706 }
2707
2708 // We only need to check kernels.
2709 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2710 continue;
2711 }
2712
2713 if (const MDNode *MD =
2714 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2715 uint32_t CurXDimCst = static_cast<uint32_t>(
2716 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2717 uint32_t CurYDimCst = static_cast<uint32_t>(
2718 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2719 uint32_t CurZDimCst = static_cast<uint32_t>(
2720 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2721
2722 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2723 PrevZDimCst == 0xFFFFFFFF) {
2724 PrevXDimCst = CurXDimCst;
2725 PrevYDimCst = CurYDimCst;
2726 PrevZDimCst = CurZDimCst;
2727 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2728 CurZDimCst != PrevZDimCst) {
2729 llvm_unreachable(
2730 "reqd_work_group_size must be the same across all kernels");
2731 } else {
2732 continue;
2733 }
2734
2735 //
2736 // Generate OpConstantComposite.
2737 //
2738 // Ops[0] : Result Type ID
2739 // Ops[1] : Constant size for x dimension.
2740 // Ops[2] : Constant size for y dimension.
2741 // Ops[3] : Constant size for z dimension.
2742 SPIRVOperandList Ops;
2743
2744 uint32_t XDimCstID =
2745 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2746 uint32_t YDimCstID =
2747 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2748 uint32_t ZDimCstID =
2749 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2750
2751 InitializerID = nextID;
2752
David Neto257c3892018-04-11 13:19:45 -04002753 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2754 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002755
David Neto87846742018-04-11 17:36:22 -04002756 auto *Inst =
2757 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002758 SPIRVInstList.push_back(Inst);
2759
2760 HasMDVec.push_back(true);
2761 } else {
2762 HasMDVec.push_back(false);
2763 }
2764 }
2765
2766 // Check all kernels have same definitions for work_group_size.
2767 bool HasMD = false;
2768 if (!HasMDVec.empty()) {
2769 HasMD = HasMDVec[0];
2770 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2771 if (HasMD != HasMDVec[i]) {
2772 llvm_unreachable(
2773 "Kernels should have consistent work group size definition");
2774 }
2775 }
2776 }
2777
2778 // If all kernels do not have metadata for reqd_work_group_size, generate
2779 // OpSpecConstants for x/y/z dimension.
2780 if (!HasMD) {
2781 //
2782 // Generate OpSpecConstants for x/y/z dimension.
2783 //
2784 // Ops[0] : Result Type ID
2785 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2786 uint32_t XDimCstID = 0;
2787 uint32_t YDimCstID = 0;
2788 uint32_t ZDimCstID = 0;
2789
David Neto22f144c2017-06-12 14:26:21 -04002790 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002791 uint32_t result_type_id =
2792 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002793
David Neto257c3892018-04-11 13:19:45 -04002794 // X Dimension
2795 Ops << MkId(result_type_id) << MkNum(1);
2796 XDimCstID = nextID++;
2797 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002798 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002799
2800 // Y Dimension
2801 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002802 Ops << MkId(result_type_id) << MkNum(1);
2803 YDimCstID = nextID++;
2804 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002805 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002806
2807 // Z Dimension
2808 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002809 Ops << MkId(result_type_id) << MkNum(1);
2810 ZDimCstID = nextID++;
2811 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002812 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002813
David Neto257c3892018-04-11 13:19:45 -04002814 BuiltinDimVec.push_back(XDimCstID);
2815 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002816 BuiltinDimVec.push_back(ZDimCstID);
2817
David Neto22f144c2017-06-12 14:26:21 -04002818 //
2819 // Generate OpSpecConstantComposite.
2820 //
2821 // Ops[0] : Result Type ID
2822 // Ops[1] : Constant size for x dimension.
2823 // Ops[2] : Constant size for y dimension.
2824 // Ops[3] : Constant size for z dimension.
2825 InitializerID = nextID;
2826
2827 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002828 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2829 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002830
David Neto87846742018-04-11 17:36:22 -04002831 auto *Inst =
2832 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002833 SPIRVInstList.push_back(Inst);
2834 }
2835 }
2836
David Neto22f144c2017-06-12 14:26:21 -04002837 VMap[&GV] = nextID;
2838
2839 //
2840 // Generate OpVariable.
2841 //
2842 // GIDOps[0] : Result Type ID
2843 // GIDOps[1] : Storage Class
2844 SPIRVOperandList Ops;
2845
David Neto85082642018-03-24 06:55:20 -07002846 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002847 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002848
David Neto85082642018-03-24 06:55:20 -07002849 if (GV.hasInitializer()) {
2850 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002851 }
2852
David Neto85082642018-03-24 06:55:20 -07002853 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002854 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002855 clspv::Option::ModuleConstantsInStorageBuffer();
2856
2857 if (0 != InitializerID) {
2858 if (!module_scope_constant_external_init) {
2859 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002860 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002861 }
2862 }
2863 const uint32_t var_id = nextID++;
2864
David Neto87846742018-04-11 17:36:22 -04002865 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002866 SPIRVInstList.push_back(Inst);
2867
2868 // If we have a builtin.
2869 if (spv::BuiltInMax != BuiltinType) {
2870 // Find Insert Point for OpDecorate.
2871 auto DecoInsertPoint =
2872 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2873 [](SPIRVInstruction *Inst) -> bool {
2874 return Inst->getOpcode() != spv::OpDecorate &&
2875 Inst->getOpcode() != spv::OpMemberDecorate &&
2876 Inst->getOpcode() != spv::OpExtInstImport;
2877 });
2878 //
2879 // Generate OpDecorate.
2880 //
2881 // DOps[0] = Target ID
2882 // DOps[1] = Decoration (Builtin)
2883 // DOps[2] = BuiltIn ID
2884 uint32_t ResultID;
2885
2886 // WorkgroupSize is different, we decorate the constant composite that has
2887 // its value, rather than the variable that we use to access the value.
2888 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2889 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002890 // Save both the value and variable IDs for later.
2891 WorkgroupSizeValueID = InitializerID;
2892 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002893 } else {
2894 ResultID = VMap[&GV];
2895 }
2896
2897 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002898 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2899 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002900
David Neto87846742018-04-11 17:36:22 -04002901 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002902 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002903 } else if (module_scope_constant_external_init) {
2904 // This module scope constant is initialized from a storage buffer with data
2905 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002906 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002907
David Neto862b7d82018-06-14 18:48:37 -04002908 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002909 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2910 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002911 std::string hexbytes;
2912 llvm::raw_string_ostream str(hexbytes);
2913 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002914 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2915 str.str()};
2916 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2917 0);
David Neto85082642018-03-24 06:55:20 -07002918
2919 // Find Insert Point for OpDecorate.
2920 auto DecoInsertPoint =
2921 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2922 [](SPIRVInstruction *Inst) -> bool {
2923 return Inst->getOpcode() != spv::OpDecorate &&
2924 Inst->getOpcode() != spv::OpMemberDecorate &&
2925 Inst->getOpcode() != spv::OpExtInstImport;
2926 });
2927
David Neto257c3892018-04-11 13:19:45 -04002928 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002929 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002930 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2931 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002932 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002933
2934 // OpDecorate %var DescriptorSet <descriptor_set>
2935 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002936 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2937 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002938 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002939 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002940 }
2941}
2942
David Netoc6f3ab22018-04-06 18:02:31 -04002943void SPIRVProducerPass::GenerateWorkgroupVars() {
2944 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002945 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2946 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002947 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002948
2949 // Generate OpVariable.
2950 //
2951 // GIDOps[0] : Result Type ID
2952 // GIDOps[1] : Storage Class
2953 SPIRVOperandList Ops;
2954 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2955
2956 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002957 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002958 }
2959}
2960
David Neto862b7d82018-06-14 18:48:37 -04002961void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2962 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002963 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2964 return;
2965 }
David Neto862b7d82018-06-14 18:48:37 -04002966 // Gather the list of resources that are used by this function's arguments.
2967 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2968
alan-bakerf5e5f692018-11-27 08:33:24 -05002969 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2970 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002971 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002972 std::string kind =
2973 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2974 ? "pod_ubo"
2975 : argKind;
2976 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002977 };
2978
2979 auto *fty = F.getType()->getPointerElementType();
2980 auto *func_ty = dyn_cast<FunctionType>(fty);
2981
alan-baker038e9242019-04-19 22:14:41 -04002982 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04002983 // If an argument maps to a resource variable, then get descriptor set and
2984 // binding from the resoure variable. Other info comes from the metadata.
2985 const auto *arg_map = F.getMetadata("kernel_arg_map");
2986 if (arg_map) {
2987 for (const auto &arg : arg_map->operands()) {
2988 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002989 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002990 const auto name =
2991 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2992 const auto old_index =
2993 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2994 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002995 const size_t new_index = static_cast<size_t>(
2996 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002997 const auto offset =
2998 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002999 const auto arg_size =
3000 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003001 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003002 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003003 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003004 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003005
3006 uint32_t descriptor_set = 0;
3007 uint32_t binding = 0;
3008 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003009 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05003010 static_cast<uint32_t>(spec_id),
3011 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003012 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003013 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003014 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3015 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3016 DL));
David Neto862b7d82018-06-14 18:48:37 -04003017 } else {
3018 auto *info = resource_var_at_index[new_index];
3019 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003020 descriptor_set = info->descriptor_set;
3021 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003022 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003023 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
3024 binding);
David Neto862b7d82018-06-14 18:48:37 -04003025 }
3026 } else {
3027 // There is no argument map.
3028 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003029 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003030
3031 SmallVector<Argument *, 4> arguments;
3032 for (auto &arg : F.args()) {
3033 arguments.push_back(&arg);
3034 }
3035
3036 unsigned arg_index = 0;
3037 for (auto *info : resource_var_at_index) {
3038 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003039 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003040 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003041 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003042 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003043 }
3044
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003045 // Local pointer arguments are unused in this case. Offset is always
3046 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05003047 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3048 F.getName(), arg->getName(),
3049 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3050 0, 0,
3051 0, arg_size};
3052 descriptorMapEntries->emplace_back(std::move(kernel_data),
3053 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003054 }
3055 arg_index++;
3056 }
3057 // Generate mappings for pointer-to-local arguments.
3058 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3059 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003060 auto where = LocalArgSpecIds.find(arg);
3061 if (where != LocalArgSpecIds.end()) {
3062 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003063 // Pod arguments members are unused in this case.
3064 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3065 F.getName(),
3066 arg->getName(),
3067 arg_index,
3068 ArgKind::Local,
3069 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003070 static_cast<uint32_t>(
3071 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05003072 0,
3073 0};
3074 // Pointer-to-local arguments do not utilize descriptor set and binding.
3075 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003076 }
3077 }
3078 }
3079}
3080
David Neto22f144c2017-06-12 14:26:21 -04003081void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3082 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3083 ValueMapType &VMap = getValueMap();
3084 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003085 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3086 auto &GlobalConstArgSet = getGlobalConstArgSet();
3087
3088 FunctionType *FTy = F.getFunctionType();
3089
3090 //
David Neto22f144c2017-06-12 14:26:21 -04003091 // Generate OPFunction.
3092 //
3093
3094 // FOps[0] : Result Type ID
3095 // FOps[1] : Function Control
3096 // FOps[2] : Function Type ID
3097 SPIRVOperandList FOps;
3098
3099 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003100 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003101
3102 // Check function attributes for SPIRV Function Control.
3103 uint32_t FuncControl = spv::FunctionControlMaskNone;
3104 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3105 FuncControl |= spv::FunctionControlInlineMask;
3106 }
3107 if (F.hasFnAttribute(Attribute::NoInline)) {
3108 FuncControl |= spv::FunctionControlDontInlineMask;
3109 }
3110 // TODO: Check llvm attribute for Function Control Pure.
3111 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3112 FuncControl |= spv::FunctionControlPureMask;
3113 }
3114 // TODO: Check llvm attribute for Function Control Const.
3115 if (F.hasFnAttribute(Attribute::ReadNone)) {
3116 FuncControl |= spv::FunctionControlConstMask;
3117 }
3118
David Neto257c3892018-04-11 13:19:45 -04003119 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003120
3121 uint32_t FTyID;
3122 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3123 SmallVector<Type *, 4> NewFuncParamTys;
3124 FunctionType *NewFTy =
3125 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3126 FTyID = lookupType(NewFTy);
3127 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003128 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003129 if (GlobalConstFuncTyMap.count(FTy)) {
3130 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3131 } else {
3132 FTyID = lookupType(FTy);
3133 }
3134 }
3135
David Neto257c3892018-04-11 13:19:45 -04003136 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003137
3138 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3139 EntryPoints.push_back(std::make_pair(&F, nextID));
3140 }
3141
3142 VMap[&F] = nextID;
3143
David Neto482550a2018-03-24 05:21:07 -07003144 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003145 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3146 }
David Neto22f144c2017-06-12 14:26:21 -04003147 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003148 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003149 SPIRVInstList.push_back(FuncInst);
3150
3151 //
3152 // Generate OpFunctionParameter for Normal function.
3153 //
3154
3155 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003156
3157 // Find Insert Point for OpDecorate.
3158 auto DecoInsertPoint =
3159 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3160 [](SPIRVInstruction *Inst) -> bool {
3161 return Inst->getOpcode() != spv::OpDecorate &&
3162 Inst->getOpcode() != spv::OpMemberDecorate &&
3163 Inst->getOpcode() != spv::OpExtInstImport;
3164 });
3165
David Neto22f144c2017-06-12 14:26:21 -04003166 // Iterate Argument for name instead of param type from function type.
3167 unsigned ArgIdx = 0;
3168 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003169 uint32_t param_id = nextID++;
3170 VMap[&Arg] = param_id;
3171
3172 if (CalledWithCoherentResource(Arg)) {
3173 // If the arg is passed a coherent resource ever, then decorate this
3174 // parameter with Coherent too.
3175 SPIRVOperandList decoration_ops;
3176 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003177 SPIRVInstList.insert(
3178 DecoInsertPoint,
3179 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003180 }
David Neto22f144c2017-06-12 14:26:21 -04003181
3182 // ParamOps[0] : Result Type ID
3183 SPIRVOperandList ParamOps;
3184
3185 // Find SPIRV instruction for parameter type.
3186 uint32_t ParamTyID = lookupType(Arg.getType());
3187 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3188 if (GlobalConstFuncTyMap.count(FTy)) {
3189 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3190 Type *EleTy = PTy->getPointerElementType();
3191 Type *ArgTy =
3192 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3193 ParamTyID = lookupType(ArgTy);
3194 GlobalConstArgSet.insert(&Arg);
3195 }
3196 }
3197 }
David Neto257c3892018-04-11 13:19:45 -04003198 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003199
3200 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003201 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003202 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003203 SPIRVInstList.push_back(ParamInst);
3204
3205 ArgIdx++;
3206 }
3207 }
3208}
3209
alan-bakerb6b09dc2018-11-08 16:59:28 -05003210void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003211 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3212 EntryPointVecType &EntryPoints = getEntryPointVec();
3213 ValueMapType &VMap = getValueMap();
3214 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3215 uint32_t &ExtInstImportID = getOpExtInstImportID();
3216 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3217
3218 // Set up insert point.
3219 auto InsertPoint = SPIRVInstList.begin();
3220
3221 //
3222 // Generate OpCapability
3223 //
3224 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3225
3226 // Ops[0] = Capability
3227 SPIRVOperandList Ops;
3228
David Neto87846742018-04-11 17:36:22 -04003229 auto *CapInst =
3230 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003231 SPIRVInstList.insert(InsertPoint, CapInst);
3232
3233 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003234 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3235 // Generate OpCapability for i8 type.
3236 SPIRVInstList.insert(InsertPoint,
3237 new SPIRVInstruction(spv::OpCapability,
3238 {MkNum(spv::CapabilityInt8)}));
3239 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003240 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003241 SPIRVInstList.insert(InsertPoint,
3242 new SPIRVInstruction(spv::OpCapability,
3243 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003244 } else if (Ty->isIntegerTy(64)) {
3245 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003246 SPIRVInstList.insert(InsertPoint,
3247 new SPIRVInstruction(spv::OpCapability,
3248 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003249 } else if (Ty->isHalfTy()) {
3250 // Generate OpCapability for half type.
3251 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003252 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3253 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003254 } else if (Ty->isDoubleTy()) {
3255 // Generate OpCapability for double type.
3256 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003257 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3258 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003259 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3260 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003261 if (STy->getName().equals("opencl.image2d_wo_t") ||
3262 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003263 // Generate OpCapability for write only image type.
3264 SPIRVInstList.insert(
3265 InsertPoint,
3266 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003267 spv::OpCapability,
3268 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003269 }
3270 }
3271 }
3272 }
3273
David Neto5c22a252018-03-15 16:07:41 -04003274 { // OpCapability ImageQuery
3275 bool hasImageQuery = false;
3276 for (const char *imageQuery : {
3277 "_Z15get_image_width14ocl_image2d_ro",
3278 "_Z15get_image_width14ocl_image2d_wo",
3279 "_Z16get_image_height14ocl_image2d_ro",
3280 "_Z16get_image_height14ocl_image2d_wo",
3281 }) {
3282 if (module.getFunction(imageQuery)) {
3283 hasImageQuery = true;
3284 break;
3285 }
3286 }
3287 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003288 auto *ImageQueryCapInst = new SPIRVInstruction(
3289 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003290 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3291 }
3292 }
3293
David Neto22f144c2017-06-12 14:26:21 -04003294 if (hasVariablePointers()) {
3295 //
David Neto22f144c2017-06-12 14:26:21 -04003296 // Generate OpCapability.
3297 //
3298 // Ops[0] = Capability
3299 //
3300 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003301 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003302
David Neto87846742018-04-11 17:36:22 -04003303 SPIRVInstList.insert(InsertPoint,
3304 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003305 } else if (hasVariablePointersStorageBuffer()) {
3306 //
3307 // Generate OpCapability.
3308 //
3309 // Ops[0] = Capability
3310 //
3311 Ops.clear();
3312 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003313
alan-baker5b86ed72019-02-15 08:26:50 -05003314 SPIRVInstList.insert(InsertPoint,
3315 new SPIRVInstruction(spv::OpCapability, Ops));
3316 }
3317
3318 // Always add the storage buffer extension
3319 {
David Neto22f144c2017-06-12 14:26:21 -04003320 //
3321 // Generate OpExtension.
3322 //
3323 // Ops[0] = Name (Literal String)
3324 //
alan-baker5b86ed72019-02-15 08:26:50 -05003325 auto *ExtensionInst = new SPIRVInstruction(
3326 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3327 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3328 }
David Neto22f144c2017-06-12 14:26:21 -04003329
alan-baker5b86ed72019-02-15 08:26:50 -05003330 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3331 //
3332 // Generate OpExtension.
3333 //
3334 // Ops[0] = Name (Literal String)
3335 //
3336 auto *ExtensionInst = new SPIRVInstruction(
3337 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3338 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003339 }
3340
3341 if (ExtInstImportID) {
3342 ++InsertPoint;
3343 }
3344
3345 //
3346 // Generate OpMemoryModel
3347 //
3348 // Memory model for Vulkan will always be GLSL450.
3349
3350 // Ops[0] = Addressing Model
3351 // Ops[1] = Memory Model
3352 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003353 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003354
David Neto87846742018-04-11 17:36:22 -04003355 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003356 SPIRVInstList.insert(InsertPoint, MemModelInst);
3357
3358 //
3359 // Generate OpEntryPoint
3360 //
3361 for (auto EntryPoint : EntryPoints) {
3362 // Ops[0] = Execution Model
3363 // Ops[1] = EntryPoint ID
3364 // Ops[2] = Name (Literal String)
3365 // ...
3366 //
3367 // TODO: Do we need to consider Interface ID for forward references???
3368 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003369 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003370 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3371 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003372
David Neto22f144c2017-06-12 14:26:21 -04003373 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003374 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003375 }
3376
David Neto87846742018-04-11 17:36:22 -04003377 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003378 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3379 }
3380
3381 for (auto EntryPoint : EntryPoints) {
3382 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3383 ->getMetadata("reqd_work_group_size")) {
3384
3385 if (!BuiltinDimVec.empty()) {
3386 llvm_unreachable(
3387 "Kernels should have consistent work group size definition");
3388 }
3389
3390 //
3391 // Generate OpExecutionMode
3392 //
3393
3394 // Ops[0] = Entry Point ID
3395 // Ops[1] = Execution Mode
3396 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3397 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003398 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003399
3400 uint32_t XDim = static_cast<uint32_t>(
3401 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3402 uint32_t YDim = static_cast<uint32_t>(
3403 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3404 uint32_t ZDim = static_cast<uint32_t>(
3405 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3406
David Neto257c3892018-04-11 13:19:45 -04003407 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003408
David Neto87846742018-04-11 17:36:22 -04003409 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003410 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3411 }
3412 }
3413
3414 //
3415 // Generate OpSource.
3416 //
3417 // Ops[0] = SourceLanguage ID
3418 // Ops[1] = Version (LiteralNum)
3419 //
3420 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003421 if (clspv::Option::CPlusPlus()) {
3422 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3423 } else {
3424 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3425 }
David Neto22f144c2017-06-12 14:26:21 -04003426
David Neto87846742018-04-11 17:36:22 -04003427 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003428 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3429
3430 if (!BuiltinDimVec.empty()) {
3431 //
3432 // Generate OpDecorates for x/y/z dimension.
3433 //
3434 // Ops[0] = Target ID
3435 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003436 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003437
3438 // X Dimension
3439 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003440 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003441 SPIRVInstList.insert(InsertPoint,
3442 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003443
3444 // Y Dimension
3445 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003446 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003447 SPIRVInstList.insert(InsertPoint,
3448 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003449
3450 // Z Dimension
3451 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003452 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003453 SPIRVInstList.insert(InsertPoint,
3454 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003455 }
3456}
3457
David Netob6e2e062018-04-25 10:32:06 -04003458void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3459 // Work around a driver bug. Initializers on Private variables might not
3460 // work. So the start of the kernel should store the initializer value to the
3461 // variables. Yes, *every* entry point pays this cost if *any* entry point
3462 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3463 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003464 // TODO(dneto): Remove this at some point once fixed drivers are widely
3465 // available.
David Netob6e2e062018-04-25 10:32:06 -04003466 if (WorkgroupSizeVarID) {
3467 assert(WorkgroupSizeValueID);
3468
3469 SPIRVOperandList Ops;
3470 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3471
3472 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3473 getSPIRVInstList().push_back(Inst);
3474 }
3475}
3476
David Neto22f144c2017-06-12 14:26:21 -04003477void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3478 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3479 ValueMapType &VMap = getValueMap();
3480
David Netob6e2e062018-04-25 10:32:06 -04003481 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003482
3483 for (BasicBlock &BB : F) {
3484 // Register BasicBlock to ValueMap.
3485 VMap[&BB] = nextID;
3486
3487 //
3488 // Generate OpLabel for Basic Block.
3489 //
3490 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003491 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003492 SPIRVInstList.push_back(Inst);
3493
David Neto6dcd4712017-06-23 11:06:47 -04003494 // OpVariable instructions must come first.
3495 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003496 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3497 // Allocating a pointer requires variable pointers.
3498 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003499 setVariablePointersCapabilities(
3500 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003501 }
David Neto6dcd4712017-06-23 11:06:47 -04003502 GenerateInstruction(I);
3503 }
3504 }
3505
David Neto22f144c2017-06-12 14:26:21 -04003506 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003507 if (clspv::Option::HackInitializers()) {
3508 GenerateEntryPointInitialStores();
3509 }
David Neto22f144c2017-06-12 14:26:21 -04003510 }
3511
3512 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003513 if (!isa<AllocaInst>(I)) {
3514 GenerateInstruction(I);
3515 }
David Neto22f144c2017-06-12 14:26:21 -04003516 }
3517 }
3518}
3519
3520spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3521 const std::map<CmpInst::Predicate, spv::Op> Map = {
3522 {CmpInst::ICMP_EQ, spv::OpIEqual},
3523 {CmpInst::ICMP_NE, spv::OpINotEqual},
3524 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3525 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3526 {CmpInst::ICMP_ULT, spv::OpULessThan},
3527 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3528 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3529 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3530 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3531 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3532 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3533 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3534 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3535 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3536 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3537 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3538 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3539 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3540 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3541 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3542 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3543 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3544
3545 assert(0 != Map.count(I->getPredicate()));
3546
3547 return Map.at(I->getPredicate());
3548}
3549
3550spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3551 const std::map<unsigned, spv::Op> Map{
3552 {Instruction::Trunc, spv::OpUConvert},
3553 {Instruction::ZExt, spv::OpUConvert},
3554 {Instruction::SExt, spv::OpSConvert},
3555 {Instruction::FPToUI, spv::OpConvertFToU},
3556 {Instruction::FPToSI, spv::OpConvertFToS},
3557 {Instruction::UIToFP, spv::OpConvertUToF},
3558 {Instruction::SIToFP, spv::OpConvertSToF},
3559 {Instruction::FPTrunc, spv::OpFConvert},
3560 {Instruction::FPExt, spv::OpFConvert},
3561 {Instruction::BitCast, spv::OpBitcast}};
3562
3563 assert(0 != Map.count(I.getOpcode()));
3564
3565 return Map.at(I.getOpcode());
3566}
3567
3568spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003569 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003570 switch (I.getOpcode()) {
3571 default:
3572 break;
3573 case Instruction::Or:
3574 return spv::OpLogicalOr;
3575 case Instruction::And:
3576 return spv::OpLogicalAnd;
3577 case Instruction::Xor:
3578 return spv::OpLogicalNotEqual;
3579 }
3580 }
3581
alan-bakerb6b09dc2018-11-08 16:59:28 -05003582 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003583 {Instruction::Add, spv::OpIAdd},
3584 {Instruction::FAdd, spv::OpFAdd},
3585 {Instruction::Sub, spv::OpISub},
3586 {Instruction::FSub, spv::OpFSub},
3587 {Instruction::Mul, spv::OpIMul},
3588 {Instruction::FMul, spv::OpFMul},
3589 {Instruction::UDiv, spv::OpUDiv},
3590 {Instruction::SDiv, spv::OpSDiv},
3591 {Instruction::FDiv, spv::OpFDiv},
3592 {Instruction::URem, spv::OpUMod},
3593 {Instruction::SRem, spv::OpSRem},
3594 {Instruction::FRem, spv::OpFRem},
3595 {Instruction::Or, spv::OpBitwiseOr},
3596 {Instruction::Xor, spv::OpBitwiseXor},
3597 {Instruction::And, spv::OpBitwiseAnd},
3598 {Instruction::Shl, spv::OpShiftLeftLogical},
3599 {Instruction::LShr, spv::OpShiftRightLogical},
3600 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3601
3602 assert(0 != Map.count(I.getOpcode()));
3603
3604 return Map.at(I.getOpcode());
3605}
3606
3607void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3608 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3609 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003610 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3611 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3612
3613 // Register Instruction to ValueMap.
3614 if (0 == VMap[&I]) {
3615 VMap[&I] = nextID;
3616 }
3617
3618 switch (I.getOpcode()) {
3619 default: {
3620 if (Instruction::isCast(I.getOpcode())) {
3621 //
3622 // Generate SPIRV instructions for cast operators.
3623 //
3624
David Netod2de94a2017-08-28 17:27:47 -04003625 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003626 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003627 auto toI8 = Ty == Type::getInt8Ty(Context);
3628 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003629 // Handle zext, sext and uitofp with i1 type specially.
3630 if ((I.getOpcode() == Instruction::ZExt ||
3631 I.getOpcode() == Instruction::SExt ||
3632 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003633 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003634 //
3635 // Generate OpSelect.
3636 //
3637
3638 // Ops[0] = Result Type ID
3639 // Ops[1] = Condition ID
3640 // Ops[2] = True Constant ID
3641 // Ops[3] = False Constant ID
3642 SPIRVOperandList Ops;
3643
David Neto257c3892018-04-11 13:19:45 -04003644 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003645
David Neto22f144c2017-06-12 14:26:21 -04003646 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003647 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003648
3649 uint32_t TrueID = 0;
3650 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003651 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003652 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003653 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003654 } else {
3655 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3656 }
David Neto257c3892018-04-11 13:19:45 -04003657 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003658
3659 uint32_t FalseID = 0;
3660 if (I.getOpcode() == Instruction::ZExt) {
3661 FalseID = VMap[Constant::getNullValue(I.getType())];
3662 } else if (I.getOpcode() == Instruction::SExt) {
3663 FalseID = VMap[Constant::getNullValue(I.getType())];
3664 } else {
3665 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3666 }
David Neto257c3892018-04-11 13:19:45 -04003667 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003668
David Neto87846742018-04-11 17:36:22 -04003669 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003670 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003671 } else if (!clspv::Option::Int8Support() &&
3672 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003673 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3674 // 8 bits.
3675 // Before:
3676 // %result = trunc i32 %a to i8
3677 // After
3678 // %result = OpBitwiseAnd %uint %a %uint_255
3679
3680 SPIRVOperandList Ops;
3681
David Neto257c3892018-04-11 13:19:45 -04003682 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003683
3684 Type *UintTy = Type::getInt32Ty(Context);
3685 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003686 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003687
David Neto87846742018-04-11 17:36:22 -04003688 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003689 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003690 } else {
3691 // Ops[0] = Result Type ID
3692 // Ops[1] = Source Value ID
3693 SPIRVOperandList Ops;
3694
David Neto257c3892018-04-11 13:19:45 -04003695 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003696
David Neto87846742018-04-11 17:36:22 -04003697 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003698 SPIRVInstList.push_back(Inst);
3699 }
3700 } else if (isa<BinaryOperator>(I)) {
3701 //
3702 // Generate SPIRV instructions for binary operators.
3703 //
3704
3705 // Handle xor with i1 type specially.
3706 if (I.getOpcode() == Instruction::Xor &&
3707 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003708 ((isa<ConstantInt>(I.getOperand(0)) &&
3709 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3710 (isa<ConstantInt>(I.getOperand(1)) &&
3711 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003712 //
3713 // Generate OpLogicalNot.
3714 //
3715 // Ops[0] = Result Type ID
3716 // Ops[1] = Operand
3717 SPIRVOperandList Ops;
3718
David Neto257c3892018-04-11 13:19:45 -04003719 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003720
3721 Value *CondV = I.getOperand(0);
3722 if (isa<Constant>(I.getOperand(0))) {
3723 CondV = I.getOperand(1);
3724 }
David Neto257c3892018-04-11 13:19:45 -04003725 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003726
David Neto87846742018-04-11 17:36:22 -04003727 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003728 SPIRVInstList.push_back(Inst);
3729 } else {
3730 // Ops[0] = Result Type ID
3731 // Ops[1] = Operand 0
3732 // Ops[2] = Operand 1
3733 SPIRVOperandList Ops;
3734
David Neto257c3892018-04-11 13:19:45 -04003735 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3736 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003737
David Neto87846742018-04-11 17:36:22 -04003738 auto *Inst =
3739 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003740 SPIRVInstList.push_back(Inst);
3741 }
3742 } else {
3743 I.print(errs());
3744 llvm_unreachable("Unsupported instruction???");
3745 }
3746 break;
3747 }
3748 case Instruction::GetElementPtr: {
3749 auto &GlobalConstArgSet = getGlobalConstArgSet();
3750
3751 //
3752 // Generate OpAccessChain.
3753 //
3754 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3755
3756 //
3757 // Generate OpAccessChain.
3758 //
3759
3760 // Ops[0] = Result Type ID
3761 // Ops[1] = Base ID
3762 // Ops[2] ... Ops[n] = Indexes ID
3763 SPIRVOperandList Ops;
3764
alan-bakerb6b09dc2018-11-08 16:59:28 -05003765 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003766 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3767 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3768 // Use pointer type with private address space for global constant.
3769 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003770 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003771 }
David Neto257c3892018-04-11 13:19:45 -04003772
3773 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003774
David Neto862b7d82018-06-14 18:48:37 -04003775 // Generate the base pointer.
3776 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003777
David Neto862b7d82018-06-14 18:48:37 -04003778 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003779
3780 //
3781 // Follows below rules for gep.
3782 //
David Neto862b7d82018-06-14 18:48:37 -04003783 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3784 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003785 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3786 // first index.
3787 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3788 // use gep's first index.
3789 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3790 // gep's first index.
3791 //
3792 spv::Op Opcode = spv::OpAccessChain;
3793 unsigned offset = 0;
3794 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003795 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003796 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003797 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003798 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003799 }
David Neto862b7d82018-06-14 18:48:37 -04003800 } else {
David Neto22f144c2017-06-12 14:26:21 -04003801 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003802 }
3803
3804 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003805 // Do we need to generate ArrayStride? Check against the GEP result type
3806 // rather than the pointer type of the base because when indexing into
3807 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3808 // for something else in the SPIR-V.
3809 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003810 auto address_space = ResultType->getAddressSpace();
3811 setVariablePointersCapabilities(address_space);
3812 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003813 case spv::StorageClassStorageBuffer:
3814 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003815 // Save the need to generate an ArrayStride decoration. But defer
3816 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003817 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003818 break;
3819 default:
3820 break;
David Neto1a1a0582017-07-07 12:01:44 -04003821 }
David Neto22f144c2017-06-12 14:26:21 -04003822 }
3823
3824 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003825 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003826 }
3827
David Neto87846742018-04-11 17:36:22 -04003828 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003829 SPIRVInstList.push_back(Inst);
3830 break;
3831 }
3832 case Instruction::ExtractValue: {
3833 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3834 // Ops[0] = Result Type ID
3835 // Ops[1] = Composite ID
3836 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3837 SPIRVOperandList Ops;
3838
David Neto257c3892018-04-11 13:19:45 -04003839 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003840
3841 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003842 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003843
3844 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003846 }
3847
David Neto87846742018-04-11 17:36:22 -04003848 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003849 SPIRVInstList.push_back(Inst);
3850 break;
3851 }
3852 case Instruction::InsertValue: {
3853 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3854 // Ops[0] = Result Type ID
3855 // Ops[1] = Object ID
3856 // Ops[2] = Composite ID
3857 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3858 SPIRVOperandList Ops;
3859
3860 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003861 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003862
3863 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003864 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003865
3866 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003867 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003868
3869 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003870 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003871 }
3872
David Neto87846742018-04-11 17:36:22 -04003873 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003874 SPIRVInstList.push_back(Inst);
3875 break;
3876 }
3877 case Instruction::Select: {
3878 //
3879 // Generate OpSelect.
3880 //
3881
3882 // Ops[0] = Result Type ID
3883 // Ops[1] = Condition ID
3884 // Ops[2] = True Constant ID
3885 // Ops[3] = False Constant ID
3886 SPIRVOperandList Ops;
3887
3888 // Find SPIRV instruction for parameter type.
3889 auto Ty = I.getType();
3890 if (Ty->isPointerTy()) {
3891 auto PointeeTy = Ty->getPointerElementType();
3892 if (PointeeTy->isStructTy() &&
3893 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3894 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003895 } else {
3896 // Selecting between pointers requires variable pointers.
3897 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3898 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3899 setVariablePointers(true);
3900 }
David Neto22f144c2017-06-12 14:26:21 -04003901 }
3902 }
3903
David Neto257c3892018-04-11 13:19:45 -04003904 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3905 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003906
David Neto87846742018-04-11 17:36:22 -04003907 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003908 SPIRVInstList.push_back(Inst);
3909 break;
3910 }
3911 case Instruction::ExtractElement: {
3912 // Handle <4 x i8> type manually.
3913 Type *CompositeTy = I.getOperand(0)->getType();
3914 if (is4xi8vec(CompositeTy)) {
3915 //
3916 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3917 // <4 x i8>.
3918 //
3919
3920 //
3921 // Generate OpShiftRightLogical
3922 //
3923 // Ops[0] = Result Type ID
3924 // Ops[1] = Operand 0
3925 // Ops[2] = Operand 1
3926 //
3927 SPIRVOperandList Ops;
3928
David Neto257c3892018-04-11 13:19:45 -04003929 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003930
3931 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003932 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003933
3934 uint32_t Op1ID = 0;
3935 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3936 // Handle constant index.
3937 uint64_t Idx = CI->getZExtValue();
3938 Value *ShiftAmount =
3939 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3940 Op1ID = VMap[ShiftAmount];
3941 } else {
3942 // Handle variable index.
3943 SPIRVOperandList TmpOps;
3944
David Neto257c3892018-04-11 13:19:45 -04003945 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3946 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003947
3948 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003949 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003950
3951 Op1ID = nextID;
3952
David Neto87846742018-04-11 17:36:22 -04003953 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003954 SPIRVInstList.push_back(TmpInst);
3955 }
David Neto257c3892018-04-11 13:19:45 -04003956 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003957
3958 uint32_t ShiftID = nextID;
3959
David Neto87846742018-04-11 17:36:22 -04003960 auto *Inst =
3961 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003962 SPIRVInstList.push_back(Inst);
3963
3964 //
3965 // Generate OpBitwiseAnd
3966 //
3967 // Ops[0] = Result Type ID
3968 // Ops[1] = Operand 0
3969 // Ops[2] = Operand 1
3970 //
3971 Ops.clear();
3972
David Neto257c3892018-04-11 13:19:45 -04003973 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003974
3975 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003976 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003977
David Neto9b2d6252017-09-06 15:47:37 -04003978 // Reset mapping for this value to the result of the bitwise and.
3979 VMap[&I] = nextID;
3980
David Neto87846742018-04-11 17:36:22 -04003981 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003982 SPIRVInstList.push_back(Inst);
3983 break;
3984 }
3985
3986 // Ops[0] = Result Type ID
3987 // Ops[1] = Composite ID
3988 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3989 SPIRVOperandList Ops;
3990
David Neto257c3892018-04-11 13:19:45 -04003991 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003992
3993 spv::Op Opcode = spv::OpCompositeExtract;
3994 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003995 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003996 } else {
David Neto257c3892018-04-11 13:19:45 -04003997 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003998 Opcode = spv::OpVectorExtractDynamic;
3999 }
4000
David Neto87846742018-04-11 17:36:22 -04004001 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004002 SPIRVInstList.push_back(Inst);
4003 break;
4004 }
4005 case Instruction::InsertElement: {
4006 // Handle <4 x i8> type manually.
4007 Type *CompositeTy = I.getOperand(0)->getType();
4008 if (is4xi8vec(CompositeTy)) {
4009 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4010 uint32_t CstFFID = VMap[CstFF];
4011
4012 uint32_t ShiftAmountID = 0;
4013 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4014 // Handle constant index.
4015 uint64_t Idx = CI->getZExtValue();
4016 Value *ShiftAmount =
4017 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4018 ShiftAmountID = VMap[ShiftAmount];
4019 } else {
4020 // Handle variable index.
4021 SPIRVOperandList TmpOps;
4022
David Neto257c3892018-04-11 13:19:45 -04004023 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4024 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004025
4026 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004027 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004028
4029 ShiftAmountID = nextID;
4030
David Neto87846742018-04-11 17:36:22 -04004031 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004032 SPIRVInstList.push_back(TmpInst);
4033 }
4034
4035 //
4036 // Generate mask operations.
4037 //
4038
4039 // ShiftLeft mask according to index of insertelement.
4040 SPIRVOperandList Ops;
4041
David Neto257c3892018-04-11 13:19:45 -04004042 const uint32_t ResTyID = lookupType(CompositeTy);
4043 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004044
4045 uint32_t MaskID = nextID;
4046
David Neto87846742018-04-11 17:36:22 -04004047 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004048 SPIRVInstList.push_back(Inst);
4049
4050 // Inverse mask.
4051 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004052 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004053
4054 uint32_t InvMaskID = nextID;
4055
David Neto87846742018-04-11 17:36:22 -04004056 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 SPIRVInstList.push_back(Inst);
4058
4059 // Apply mask.
4060 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004061 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004062
4063 uint32_t OrgValID = nextID;
4064
David Neto87846742018-04-11 17:36:22 -04004065 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004066 SPIRVInstList.push_back(Inst);
4067
4068 // Create correct value according to index of insertelement.
4069 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004070 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4071 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004072
4073 uint32_t InsertValID = nextID;
4074
David Neto87846742018-04-11 17:36:22 -04004075 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004076 SPIRVInstList.push_back(Inst);
4077
4078 // Insert value to original value.
4079 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004080 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004081
David Netoa394f392017-08-26 20:45:29 -04004082 VMap[&I] = nextID;
4083
David Neto87846742018-04-11 17:36:22 -04004084 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004085 SPIRVInstList.push_back(Inst);
4086
4087 break;
4088 }
4089
David Neto22f144c2017-06-12 14:26:21 -04004090 SPIRVOperandList Ops;
4091
James Priced26efea2018-06-09 23:28:32 +01004092 // Ops[0] = Result Type ID
4093 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004094
4095 spv::Op Opcode = spv::OpCompositeInsert;
4096 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004097 const auto value = CI->getZExtValue();
4098 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004099 // Ops[1] = Object ID
4100 // Ops[2] = Composite ID
4101 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004102 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004103 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004104 } else {
James Priced26efea2018-06-09 23:28:32 +01004105 // Ops[1] = Composite ID
4106 // Ops[2] = Object ID
4107 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004108 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004109 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004110 Opcode = spv::OpVectorInsertDynamic;
4111 }
4112
David Neto87846742018-04-11 17:36:22 -04004113 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004114 SPIRVInstList.push_back(Inst);
4115 break;
4116 }
4117 case Instruction::ShuffleVector: {
4118 // Ops[0] = Result Type ID
4119 // Ops[1] = Vector 1 ID
4120 // Ops[2] = Vector 2 ID
4121 // Ops[3] ... Ops[n] = Components (Literal Number)
4122 SPIRVOperandList Ops;
4123
David Neto257c3892018-04-11 13:19:45 -04004124 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4125 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004126
4127 uint64_t NumElements = 0;
4128 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4129 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4130
4131 if (Cst->isNullValue()) {
4132 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004133 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004134 }
4135 } else if (const ConstantDataSequential *CDS =
4136 dyn_cast<ConstantDataSequential>(Cst)) {
4137 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4138 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004139 const auto value = CDS->getElementAsInteger(i);
4140 assert(value <= UINT32_MAX);
4141 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004142 }
4143 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4144 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4145 auto Op = CV->getOperand(i);
4146
4147 uint32_t literal = 0;
4148
4149 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4150 literal = static_cast<uint32_t>(CI->getZExtValue());
4151 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4152 literal = 0xFFFFFFFFu;
4153 } else {
4154 Op->print(errs());
4155 llvm_unreachable("Unsupported element in ConstantVector!");
4156 }
4157
David Neto257c3892018-04-11 13:19:45 -04004158 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004159 }
4160 } else {
4161 Cst->print(errs());
4162 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4163 }
4164 }
4165
David Neto87846742018-04-11 17:36:22 -04004166 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004167 SPIRVInstList.push_back(Inst);
4168 break;
4169 }
4170 case Instruction::ICmp:
4171 case Instruction::FCmp: {
4172 CmpInst *CmpI = cast<CmpInst>(&I);
4173
David Netod4ca2e62017-07-06 18:47:35 -04004174 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004175 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004176 if (isa<PointerType>(ArgTy)) {
4177 CmpI->print(errs());
4178 std::string name = I.getParent()->getParent()->getName();
4179 errs()
4180 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4181 << "in function " << name << "\n";
4182 llvm_unreachable("Pointer equality check is invalid");
4183 break;
4184 }
4185
David Neto257c3892018-04-11 13:19:45 -04004186 // Ops[0] = Result Type ID
4187 // Ops[1] = Operand 1 ID
4188 // Ops[2] = Operand 2 ID
4189 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004190
David Neto257c3892018-04-11 13:19:45 -04004191 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4192 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004193
4194 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004195 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004196 SPIRVInstList.push_back(Inst);
4197 break;
4198 }
4199 case Instruction::Br: {
4200 // Branch instrucion is deferred because it needs label's ID. Record slot's
4201 // location on SPIRVInstructionList.
4202 DeferredInsts.push_back(
4203 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4204 break;
4205 }
4206 case Instruction::Switch: {
4207 I.print(errs());
4208 llvm_unreachable("Unsupported instruction???");
4209 break;
4210 }
4211 case Instruction::IndirectBr: {
4212 I.print(errs());
4213 llvm_unreachable("Unsupported instruction???");
4214 break;
4215 }
4216 case Instruction::PHI: {
4217 // Branch instrucion is deferred because it needs label's ID. Record slot's
4218 // location on SPIRVInstructionList.
4219 DeferredInsts.push_back(
4220 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4221 break;
4222 }
4223 case Instruction::Alloca: {
4224 //
4225 // Generate OpVariable.
4226 //
4227 // Ops[0] : Result Type ID
4228 // Ops[1] : Storage Class
4229 SPIRVOperandList Ops;
4230
David Neto257c3892018-04-11 13:19:45 -04004231 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004232
David Neto87846742018-04-11 17:36:22 -04004233 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004234 SPIRVInstList.push_back(Inst);
4235 break;
4236 }
4237 case Instruction::Load: {
4238 LoadInst *LD = cast<LoadInst>(&I);
4239 //
4240 // Generate OpLoad.
4241 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004242
alan-baker5b86ed72019-02-15 08:26:50 -05004243 if (LD->getType()->isPointerTy()) {
4244 // Loading a pointer requires variable pointers.
4245 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4246 }
David Neto22f144c2017-06-12 14:26:21 -04004247
David Neto0a2f98d2017-09-15 19:38:40 -04004248 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004249 uint32_t PointerID = VMap[LD->getPointerOperand()];
4250
4251 // This is a hack to work around what looks like a driver bug.
4252 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004253 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4254 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004255 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004256 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004257 // Generate a bitwise-and of the original value with itself.
4258 // We should have been able to get away with just an OpCopyObject,
4259 // but we need something more complex to get past certain driver bugs.
4260 // This is ridiculous, but necessary.
4261 // TODO(dneto): Revisit this once drivers fix their bugs.
4262
4263 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004264 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4265 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004266
David Neto87846742018-04-11 17:36:22 -04004267 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004268 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004269 break;
4270 }
4271
4272 // This is the normal path. Generate a load.
4273
David Neto22f144c2017-06-12 14:26:21 -04004274 // Ops[0] = Result Type ID
4275 // Ops[1] = Pointer ID
4276 // Ops[2] ... Ops[n] = Optional Memory Access
4277 //
4278 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004279
David Neto22f144c2017-06-12 14:26:21 -04004280 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004281 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004282
David Neto87846742018-04-11 17:36:22 -04004283 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004284 SPIRVInstList.push_back(Inst);
4285 break;
4286 }
4287 case Instruction::Store: {
4288 StoreInst *ST = cast<StoreInst>(&I);
4289 //
4290 // Generate OpStore.
4291 //
4292
alan-baker5b86ed72019-02-15 08:26:50 -05004293 if (ST->getValueOperand()->getType()->isPointerTy()) {
4294 // Storing a pointer requires variable pointers.
4295 setVariablePointersCapabilities(
4296 ST->getValueOperand()->getType()->getPointerAddressSpace());
4297 }
4298
David Neto22f144c2017-06-12 14:26:21 -04004299 // Ops[0] = Pointer ID
4300 // Ops[1] = Object ID
4301 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4302 //
4303 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004304 SPIRVOperandList Ops;
4305 Ops << MkId(VMap[ST->getPointerOperand()])
4306 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004307
David Neto87846742018-04-11 17:36:22 -04004308 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004309 SPIRVInstList.push_back(Inst);
4310 break;
4311 }
4312 case Instruction::AtomicCmpXchg: {
4313 I.print(errs());
4314 llvm_unreachable("Unsupported instruction???");
4315 break;
4316 }
4317 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004318 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4319
4320 spv::Op opcode;
4321
4322 switch (AtomicRMW->getOperation()) {
4323 default:
4324 I.print(errs());
4325 llvm_unreachable("Unsupported instruction???");
4326 case llvm::AtomicRMWInst::Add:
4327 opcode = spv::OpAtomicIAdd;
4328 break;
4329 case llvm::AtomicRMWInst::Sub:
4330 opcode = spv::OpAtomicISub;
4331 break;
4332 case llvm::AtomicRMWInst::Xchg:
4333 opcode = spv::OpAtomicExchange;
4334 break;
4335 case llvm::AtomicRMWInst::Min:
4336 opcode = spv::OpAtomicSMin;
4337 break;
4338 case llvm::AtomicRMWInst::Max:
4339 opcode = spv::OpAtomicSMax;
4340 break;
4341 case llvm::AtomicRMWInst::UMin:
4342 opcode = spv::OpAtomicUMin;
4343 break;
4344 case llvm::AtomicRMWInst::UMax:
4345 opcode = spv::OpAtomicUMax;
4346 break;
4347 case llvm::AtomicRMWInst::And:
4348 opcode = spv::OpAtomicAnd;
4349 break;
4350 case llvm::AtomicRMWInst::Or:
4351 opcode = spv::OpAtomicOr;
4352 break;
4353 case llvm::AtomicRMWInst::Xor:
4354 opcode = spv::OpAtomicXor;
4355 break;
4356 }
4357
4358 //
4359 // Generate OpAtomic*.
4360 //
4361 SPIRVOperandList Ops;
4362
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(lookupType(I.getType()))
4364 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004365
4366 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004367 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004368 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004369
4370 const auto ConstantMemorySemantics = ConstantInt::get(
4371 IntTy, spv::MemorySemanticsUniformMemoryMask |
4372 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004373 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004374
David Neto257c3892018-04-11 13:19:45 -04004375 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004376
4377 VMap[&I] = nextID;
4378
David Neto87846742018-04-11 17:36:22 -04004379 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004380 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004381 break;
4382 }
4383 case Instruction::Fence: {
4384 I.print(errs());
4385 llvm_unreachable("Unsupported instruction???");
4386 break;
4387 }
4388 case Instruction::Call: {
4389 CallInst *Call = dyn_cast<CallInst>(&I);
4390 Function *Callee = Call->getCalledFunction();
4391
Alan Baker202c8c72018-08-13 13:47:44 -04004392 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004393 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4394 // Generate an OpLoad
4395 SPIRVOperandList Ops;
4396 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004397
David Neto862b7d82018-06-14 18:48:37 -04004398 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4399 << MkId(ResourceVarDeferredLoadCalls[Call]);
4400
4401 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4402 SPIRVInstList.push_back(Inst);
4403 VMap[Call] = load_id;
4404 break;
4405
4406 } else {
4407 // This maps to an OpVariable we've already generated.
4408 // No code is generated for the call.
4409 }
4410 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004411 } else if (Callee->getName().startswith(
4412 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004413 // Don't codegen an instruction here, but instead map this call directly
4414 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004415 int spec_id = static_cast<int>(
4416 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004417 const auto &info = LocalSpecIdInfoMap[spec_id];
4418 VMap[Call] = info.variable_id;
4419 break;
David Neto862b7d82018-06-14 18:48:37 -04004420 }
4421
4422 // Sampler initializers become a load of the corresponding sampler.
4423
Kévin Petitdf71de32019-04-09 14:09:50 +01004424 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004425 // Map this to a load from the variable.
4426 const auto index_into_sampler_map =
4427 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4428
4429 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004430 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004431 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004432
David Neto257c3892018-04-11 13:19:45 -04004433 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004434 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4435 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004436
David Neto862b7d82018-06-14 18:48:37 -04004437 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004438 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004439 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004440 break;
4441 }
4442
Kévin Petit349c9502019-03-28 17:24:14 +00004443 // Handle SPIR-V intrinsics
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004444 spv::Op opcode =
4445 StringSwitch<spv::Op>(Callee->getName())
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004446 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4447 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4448 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004449 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4450 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4451 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
4452 .StartsWith("spirv.store_null", spv::OpStore)
4453 .StartsWith("__spirv_isinf", spv::OpIsInf)
4454 .StartsWith("__spirv_isnan", spv::OpIsNan)
4455 .StartsWith("__spirv_allDv", spv::OpAll)
4456 .StartsWith("__spirv_anyDv", spv::OpAny)
4457 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004458
Kévin Petit617a76d2019-04-04 13:54:16 +01004459 // If the switch above didn't have an entry maybe the intrinsic
4460 // is using the name mangling logic.
4461 bool usesMangler = false;
4462 if (opcode == spv::OpNop) {
4463 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4464 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4465 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4466 usesMangler = true;
4467 }
4468 }
4469
Kévin Petit349c9502019-03-28 17:24:14 +00004470 if (opcode != spv::OpNop) {
4471
David Neto22f144c2017-06-12 14:26:21 -04004472 SPIRVOperandList Ops;
4473
Kévin Petit349c9502019-03-28 17:24:14 +00004474 if (!I.getType()->isVoidTy()) {
4475 Ops << MkId(lookupType(I.getType()));
4476 }
David Neto22f144c2017-06-12 14:26:21 -04004477
Kévin Petit617a76d2019-04-04 13:54:16 +01004478 unsigned firstOperand = usesMangler ? 1 : 0;
4479 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004480 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004481 }
4482
Kévin Petit349c9502019-03-28 17:24:14 +00004483 if (!I.getType()->isVoidTy()) {
4484 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004485 }
4486
Kévin Petit349c9502019-03-28 17:24:14 +00004487 SPIRVInstruction *Inst;
4488 if (!I.getType()->isVoidTy()) {
4489 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4490 } else {
4491 Inst = new SPIRVInstruction(opcode, Ops);
4492 }
Kévin Petit8a560882019-03-21 15:24:34 +00004493 SPIRVInstList.push_back(Inst);
4494 break;
4495 }
4496
David Neto22f144c2017-06-12 14:26:21 -04004497 if (Callee->getName().startswith("_Z3dot")) {
4498 // If the argument is a vector type, generate OpDot
4499 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4500 //
4501 // Generate OpDot.
4502 //
4503 SPIRVOperandList Ops;
4504
David Neto257c3892018-04-11 13:19:45 -04004505 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004506
4507 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004508 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004509 }
4510
4511 VMap[&I] = nextID;
4512
David Neto87846742018-04-11 17:36:22 -04004513 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004514 SPIRVInstList.push_back(Inst);
4515 } else {
4516 //
4517 // Generate OpFMul.
4518 //
4519 SPIRVOperandList Ops;
4520
David Neto257c3892018-04-11 13:19:45 -04004521 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004522
4523 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004525 }
4526
4527 VMap[&I] = nextID;
4528
David Neto87846742018-04-11 17:36:22 -04004529 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004530 SPIRVInstList.push_back(Inst);
4531 }
4532 break;
4533 }
4534
David Neto8505ebf2017-10-13 18:50:50 -04004535 if (Callee->getName().startswith("_Z4fmod")) {
4536 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4537 // The sign for a non-zero result is taken from x.
4538 // (Try an example.)
4539 // So translate to OpFRem
4540
4541 SPIRVOperandList Ops;
4542
David Neto257c3892018-04-11 13:19:45 -04004543 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004544
4545 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004546 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004547 }
4548
4549 VMap[&I] = nextID;
4550
David Neto87846742018-04-11 17:36:22 -04004551 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004552 SPIRVInstList.push_back(Inst);
4553 break;
4554 }
4555
David Neto22f144c2017-06-12 14:26:21 -04004556 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4557 if (Callee->getName().startswith("spirv.copy_memory")) {
4558 //
4559 // Generate OpCopyMemory.
4560 //
4561
4562 // Ops[0] = Dst ID
4563 // Ops[1] = Src ID
4564 // Ops[2] = Memory Access
4565 // Ops[3] = Alignment
4566
4567 auto IsVolatile =
4568 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4569
4570 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4571 : spv::MemoryAccessMaskNone;
4572
4573 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4574
4575 auto Alignment =
4576 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4577
David Neto257c3892018-04-11 13:19:45 -04004578 SPIRVOperandList Ops;
4579 Ops << MkId(VMap[Call->getArgOperand(0)])
4580 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4581 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004582
David Neto87846742018-04-11 17:36:22 -04004583 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004584
4585 SPIRVInstList.push_back(Inst);
4586
4587 break;
4588 }
4589
David Neto22f144c2017-06-12 14:26:21 -04004590 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4591 // Additionally, OpTypeSampledImage is generated.
4592 if (Callee->getName().equals(
4593 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4594 Callee->getName().equals(
4595 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4596 //
4597 // Generate OpSampledImage.
4598 //
4599 // Ops[0] = Result Type ID
4600 // Ops[1] = Image ID
4601 // Ops[2] = Sampler ID
4602 //
4603 SPIRVOperandList Ops;
4604
4605 Value *Image = Call->getArgOperand(0);
4606 Value *Sampler = Call->getArgOperand(1);
4607 Value *Coordinate = Call->getArgOperand(2);
4608
4609 TypeMapType &OpImageTypeMap = getImageTypeMap();
4610 Type *ImageTy = Image->getType()->getPointerElementType();
4611 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004612 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004613 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004614
4615 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004616
4617 uint32_t SampledImageID = nextID;
4618
David Neto87846742018-04-11 17:36:22 -04004619 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004620 SPIRVInstList.push_back(Inst);
4621
4622 //
4623 // Generate OpImageSampleExplicitLod.
4624 //
4625 // Ops[0] = Result Type ID
4626 // Ops[1] = Sampled Image ID
4627 // Ops[2] = Coordinate ID
4628 // Ops[3] = Image Operands Type ID
4629 // Ops[4] ... Ops[n] = Operands ID
4630 //
4631 Ops.clear();
4632
David Neto257c3892018-04-11 13:19:45 -04004633 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4634 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004635
4636 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004637 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004638
4639 VMap[&I] = nextID;
4640
David Neto87846742018-04-11 17:36:22 -04004641 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004642 SPIRVInstList.push_back(Inst);
4643 break;
4644 }
4645
4646 // write_imagef is mapped to OpImageWrite.
4647 if (Callee->getName().equals(
4648 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4649 Callee->getName().equals(
4650 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4651 //
4652 // Generate OpImageWrite.
4653 //
4654 // Ops[0] = Image ID
4655 // Ops[1] = Coordinate ID
4656 // Ops[2] = Texel ID
4657 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4658 // Ops[4] ... Ops[n] = (Optional) Operands ID
4659 //
4660 SPIRVOperandList Ops;
4661
4662 Value *Image = Call->getArgOperand(0);
4663 Value *Coordinate = Call->getArgOperand(1);
4664 Value *Texel = Call->getArgOperand(2);
4665
4666 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004667 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004668 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004669 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004670
David Neto87846742018-04-11 17:36:22 -04004671 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004672 SPIRVInstList.push_back(Inst);
4673 break;
4674 }
4675
David Neto5c22a252018-03-15 16:07:41 -04004676 // get_image_width is mapped to OpImageQuerySize
4677 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4678 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4679 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4680 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4681 //
4682 // Generate OpImageQuerySize, then pull out the right component.
4683 // Assume 2D image for now.
4684 //
4685 // Ops[0] = Image ID
4686 //
4687 // %sizes = OpImageQuerySizes %uint2 %im
4688 // %result = OpCompositeExtract %uint %sizes 0-or-1
4689 SPIRVOperandList Ops;
4690
4691 // Implement:
4692 // %sizes = OpImageQuerySizes %uint2 %im
4693 uint32_t SizesTypeID =
4694 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004695 Value *Image = Call->getArgOperand(0);
4696 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004697 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004698
4699 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004700 auto *QueryInst =
4701 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004702 SPIRVInstList.push_back(QueryInst);
4703
4704 // Reset value map entry since we generated an intermediate instruction.
4705 VMap[&I] = nextID;
4706
4707 // Implement:
4708 // %result = OpCompositeExtract %uint %sizes 0-or-1
4709 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004710 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004711
4712 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004713 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004714
David Neto87846742018-04-11 17:36:22 -04004715 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004716 SPIRVInstList.push_back(Inst);
4717 break;
4718 }
4719
David Neto22f144c2017-06-12 14:26:21 -04004720 // Call instrucion is deferred because it needs function's ID. Record
4721 // slot's location on SPIRVInstructionList.
4722 DeferredInsts.push_back(
4723 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4724
David Neto3fbb4072017-10-16 11:28:14 -04004725 // Check whether the implementation of this call uses an extended
4726 // instruction plus one more value-producing instruction. If so, then
4727 // reserve the id for the extra value-producing slot.
4728 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4729 if (EInst != kGlslExtInstBad) {
4730 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004731 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004732 VMap[&I] = nextID;
4733 nextID++;
4734 }
4735 break;
4736 }
4737 case Instruction::Ret: {
4738 unsigned NumOps = I.getNumOperands();
4739 if (NumOps == 0) {
4740 //
4741 // Generate OpReturn.
4742 //
David Neto87846742018-04-11 17:36:22 -04004743 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004744 } else {
4745 //
4746 // Generate OpReturnValue.
4747 //
4748
4749 // Ops[0] = Return Value ID
4750 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004751
4752 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004753
David Neto87846742018-04-11 17:36:22 -04004754 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004755 SPIRVInstList.push_back(Inst);
4756 break;
4757 }
4758 break;
4759 }
4760 }
4761}
4762
4763void SPIRVProducerPass::GenerateFuncEpilogue() {
4764 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4765
4766 //
4767 // Generate OpFunctionEnd
4768 //
4769
David Neto87846742018-04-11 17:36:22 -04004770 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004771 SPIRVInstList.push_back(Inst);
4772}
4773
4774bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004775 // Don't specialize <4 x i8> if i8 is generally supported.
4776 if (clspv::Option::Int8Support())
4777 return false;
4778
David Neto22f144c2017-06-12 14:26:21 -04004779 LLVMContext &Context = Ty->getContext();
4780 if (Ty->isVectorTy()) {
4781 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4782 Ty->getVectorNumElements() == 4) {
4783 return true;
4784 }
4785 }
4786
4787 return false;
4788}
4789
David Neto257c3892018-04-11 13:19:45 -04004790uint32_t SPIRVProducerPass::GetI32Zero() {
4791 if (0 == constant_i32_zero_id_) {
4792 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4793 "defined in the SPIR-V module");
4794 }
4795 return constant_i32_zero_id_;
4796}
4797
David Neto22f144c2017-06-12 14:26:21 -04004798void SPIRVProducerPass::HandleDeferredInstruction() {
4799 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4800 ValueMapType &VMap = getValueMap();
4801 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4802
4803 for (auto DeferredInst = DeferredInsts.rbegin();
4804 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4805 Value *Inst = std::get<0>(*DeferredInst);
4806 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4807 if (InsertPoint != SPIRVInstList.end()) {
4808 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4809 ++InsertPoint;
4810 }
4811 }
4812
4813 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4814 // Check whether basic block, which has this branch instruction, is loop
4815 // header or not. If it is loop header, generate OpLoopMerge and
4816 // OpBranchConditional.
4817 Function *Func = Br->getParent()->getParent();
4818 DominatorTree &DT =
4819 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4820 const LoopInfo &LI =
4821 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4822
4823 BasicBlock *BrBB = Br->getParent();
4824 if (LI.isLoopHeader(BrBB)) {
4825 Value *ContinueBB = nullptr;
4826 Value *MergeBB = nullptr;
4827
4828 Loop *L = LI.getLoopFor(BrBB);
4829 MergeBB = L->getExitBlock();
4830 if (!MergeBB) {
4831 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4832 // has regions with single entry/exit. As a result, loop should not
4833 // have multiple exits.
4834 llvm_unreachable("Loop has multiple exits???");
4835 }
4836
4837 if (L->isLoopLatch(BrBB)) {
4838 ContinueBB = BrBB;
4839 } else {
4840 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4841 // block.
4842 BasicBlock *Header = L->getHeader();
4843 BasicBlock *Latch = L->getLoopLatch();
4844 for (BasicBlock *BB : L->blocks()) {
4845 if (BB == Header) {
4846 continue;
4847 }
4848
4849 // Check whether block dominates block with back-edge.
4850 if (DT.dominates(BB, Latch)) {
4851 ContinueBB = BB;
4852 }
4853 }
4854
4855 if (!ContinueBB) {
4856 llvm_unreachable("Wrong continue block from loop");
4857 }
4858 }
4859
4860 //
4861 // Generate OpLoopMerge.
4862 //
4863 // Ops[0] = Merge Block ID
4864 // Ops[1] = Continue Target ID
4865 // Ops[2] = Selection Control
4866 SPIRVOperandList Ops;
4867
4868 // StructurizeCFG pass already manipulated CFG. Just use false block of
4869 // branch instruction as merge block.
4870 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004871 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004872 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4873 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004874
David Neto87846742018-04-11 17:36:22 -04004875 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004876 SPIRVInstList.insert(InsertPoint, MergeInst);
4877
4878 } else if (Br->isConditional()) {
4879 bool HasBackEdge = false;
4880
4881 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4882 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4883 HasBackEdge = true;
4884 }
4885 }
4886 if (!HasBackEdge) {
4887 //
4888 // Generate OpSelectionMerge.
4889 //
4890 // Ops[0] = Merge Block ID
4891 // Ops[1] = Selection Control
4892 SPIRVOperandList Ops;
4893
4894 // StructurizeCFG pass already manipulated CFG. Just use false block
4895 // of branch instruction as merge block.
4896 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004897 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004898
David Neto87846742018-04-11 17:36:22 -04004899 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004900 SPIRVInstList.insert(InsertPoint, MergeInst);
4901 }
4902 }
4903
4904 if (Br->isConditional()) {
4905 //
4906 // Generate OpBranchConditional.
4907 //
4908 // Ops[0] = Condition ID
4909 // Ops[1] = True Label ID
4910 // Ops[2] = False Label ID
4911 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4912 SPIRVOperandList Ops;
4913
4914 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004915 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004916 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004917
4918 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004919
David Neto87846742018-04-11 17:36:22 -04004920 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004921 SPIRVInstList.insert(InsertPoint, BrInst);
4922 } else {
4923 //
4924 // Generate OpBranch.
4925 //
4926 // Ops[0] = Target Label ID
4927 SPIRVOperandList Ops;
4928
4929 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004930 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004931
David Neto87846742018-04-11 17:36:22 -04004932 SPIRVInstList.insert(InsertPoint,
4933 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004934 }
4935 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004936 if (PHI->getType()->isPointerTy()) {
4937 // OpPhi on pointers requires variable pointers.
4938 setVariablePointersCapabilities(
4939 PHI->getType()->getPointerAddressSpace());
4940 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4941 setVariablePointers(true);
4942 }
4943 }
4944
David Neto22f144c2017-06-12 14:26:21 -04004945 //
4946 // Generate OpPhi.
4947 //
4948 // Ops[0] = Result Type ID
4949 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4950 SPIRVOperandList Ops;
4951
David Neto257c3892018-04-11 13:19:45 -04004952 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004953
David Neto22f144c2017-06-12 14:26:21 -04004954 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4955 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004956 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004957 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004958 }
4959
4960 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004961 InsertPoint,
4962 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004963 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4964 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004965 auto callee_name = Callee->getName();
4966 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004967
4968 if (EInst) {
4969 uint32_t &ExtInstImportID = getOpExtInstImportID();
4970
4971 //
4972 // Generate OpExtInst.
4973 //
4974
4975 // Ops[0] = Result Type ID
4976 // Ops[1] = Set ID (OpExtInstImport ID)
4977 // Ops[2] = Instruction Number (Literal Number)
4978 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4979 SPIRVOperandList Ops;
4980
David Neto862b7d82018-06-14 18:48:37 -04004981 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4982 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004983
David Neto22f144c2017-06-12 14:26:21 -04004984 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4985 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004986 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004987 }
4988
David Neto87846742018-04-11 17:36:22 -04004989 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4990 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004991 SPIRVInstList.insert(InsertPoint, ExtInst);
4992
David Neto3fbb4072017-10-16 11:28:14 -04004993 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4994 if (IndirectExtInst != kGlslExtInstBad) {
4995 // Generate one more instruction that uses the result of the extended
4996 // instruction. Its result id is one more than the id of the
4997 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004998 LLVMContext &Context =
4999 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005000
David Neto3fbb4072017-10-16 11:28:14 -04005001 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5002 &VMap, &SPIRVInstList, &InsertPoint](
5003 spv::Op opcode, Constant *constant) {
5004 //
5005 // Generate instruction like:
5006 // result = opcode constant <extinst-result>
5007 //
5008 // Ops[0] = Result Type ID
5009 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5010 // Ops[2] = Operand 1 ;; the result of the extended instruction
5011 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005012
David Neto3fbb4072017-10-16 11:28:14 -04005013 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005014 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005015
5016 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5017 constant = ConstantVector::getSplat(
5018 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5019 }
David Neto257c3892018-04-11 13:19:45 -04005020 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005021
5022 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005023 InsertPoint, new SPIRVInstruction(
5024 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005025 };
5026
5027 switch (IndirectExtInst) {
5028 case glsl::ExtInstFindUMsb: // Implementing clz
5029 generate_extra_inst(
5030 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5031 break;
5032 case glsl::ExtInstAcos: // Implementing acospi
5033 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005034 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005035 case glsl::ExtInstAtan2: // Implementing atan2pi
5036 generate_extra_inst(
5037 spv::OpFMul,
5038 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5039 break;
5040
5041 default:
5042 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005043 }
David Neto22f144c2017-06-12 14:26:21 -04005044 }
David Neto3fbb4072017-10-16 11:28:14 -04005045
alan-bakerb39c8262019-03-08 14:03:37 -05005046 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005047 //
5048 // Generate OpBitCount
5049 //
5050 // Ops[0] = Result Type ID
5051 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005052 SPIRVOperandList Ops;
5053 Ops << MkId(lookupType(Call->getType()))
5054 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005055
5056 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005057 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005058 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005059
David Neto862b7d82018-06-14 18:48:37 -04005060 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005061
5062 // Generate an OpCompositeConstruct
5063 SPIRVOperandList Ops;
5064
5065 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005066 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005067
5068 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005069 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005070 }
5071
5072 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005073 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5074 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005075
Alan Baker202c8c72018-08-13 13:47:44 -04005076 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5077
5078 // We have already mapped the call's result value to an ID.
5079 // Don't generate any code now.
5080
5081 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005082
5083 // We have already mapped the call's result value to an ID.
5084 // Don't generate any code now.
5085
David Neto22f144c2017-06-12 14:26:21 -04005086 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005087 if (Call->getType()->isPointerTy()) {
5088 // Functions returning pointers require variable pointers.
5089 setVariablePointersCapabilities(
5090 Call->getType()->getPointerAddressSpace());
5091 }
5092
David Neto22f144c2017-06-12 14:26:21 -04005093 //
5094 // Generate OpFunctionCall.
5095 //
5096
5097 // Ops[0] = Result Type ID
5098 // Ops[1] = Callee Function ID
5099 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5100 SPIRVOperandList Ops;
5101
David Neto862b7d82018-06-14 18:48:37 -04005102 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005103
5104 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005105 if (CalleeID == 0) {
5106 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005107 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005108 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5109 // causes an infinite loop. Instead, go ahead and generate
5110 // the bad function call. A validator will catch the 0-Id.
5111 // llvm_unreachable("Can't translate function call");
5112 }
David Neto22f144c2017-06-12 14:26:21 -04005113
David Neto257c3892018-04-11 13:19:45 -04005114 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005115
David Neto22f144c2017-06-12 14:26:21 -04005116 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5117 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005118 auto *operand = Call->getOperand(i);
5119 if (operand->getType()->isPointerTy()) {
5120 auto sc =
5121 GetStorageClass(operand->getType()->getPointerAddressSpace());
5122 if (sc == spv::StorageClassStorageBuffer) {
5123 // Passing SSBO by reference requires variable pointers storage
5124 // buffer.
5125 setVariablePointersStorageBuffer(true);
5126 } else if (sc == spv::StorageClassWorkgroup) {
5127 // Workgroup references require variable pointers if they are not
5128 // memory object declarations.
5129 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5130 // Workgroup accessor represents a variable reference.
5131 if (!operand_call->getCalledFunction()->getName().startswith(
5132 clspv::WorkgroupAccessorFunction()))
5133 setVariablePointers(true);
5134 } else {
5135 // Arguments are function parameters.
5136 if (!isa<Argument>(operand))
5137 setVariablePointers(true);
5138 }
5139 }
5140 }
5141 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005142 }
5143
David Neto87846742018-04-11 17:36:22 -04005144 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5145 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005146 SPIRVInstList.insert(InsertPoint, CallInst);
5147 }
5148 }
5149 }
5150}
5151
David Neto1a1a0582017-07-07 12:01:44 -04005152void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005153 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005154 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005155 }
David Neto1a1a0582017-07-07 12:01:44 -04005156
5157 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005158
5159 // Find an iterator pointing just past the last decoration.
5160 bool seen_decorations = false;
5161 auto DecoInsertPoint =
5162 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5163 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5164 const bool is_decoration =
5165 Inst->getOpcode() == spv::OpDecorate ||
5166 Inst->getOpcode() == spv::OpMemberDecorate;
5167 if (is_decoration) {
5168 seen_decorations = true;
5169 return false;
5170 } else {
5171 return seen_decorations;
5172 }
5173 });
5174
David Netoc6f3ab22018-04-06 18:02:31 -04005175 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5176 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005177 for (auto *type : getTypesNeedingArrayStride()) {
5178 Type *elemTy = nullptr;
5179 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5180 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005181 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005182 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005183 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005184 elemTy = seqTy->getSequentialElementType();
5185 } else {
5186 errs() << "Unhandled strided type " << *type << "\n";
5187 llvm_unreachable("Unhandled strided type");
5188 }
David Neto1a1a0582017-07-07 12:01:44 -04005189
5190 // Ops[0] = Target ID
5191 // Ops[1] = Decoration (ArrayStride)
5192 // Ops[2] = Stride number (Literal Number)
5193 SPIRVOperandList Ops;
5194
David Neto85082642018-03-24 06:55:20 -07005195 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005196 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005197
5198 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5199 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005200
David Neto87846742018-04-11 17:36:22 -04005201 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005202 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5203 }
David Netoc6f3ab22018-04-06 18:02:31 -04005204
5205 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005206 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5207 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005208 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005209 SPIRVOperandList Ops;
5210 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5211 << MkNum(arg_info.spec_id);
5212 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005213 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005214 }
David Neto1a1a0582017-07-07 12:01:44 -04005215}
5216
David Neto22f144c2017-06-12 14:26:21 -04005217glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5218 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005219 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5220 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5221 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5222 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005223 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5224 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5225 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5226 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005227 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5228 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5229 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5230 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005231 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5232 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5233 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5234 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005235 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5236 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5237 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5238 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5239 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5240 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5241 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5242 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005243 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5244 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5245 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5246 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5247 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5248 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5249 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5250 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005251 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5252 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5253 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5254 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5255 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5256 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5257 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5258 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005259 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5260 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5261 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5262 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5263 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5264 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5265 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5266 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005267 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5268 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5269 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5270 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005271 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5272 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5273 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5274 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5275 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5276 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5277 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5278 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005279 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5280 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5281 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5282 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5283 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5284 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5285 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5286 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005287 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5288 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5289 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5290 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5291 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5292 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5293 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5294 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005295 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5296 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5297 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5298 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5299 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5300 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5301 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5302 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005303 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5304 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5305 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5306 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5307 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005308 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5309 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5310 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5311 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5312 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5313 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5314 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5315 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005316 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5317 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5318 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5319 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5320 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5321 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5322 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5323 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005324 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5325 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5326 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5327 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5328 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5329 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5330 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5331 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005332 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5333 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5334 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5335 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5336 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5337 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5338 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5339 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005340 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5341 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5342 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5343 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5344 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5345 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5346 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5347 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5348 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5349 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5350 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5351 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5352 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5353 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5354 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5355 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5356 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5357 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5358 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5359 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5360 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5361 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5362 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5363 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5364 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5365 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5366 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5367 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5368 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5369 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5370 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5371 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5372 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5373 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5374 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5375 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5376 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5377 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5378 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5379 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5380 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005381 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005382 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5383 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5384 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5385 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5386 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5387 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5388 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5389 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5390 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5391 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5392 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5393 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5394 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5395 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5396 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5397 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5398 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005399 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005400 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005401 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005402 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005403 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005404 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5405 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005406 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005407 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5408 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5409 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005410 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5411 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5412 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5413 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005414 .Default(kGlslExtInstBad);
5415}
5416
5417glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5418 // Check indirect cases.
5419 return StringSwitch<glsl::ExtInst>(Name)
5420 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5421 // Use exact match on float arg because these need a multiply
5422 // of a constant of the right floating point type.
5423 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5424 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5425 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5426 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5427 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5428 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5429 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5430 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005431 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5432 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5433 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5434 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005435 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5436 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5437 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5438 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5439 .Default(kGlslExtInstBad);
5440}
5441
alan-bakerb6b09dc2018-11-08 16:59:28 -05005442glsl::ExtInst
5443SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005444 auto direct = getExtInstEnum(Name);
5445 if (direct != kGlslExtInstBad)
5446 return direct;
5447 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005448}
5449
5450void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5451 out << "%" << Inst->getResultID();
5452}
5453
5454void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5455 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5456 out << "\t" << spv::getOpName(Opcode);
5457}
5458
5459void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5460 SPIRVOperandType OpTy = Op->getType();
5461 switch (OpTy) {
5462 default: {
5463 llvm_unreachable("Unsupported SPIRV Operand Type???");
5464 break;
5465 }
5466 case SPIRVOperandType::NUMBERID: {
5467 out << "%" << Op->getNumID();
5468 break;
5469 }
5470 case SPIRVOperandType::LITERAL_STRING: {
5471 out << "\"" << Op->getLiteralStr() << "\"";
5472 break;
5473 }
5474 case SPIRVOperandType::LITERAL_INTEGER: {
5475 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005476 auto Words = Op->getLiteralNum();
5477 auto NumWords = Words.size();
5478
5479 if (NumWords == 1) {
5480 out << Words[0];
5481 } else if (NumWords == 2) {
5482 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5483 out << Val;
5484 } else {
5485 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005486 }
5487 break;
5488 }
5489 case SPIRVOperandType::LITERAL_FLOAT: {
5490 // TODO: Handle LiteralNum carefully.
5491 for (auto Word : Op->getLiteralNum()) {
5492 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5493 SmallString<8> Str;
5494 APF.toString(Str, 6, 2);
5495 out << Str;
5496 }
5497 break;
5498 }
5499 }
5500}
5501
5502void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5503 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5504 out << spv::getCapabilityName(Cap);
5505}
5506
5507void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5508 auto LiteralNum = Op->getLiteralNum();
5509 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5510 out << glsl::getExtInstName(Ext);
5511}
5512
5513void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5514 spv::AddressingModel AddrModel =
5515 static_cast<spv::AddressingModel>(Op->getNumID());
5516 out << spv::getAddressingModelName(AddrModel);
5517}
5518
5519void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5520 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5521 out << spv::getMemoryModelName(MemModel);
5522}
5523
5524void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5525 spv::ExecutionModel ExecModel =
5526 static_cast<spv::ExecutionModel>(Op->getNumID());
5527 out << spv::getExecutionModelName(ExecModel);
5528}
5529
5530void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5531 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5532 out << spv::getExecutionModeName(ExecMode);
5533}
5534
5535void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005536 spv::SourceLanguage SourceLang =
5537 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005538 out << spv::getSourceLanguageName(SourceLang);
5539}
5540
5541void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5542 spv::FunctionControlMask FuncCtrl =
5543 static_cast<spv::FunctionControlMask>(Op->getNumID());
5544 out << spv::getFunctionControlName(FuncCtrl);
5545}
5546
5547void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5548 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5549 out << getStorageClassName(StClass);
5550}
5551
5552void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5553 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5554 out << getDecorationName(Deco);
5555}
5556
5557void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5558 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5559 out << getBuiltInName(BIn);
5560}
5561
5562void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5563 spv::SelectionControlMask BIn =
5564 static_cast<spv::SelectionControlMask>(Op->getNumID());
5565 out << getSelectionControlName(BIn);
5566}
5567
5568void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5569 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5570 out << getLoopControlName(BIn);
5571}
5572
5573void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5574 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5575 out << getDimName(DIM);
5576}
5577
5578void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5579 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5580 out << getImageFormatName(Format);
5581}
5582
5583void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5584 out << spv::getMemoryAccessName(
5585 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5586}
5587
5588void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5589 auto LiteralNum = Op->getLiteralNum();
5590 spv::ImageOperandsMask Type =
5591 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5592 out << getImageOperandsName(Type);
5593}
5594
5595void SPIRVProducerPass::WriteSPIRVAssembly() {
5596 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5597
5598 for (auto Inst : SPIRVInstList) {
5599 SPIRVOperandList Ops = Inst->getOperands();
5600 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5601
5602 switch (Opcode) {
5603 default: {
5604 llvm_unreachable("Unsupported SPIRV instruction");
5605 break;
5606 }
5607 case spv::OpCapability: {
5608 // Ops[0] = Capability
5609 PrintOpcode(Inst);
5610 out << " ";
5611 PrintCapability(Ops[0]);
5612 out << "\n";
5613 break;
5614 }
5615 case spv::OpMemoryModel: {
5616 // Ops[0] = Addressing Model
5617 // Ops[1] = Memory Model
5618 PrintOpcode(Inst);
5619 out << " ";
5620 PrintAddrModel(Ops[0]);
5621 out << " ";
5622 PrintMemModel(Ops[1]);
5623 out << "\n";
5624 break;
5625 }
5626 case spv::OpEntryPoint: {
5627 // Ops[0] = Execution Model
5628 // Ops[1] = EntryPoint ID
5629 // Ops[2] = Name (Literal String)
5630 // Ops[3] ... Ops[n] = Interface ID
5631 PrintOpcode(Inst);
5632 out << " ";
5633 PrintExecModel(Ops[0]);
5634 for (uint32_t i = 1; i < Ops.size(); i++) {
5635 out << " ";
5636 PrintOperand(Ops[i]);
5637 }
5638 out << "\n";
5639 break;
5640 }
5641 case spv::OpExecutionMode: {
5642 // Ops[0] = Entry Point ID
5643 // Ops[1] = Execution Mode
5644 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5645 PrintOpcode(Inst);
5646 out << " ";
5647 PrintOperand(Ops[0]);
5648 out << " ";
5649 PrintExecMode(Ops[1]);
5650 for (uint32_t i = 2; i < Ops.size(); i++) {
5651 out << " ";
5652 PrintOperand(Ops[i]);
5653 }
5654 out << "\n";
5655 break;
5656 }
5657 case spv::OpSource: {
5658 // Ops[0] = SourceLanguage ID
5659 // Ops[1] = Version (LiteralNum)
5660 PrintOpcode(Inst);
5661 out << " ";
5662 PrintSourceLanguage(Ops[0]);
5663 out << " ";
5664 PrintOperand(Ops[1]);
5665 out << "\n";
5666 break;
5667 }
5668 case spv::OpDecorate: {
5669 // Ops[0] = Target ID
5670 // Ops[1] = Decoration (Block or BufferBlock)
5671 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5672 PrintOpcode(Inst);
5673 out << " ";
5674 PrintOperand(Ops[0]);
5675 out << " ";
5676 PrintDecoration(Ops[1]);
5677 // Handle BuiltIn OpDecorate specially.
5678 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5679 out << " ";
5680 PrintBuiltIn(Ops[2]);
5681 } else {
5682 for (uint32_t i = 2; i < Ops.size(); i++) {
5683 out << " ";
5684 PrintOperand(Ops[i]);
5685 }
5686 }
5687 out << "\n";
5688 break;
5689 }
5690 case spv::OpMemberDecorate: {
5691 // Ops[0] = Structure Type ID
5692 // Ops[1] = Member Index(Literal Number)
5693 // Ops[2] = Decoration
5694 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5695 PrintOpcode(Inst);
5696 out << " ";
5697 PrintOperand(Ops[0]);
5698 out << " ";
5699 PrintOperand(Ops[1]);
5700 out << " ";
5701 PrintDecoration(Ops[2]);
5702 for (uint32_t i = 3; i < Ops.size(); i++) {
5703 out << " ";
5704 PrintOperand(Ops[i]);
5705 }
5706 out << "\n";
5707 break;
5708 }
5709 case spv::OpTypePointer: {
5710 // Ops[0] = Storage Class
5711 // Ops[1] = Element Type ID
5712 PrintResID(Inst);
5713 out << " = ";
5714 PrintOpcode(Inst);
5715 out << " ";
5716 PrintStorageClass(Ops[0]);
5717 out << " ";
5718 PrintOperand(Ops[1]);
5719 out << "\n";
5720 break;
5721 }
5722 case spv::OpTypeImage: {
5723 // Ops[0] = Sampled Type ID
5724 // Ops[1] = Dim ID
5725 // Ops[2] = Depth (Literal Number)
5726 // Ops[3] = Arrayed (Literal Number)
5727 // Ops[4] = MS (Literal Number)
5728 // Ops[5] = Sampled (Literal Number)
5729 // Ops[6] = Image Format ID
5730 PrintResID(Inst);
5731 out << " = ";
5732 PrintOpcode(Inst);
5733 out << " ";
5734 PrintOperand(Ops[0]);
5735 out << " ";
5736 PrintDimensionality(Ops[1]);
5737 out << " ";
5738 PrintOperand(Ops[2]);
5739 out << " ";
5740 PrintOperand(Ops[3]);
5741 out << " ";
5742 PrintOperand(Ops[4]);
5743 out << " ";
5744 PrintOperand(Ops[5]);
5745 out << " ";
5746 PrintImageFormat(Ops[6]);
5747 out << "\n";
5748 break;
5749 }
5750 case spv::OpFunction: {
5751 // Ops[0] : Result Type ID
5752 // Ops[1] : Function Control
5753 // Ops[2] : Function Type ID
5754 PrintResID(Inst);
5755 out << " = ";
5756 PrintOpcode(Inst);
5757 out << " ";
5758 PrintOperand(Ops[0]);
5759 out << " ";
5760 PrintFuncCtrl(Ops[1]);
5761 out << " ";
5762 PrintOperand(Ops[2]);
5763 out << "\n";
5764 break;
5765 }
5766 case spv::OpSelectionMerge: {
5767 // Ops[0] = Merge Block ID
5768 // Ops[1] = Selection Control
5769 PrintOpcode(Inst);
5770 out << " ";
5771 PrintOperand(Ops[0]);
5772 out << " ";
5773 PrintSelectionControl(Ops[1]);
5774 out << "\n";
5775 break;
5776 }
5777 case spv::OpLoopMerge: {
5778 // Ops[0] = Merge Block ID
5779 // Ops[1] = Continue Target ID
5780 // Ops[2] = Selection Control
5781 PrintOpcode(Inst);
5782 out << " ";
5783 PrintOperand(Ops[0]);
5784 out << " ";
5785 PrintOperand(Ops[1]);
5786 out << " ";
5787 PrintLoopControl(Ops[2]);
5788 out << "\n";
5789 break;
5790 }
5791 case spv::OpImageSampleExplicitLod: {
5792 // Ops[0] = Result Type ID
5793 // Ops[1] = Sampled Image ID
5794 // Ops[2] = Coordinate ID
5795 // Ops[3] = Image Operands Type ID
5796 // Ops[4] ... Ops[n] = Operands ID
5797 PrintResID(Inst);
5798 out << " = ";
5799 PrintOpcode(Inst);
5800 for (uint32_t i = 0; i < 3; i++) {
5801 out << " ";
5802 PrintOperand(Ops[i]);
5803 }
5804 out << " ";
5805 PrintImageOperandsType(Ops[3]);
5806 for (uint32_t i = 4; i < Ops.size(); i++) {
5807 out << " ";
5808 PrintOperand(Ops[i]);
5809 }
5810 out << "\n";
5811 break;
5812 }
5813 case spv::OpVariable: {
5814 // Ops[0] : Result Type ID
5815 // Ops[1] : Storage Class
5816 // Ops[2] ... Ops[n] = Initializer IDs
5817 PrintResID(Inst);
5818 out << " = ";
5819 PrintOpcode(Inst);
5820 out << " ";
5821 PrintOperand(Ops[0]);
5822 out << " ";
5823 PrintStorageClass(Ops[1]);
5824 for (uint32_t i = 2; i < Ops.size(); i++) {
5825 out << " ";
5826 PrintOperand(Ops[i]);
5827 }
5828 out << "\n";
5829 break;
5830 }
5831 case spv::OpExtInst: {
5832 // Ops[0] = Result Type ID
5833 // Ops[1] = Set ID (OpExtInstImport ID)
5834 // Ops[2] = Instruction Number (Literal Number)
5835 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5836 PrintResID(Inst);
5837 out << " = ";
5838 PrintOpcode(Inst);
5839 out << " ";
5840 PrintOperand(Ops[0]);
5841 out << " ";
5842 PrintOperand(Ops[1]);
5843 out << " ";
5844 PrintExtInst(Ops[2]);
5845 for (uint32_t i = 3; i < Ops.size(); i++) {
5846 out << " ";
5847 PrintOperand(Ops[i]);
5848 }
5849 out << "\n";
5850 break;
5851 }
5852 case spv::OpCopyMemory: {
5853 // Ops[0] = Addressing Model
5854 // Ops[1] = Memory Model
5855 PrintOpcode(Inst);
5856 out << " ";
5857 PrintOperand(Ops[0]);
5858 out << " ";
5859 PrintOperand(Ops[1]);
5860 out << " ";
5861 PrintMemoryAccess(Ops[2]);
5862 out << " ";
5863 PrintOperand(Ops[3]);
5864 out << "\n";
5865 break;
5866 }
5867 case spv::OpExtension:
5868 case spv::OpControlBarrier:
5869 case spv::OpMemoryBarrier:
5870 case spv::OpBranch:
5871 case spv::OpBranchConditional:
5872 case spv::OpStore:
5873 case spv::OpImageWrite:
5874 case spv::OpReturnValue:
5875 case spv::OpReturn:
5876 case spv::OpFunctionEnd: {
5877 PrintOpcode(Inst);
5878 for (uint32_t i = 0; i < Ops.size(); i++) {
5879 out << " ";
5880 PrintOperand(Ops[i]);
5881 }
5882 out << "\n";
5883 break;
5884 }
5885 case spv::OpExtInstImport:
5886 case spv::OpTypeRuntimeArray:
5887 case spv::OpTypeStruct:
5888 case spv::OpTypeSampler:
5889 case spv::OpTypeSampledImage:
5890 case spv::OpTypeInt:
5891 case spv::OpTypeFloat:
5892 case spv::OpTypeArray:
5893 case spv::OpTypeVector:
5894 case spv::OpTypeBool:
5895 case spv::OpTypeVoid:
5896 case spv::OpTypeFunction:
5897 case spv::OpFunctionParameter:
5898 case spv::OpLabel:
5899 case spv::OpPhi:
5900 case spv::OpLoad:
5901 case spv::OpSelect:
5902 case spv::OpAccessChain:
5903 case spv::OpPtrAccessChain:
5904 case spv::OpInBoundsAccessChain:
5905 case spv::OpUConvert:
5906 case spv::OpSConvert:
5907 case spv::OpConvertFToU:
5908 case spv::OpConvertFToS:
5909 case spv::OpConvertUToF:
5910 case spv::OpConvertSToF:
5911 case spv::OpFConvert:
5912 case spv::OpConvertPtrToU:
5913 case spv::OpConvertUToPtr:
5914 case spv::OpBitcast:
5915 case spv::OpIAdd:
5916 case spv::OpFAdd:
5917 case spv::OpISub:
5918 case spv::OpFSub:
5919 case spv::OpIMul:
5920 case spv::OpFMul:
5921 case spv::OpUDiv:
5922 case spv::OpSDiv:
5923 case spv::OpFDiv:
5924 case spv::OpUMod:
5925 case spv::OpSRem:
5926 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005927 case spv::OpUMulExtended:
5928 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005929 case spv::OpBitwiseOr:
5930 case spv::OpBitwiseXor:
5931 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005932 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005933 case spv::OpShiftLeftLogical:
5934 case spv::OpShiftRightLogical:
5935 case spv::OpShiftRightArithmetic:
5936 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005937 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005938 case spv::OpCompositeExtract:
5939 case spv::OpVectorExtractDynamic:
5940 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005941 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005942 case spv::OpVectorInsertDynamic:
5943 case spv::OpVectorShuffle:
5944 case spv::OpIEqual:
5945 case spv::OpINotEqual:
5946 case spv::OpUGreaterThan:
5947 case spv::OpUGreaterThanEqual:
5948 case spv::OpULessThan:
5949 case spv::OpULessThanEqual:
5950 case spv::OpSGreaterThan:
5951 case spv::OpSGreaterThanEqual:
5952 case spv::OpSLessThan:
5953 case spv::OpSLessThanEqual:
5954 case spv::OpFOrdEqual:
5955 case spv::OpFOrdGreaterThan:
5956 case spv::OpFOrdGreaterThanEqual:
5957 case spv::OpFOrdLessThan:
5958 case spv::OpFOrdLessThanEqual:
5959 case spv::OpFOrdNotEqual:
5960 case spv::OpFUnordEqual:
5961 case spv::OpFUnordGreaterThan:
5962 case spv::OpFUnordGreaterThanEqual:
5963 case spv::OpFUnordLessThan:
5964 case spv::OpFUnordLessThanEqual:
5965 case spv::OpFUnordNotEqual:
5966 case spv::OpSampledImage:
5967 case spv::OpFunctionCall:
5968 case spv::OpConstantTrue:
5969 case spv::OpConstantFalse:
5970 case spv::OpConstant:
5971 case spv::OpSpecConstant:
5972 case spv::OpConstantComposite:
5973 case spv::OpSpecConstantComposite:
5974 case spv::OpConstantNull:
5975 case spv::OpLogicalOr:
5976 case spv::OpLogicalAnd:
5977 case spv::OpLogicalNot:
5978 case spv::OpLogicalNotEqual:
5979 case spv::OpUndef:
5980 case spv::OpIsInf:
5981 case spv::OpIsNan:
5982 case spv::OpAny:
5983 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005984 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005985 case spv::OpAtomicIAdd:
5986 case spv::OpAtomicISub:
5987 case spv::OpAtomicExchange:
5988 case spv::OpAtomicIIncrement:
5989 case spv::OpAtomicIDecrement:
5990 case spv::OpAtomicCompareExchange:
5991 case spv::OpAtomicUMin:
5992 case spv::OpAtomicSMin:
5993 case spv::OpAtomicUMax:
5994 case spv::OpAtomicSMax:
5995 case spv::OpAtomicAnd:
5996 case spv::OpAtomicOr:
5997 case spv::OpAtomicXor:
5998 case spv::OpDot: {
5999 PrintResID(Inst);
6000 out << " = ";
6001 PrintOpcode(Inst);
6002 for (uint32_t i = 0; i < Ops.size(); i++) {
6003 out << " ";
6004 PrintOperand(Ops[i]);
6005 }
6006 out << "\n";
6007 break;
6008 }
6009 }
6010 }
6011}
6012
6013void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006014 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006015}
6016
6017void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6018 WriteOneWord(Inst->getResultID());
6019}
6020
6021void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6022 // High 16 bit : Word Count
6023 // Low 16 bit : Opcode
6024 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006025 const uint32_t count = Inst->getWordCount();
6026 if (count > 65535) {
6027 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6028 llvm_unreachable("Word count too high");
6029 }
David Neto22f144c2017-06-12 14:26:21 -04006030 Word |= Inst->getWordCount() << 16;
6031 WriteOneWord(Word);
6032}
6033
6034void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6035 SPIRVOperandType OpTy = Op->getType();
6036 switch (OpTy) {
6037 default: {
6038 llvm_unreachable("Unsupported SPIRV Operand Type???");
6039 break;
6040 }
6041 case SPIRVOperandType::NUMBERID: {
6042 WriteOneWord(Op->getNumID());
6043 break;
6044 }
6045 case SPIRVOperandType::LITERAL_STRING: {
6046 std::string Str = Op->getLiteralStr();
6047 const char *Data = Str.c_str();
6048 size_t WordSize = Str.size() / 4;
6049 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6050 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6051 }
6052
6053 uint32_t Remainder = Str.size() % 4;
6054 uint32_t LastWord = 0;
6055 if (Remainder) {
6056 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6057 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6058 }
6059 }
6060
6061 WriteOneWord(LastWord);
6062 break;
6063 }
6064 case SPIRVOperandType::LITERAL_INTEGER:
6065 case SPIRVOperandType::LITERAL_FLOAT: {
6066 auto LiteralNum = Op->getLiteralNum();
6067 // TODO: Handle LiteranNum carefully.
6068 for (auto Word : LiteralNum) {
6069 WriteOneWord(Word);
6070 }
6071 break;
6072 }
6073 }
6074}
6075
6076void SPIRVProducerPass::WriteSPIRVBinary() {
6077 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6078
6079 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006080 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006081 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6082
6083 switch (Opcode) {
6084 default: {
David Neto5c22a252018-03-15 16:07:41 -04006085 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006086 llvm_unreachable("Unsupported SPIRV instruction");
6087 break;
6088 }
6089 case spv::OpCapability:
6090 case spv::OpExtension:
6091 case spv::OpMemoryModel:
6092 case spv::OpEntryPoint:
6093 case spv::OpExecutionMode:
6094 case spv::OpSource:
6095 case spv::OpDecorate:
6096 case spv::OpMemberDecorate:
6097 case spv::OpBranch:
6098 case spv::OpBranchConditional:
6099 case spv::OpSelectionMerge:
6100 case spv::OpLoopMerge:
6101 case spv::OpStore:
6102 case spv::OpImageWrite:
6103 case spv::OpReturnValue:
6104 case spv::OpControlBarrier:
6105 case spv::OpMemoryBarrier:
6106 case spv::OpReturn:
6107 case spv::OpFunctionEnd:
6108 case spv::OpCopyMemory: {
6109 WriteWordCountAndOpcode(Inst);
6110 for (uint32_t i = 0; i < Ops.size(); i++) {
6111 WriteOperand(Ops[i]);
6112 }
6113 break;
6114 }
6115 case spv::OpTypeBool:
6116 case spv::OpTypeVoid:
6117 case spv::OpTypeSampler:
6118 case spv::OpLabel:
6119 case spv::OpExtInstImport:
6120 case spv::OpTypePointer:
6121 case spv::OpTypeRuntimeArray:
6122 case spv::OpTypeStruct:
6123 case spv::OpTypeImage:
6124 case spv::OpTypeSampledImage:
6125 case spv::OpTypeInt:
6126 case spv::OpTypeFloat:
6127 case spv::OpTypeArray:
6128 case spv::OpTypeVector:
6129 case spv::OpTypeFunction: {
6130 WriteWordCountAndOpcode(Inst);
6131 WriteResultID(Inst);
6132 for (uint32_t i = 0; i < Ops.size(); i++) {
6133 WriteOperand(Ops[i]);
6134 }
6135 break;
6136 }
6137 case spv::OpFunction:
6138 case spv::OpFunctionParameter:
6139 case spv::OpAccessChain:
6140 case spv::OpPtrAccessChain:
6141 case spv::OpInBoundsAccessChain:
6142 case spv::OpUConvert:
6143 case spv::OpSConvert:
6144 case spv::OpConvertFToU:
6145 case spv::OpConvertFToS:
6146 case spv::OpConvertUToF:
6147 case spv::OpConvertSToF:
6148 case spv::OpFConvert:
6149 case spv::OpConvertPtrToU:
6150 case spv::OpConvertUToPtr:
6151 case spv::OpBitcast:
6152 case spv::OpIAdd:
6153 case spv::OpFAdd:
6154 case spv::OpISub:
6155 case spv::OpFSub:
6156 case spv::OpIMul:
6157 case spv::OpFMul:
6158 case spv::OpUDiv:
6159 case spv::OpSDiv:
6160 case spv::OpFDiv:
6161 case spv::OpUMod:
6162 case spv::OpSRem:
6163 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006164 case spv::OpUMulExtended:
6165 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006166 case spv::OpBitwiseOr:
6167 case spv::OpBitwiseXor:
6168 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006169 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006170 case spv::OpShiftLeftLogical:
6171 case spv::OpShiftRightLogical:
6172 case spv::OpShiftRightArithmetic:
6173 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006174 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006175 case spv::OpCompositeExtract:
6176 case spv::OpVectorExtractDynamic:
6177 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006178 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006179 case spv::OpVectorInsertDynamic:
6180 case spv::OpVectorShuffle:
6181 case spv::OpIEqual:
6182 case spv::OpINotEqual:
6183 case spv::OpUGreaterThan:
6184 case spv::OpUGreaterThanEqual:
6185 case spv::OpULessThan:
6186 case spv::OpULessThanEqual:
6187 case spv::OpSGreaterThan:
6188 case spv::OpSGreaterThanEqual:
6189 case spv::OpSLessThan:
6190 case spv::OpSLessThanEqual:
6191 case spv::OpFOrdEqual:
6192 case spv::OpFOrdGreaterThan:
6193 case spv::OpFOrdGreaterThanEqual:
6194 case spv::OpFOrdLessThan:
6195 case spv::OpFOrdLessThanEqual:
6196 case spv::OpFOrdNotEqual:
6197 case spv::OpFUnordEqual:
6198 case spv::OpFUnordGreaterThan:
6199 case spv::OpFUnordGreaterThanEqual:
6200 case spv::OpFUnordLessThan:
6201 case spv::OpFUnordLessThanEqual:
6202 case spv::OpFUnordNotEqual:
6203 case spv::OpExtInst:
6204 case spv::OpIsInf:
6205 case spv::OpIsNan:
6206 case spv::OpAny:
6207 case spv::OpAll:
6208 case spv::OpUndef:
6209 case spv::OpConstantNull:
6210 case spv::OpLogicalOr:
6211 case spv::OpLogicalAnd:
6212 case spv::OpLogicalNot:
6213 case spv::OpLogicalNotEqual:
6214 case spv::OpConstantComposite:
6215 case spv::OpSpecConstantComposite:
6216 case spv::OpConstantTrue:
6217 case spv::OpConstantFalse:
6218 case spv::OpConstant:
6219 case spv::OpSpecConstant:
6220 case spv::OpVariable:
6221 case spv::OpFunctionCall:
6222 case spv::OpSampledImage:
6223 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006224 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006225 case spv::OpSelect:
6226 case spv::OpPhi:
6227 case spv::OpLoad:
6228 case spv::OpAtomicIAdd:
6229 case spv::OpAtomicISub:
6230 case spv::OpAtomicExchange:
6231 case spv::OpAtomicIIncrement:
6232 case spv::OpAtomicIDecrement:
6233 case spv::OpAtomicCompareExchange:
6234 case spv::OpAtomicUMin:
6235 case spv::OpAtomicSMin:
6236 case spv::OpAtomicUMax:
6237 case spv::OpAtomicSMax:
6238 case spv::OpAtomicAnd:
6239 case spv::OpAtomicOr:
6240 case spv::OpAtomicXor:
6241 case spv::OpDot: {
6242 WriteWordCountAndOpcode(Inst);
6243 WriteOperand(Ops[0]);
6244 WriteResultID(Inst);
6245 for (uint32_t i = 1; i < Ops.size(); i++) {
6246 WriteOperand(Ops[i]);
6247 }
6248 break;
6249 }
6250 }
6251 }
6252}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006253
alan-bakerb6b09dc2018-11-08 16:59:28 -05006254bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006255 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006256 case Type::HalfTyID:
6257 case Type::FloatTyID:
6258 case Type::DoubleTyID:
6259 case Type::IntegerTyID:
6260 case Type::VectorTyID:
6261 return true;
6262 case Type::PointerTyID: {
6263 const PointerType *pointer_type = cast<PointerType>(type);
6264 if (pointer_type->getPointerAddressSpace() !=
6265 AddressSpace::UniformConstant) {
6266 auto pointee_type = pointer_type->getPointerElementType();
6267 if (pointee_type->isStructTy() &&
6268 cast<StructType>(pointee_type)->isOpaque()) {
6269 // Images and samplers are not nullable.
6270 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006271 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006272 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006273 return true;
6274 }
6275 case Type::ArrayTyID:
6276 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6277 case Type::StructTyID: {
6278 const StructType *struct_type = cast<StructType>(type);
6279 // Images and samplers are not nullable.
6280 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006281 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006282 for (const auto element : struct_type->elements()) {
6283 if (!IsTypeNullable(element))
6284 return false;
6285 }
6286 return true;
6287 }
6288 default:
6289 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006290 }
6291}
Alan Bakerfcda9482018-10-02 17:09:59 -04006292
6293void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6294 if (auto *offsets_md =
6295 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6296 // Metdata is stored as key-value pair operands. The first element of each
6297 // operand is the type and the second is a vector of offsets.
6298 for (const auto *operand : offsets_md->operands()) {
6299 const auto *pair = cast<MDTuple>(operand);
6300 auto *type =
6301 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6302 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6303 std::vector<uint32_t> offsets;
6304 for (const Metadata *offset_md : offset_vector->operands()) {
6305 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006306 offsets.push_back(static_cast<uint32_t>(
6307 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006308 }
6309 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6310 }
6311 }
6312
6313 if (auto *sizes_md =
6314 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6315 // Metadata is stored as key-value pair operands. The first element of each
6316 // operand is the type and the second is a triple of sizes: type size in
6317 // bits, store size and alloc size.
6318 for (const auto *operand : sizes_md->operands()) {
6319 const auto *pair = cast<MDTuple>(operand);
6320 auto *type =
6321 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6322 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6323 uint64_t type_size_in_bits =
6324 cast<ConstantInt>(
6325 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6326 ->getZExtValue();
6327 uint64_t type_store_size =
6328 cast<ConstantInt>(
6329 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6330 ->getZExtValue();
6331 uint64_t type_alloc_size =
6332 cast<ConstantInt>(
6333 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6334 ->getZExtValue();
6335 RemappedUBOTypeSizes.insert(std::make_pair(
6336 type, std::make_tuple(type_size_in_bits, type_store_size,
6337 type_alloc_size)));
6338 }
6339 }
6340}
6341
6342uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6343 const DataLayout &DL) {
6344 auto iter = RemappedUBOTypeSizes.find(type);
6345 if (iter != RemappedUBOTypeSizes.end()) {
6346 return std::get<0>(iter->second);
6347 }
6348
6349 return DL.getTypeSizeInBits(type);
6350}
6351
6352uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6353 auto iter = RemappedUBOTypeSizes.find(type);
6354 if (iter != RemappedUBOTypeSizes.end()) {
6355 return std::get<1>(iter->second);
6356 }
6357
6358 return DL.getTypeStoreSize(type);
6359}
6360
6361uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6362 auto iter = RemappedUBOTypeSizes.find(type);
6363 if (iter != RemappedUBOTypeSizes.end()) {
6364 return std::get<2>(iter->second);
6365 }
6366
6367 return DL.getTypeAllocSize(type);
6368}
alan-baker5b86ed72019-02-15 08:26:50 -05006369
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006370void SPIRVProducerPass::setVariablePointersCapabilities(
6371 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05006372 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6373 setVariablePointersStorageBuffer(true);
6374 } else {
6375 setVariablePointers(true);
6376 }
6377}
6378
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04006379Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05006380 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6381 return GetBasePointer(gep->getPointerOperand());
6382 }
6383
6384 // Conservatively return |v|.
6385 return v;
6386}
6387
6388bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6389 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6390 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6391 if (lhs_call->getCalledFunction()->getName().startswith(
6392 clspv::ResourceAccessorFunction()) &&
6393 rhs_call->getCalledFunction()->getName().startswith(
6394 clspv::ResourceAccessorFunction())) {
6395 // For resource accessors, match descriptor set and binding.
6396 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6397 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6398 return true;
6399 } else if (lhs_call->getCalledFunction()->getName().startswith(
6400 clspv::WorkgroupAccessorFunction()) &&
6401 rhs_call->getCalledFunction()->getName().startswith(
6402 clspv::WorkgroupAccessorFunction())) {
6403 // For workgroup resources, match spec id.
6404 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6405 return true;
6406 }
6407 }
6408 }
6409
6410 return false;
6411}
6412
6413bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6414 assert(inst->getType()->isPointerTy());
6415 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6416 spv::StorageClassStorageBuffer);
6417 const bool hack_undef = clspv::Option::HackUndef();
6418 if (auto *select = dyn_cast<SelectInst>(inst)) {
6419 auto *true_base = GetBasePointer(select->getTrueValue());
6420 auto *false_base = GetBasePointer(select->getFalseValue());
6421
6422 if (true_base == false_base)
6423 return true;
6424
6425 // If either the true or false operand is a null, then we satisfy the same
6426 // object constraint.
6427 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6428 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6429 return true;
6430 }
6431
6432 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6433 if (false_cst->isNullValue() ||
6434 (hack_undef && isa<UndefValue>(false_base)))
6435 return true;
6436 }
6437
6438 if (sameResource(true_base, false_base))
6439 return true;
6440 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6441 Value *value = nullptr;
6442 bool ok = true;
6443 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6444 auto *base = GetBasePointer(phi->getIncomingValue(i));
6445 // Null values satisfy the constraint of selecting of selecting from the
6446 // same object.
6447 if (!value) {
6448 if (auto *cst = dyn_cast<Constant>(base)) {
6449 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6450 value = base;
6451 } else {
6452 value = base;
6453 }
6454 } else if (base != value) {
6455 if (auto *base_cst = dyn_cast<Constant>(base)) {
6456 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6457 continue;
6458 }
6459
6460 if (sameResource(value, base))
6461 continue;
6462
6463 // Values don't represent the same base.
6464 ok = false;
6465 }
6466 }
6467
6468 return ok;
6469 }
6470
6471 // Conservatively return false.
6472 return false;
6473}
alan-bakere9308012019-03-15 10:25:13 -04006474
6475bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6476 if (!Arg.getType()->isPointerTy() ||
6477 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6478 // Only SSBOs need to be annotated as coherent.
6479 return false;
6480 }
6481
6482 DenseSet<Value *> visited;
6483 std::vector<Value *> stack;
6484 for (auto *U : Arg.getParent()->users()) {
6485 if (auto *call = dyn_cast<CallInst>(U)) {
6486 stack.push_back(call->getOperand(Arg.getArgNo()));
6487 }
6488 }
6489
6490 while (!stack.empty()) {
6491 Value *v = stack.back();
6492 stack.pop_back();
6493
6494 if (!visited.insert(v).second)
6495 continue;
6496
6497 auto *resource_call = dyn_cast<CallInst>(v);
6498 if (resource_call &&
6499 resource_call->getCalledFunction()->getName().startswith(
6500 clspv::ResourceAccessorFunction())) {
6501 // If this is a resource accessor function, check if the coherent operand
6502 // is set.
6503 const auto coherent =
6504 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6505 ->getZExtValue());
6506 if (coherent == 1)
6507 return true;
6508 } else if (auto *arg = dyn_cast<Argument>(v)) {
6509 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006510 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006511 if (auto *call = dyn_cast<CallInst>(U)) {
6512 stack.push_back(call->getOperand(arg->getArgNo()));
6513 }
6514 }
6515 } else if (auto *user = dyn_cast<User>(v)) {
6516 // If this is a user, traverse all operands that could lead to resource
6517 // variables.
6518 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6519 Value *operand = user->getOperand(i);
6520 if (operand->getType()->isPointerTy() &&
6521 operand->getType()->getPointerAddressSpace() ==
6522 clspv::AddressSpace::Global) {
6523 stack.push_back(operand);
6524 }
6525 }
6526 }
6527 }
6528
6529 // No coherent resource variables encountered.
6530 return false;
6531}