blob: 37e2fa9c167d5eaf848ab3d7a7cdd7fd6a581d06 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
alan-bakerb6b09dc2018-11-08 16:59:28 -050080const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040081
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500127 SPIRVOperandList(const SPIRVOperandList &other) = delete;
128 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500136 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500145 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
alan-bakerb6b09dc2018-11-08 16:59:28 -0500153SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500156SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500159SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500162SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
163SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400164 return new SPIRVOperand(LITERAL_STRING, str);
165}
David Netoc6f3ab22018-04-06 18:02:31 -0400166
David Neto22f144c2017-06-12 14:26:21 -0400167struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400168 // Create an instruction with an opcode and no result ID, and with the given
169 // operands. This computes its own word count.
170 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
171 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
172 Operands(Ops.begin(), Ops.end()) {
173 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400174 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400175 }
176 }
177 // Create an instruction with an opcode and a no-zero result ID, and
178 // with the given operands. This computes its own word count.
179 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400180 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400181 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
182 Operands(Ops.begin(), Ops.end()) {
183 if (ResID == 0) {
184 llvm_unreachable("Result ID of 0 was provided");
185 }
186 for (auto *operand : Ops) {
187 WordCount += operand->GetNumWords();
188 }
189 }
David Neto22f144c2017-06-12 14:26:21 -0400190
David Netoee2660d2018-06-28 16:31:29 -0400191 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400192 uint16_t getOpcode() const { return Opcode; }
193 uint32_t getResultID() const { return ResultID; }
194 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
195
196private:
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t Opcode;
199 uint32_t ResultID;
200 SmallVector<SPIRVOperand *, 4> Operands;
201};
202
203struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400204 typedef DenseMap<Type *, uint32_t> TypeMapType;
205 typedef UniqueVector<Type *> TypeList;
206 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400207 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400208 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
209 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400210 // A vector of tuples, each of which is:
211 // - the LLVM instruction that we will later generate SPIR-V code for
212 // - where the SPIR-V instruction should be inserted
213 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400214 typedef std::vector<
215 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
216 DeferredInstVecType;
217 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
218 GlobalConstFuncMapType;
219
David Neto44795152017-07-13 15:45:28 -0400220 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 raw_pwrite_stream &out,
222 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400223 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
224 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400225 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400226 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400228 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500229 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
230 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
231 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
232 }
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500286 bool hasVariablePointers() {
alan-baker5b86ed72019-02-15 08:26:50 -0500287 return HasVariablePointers;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 };
David Neto22f144c2017-06-12 14:26:21 -0400289 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
291 return samplerMap;
292 }
David Neto22f144c2017-06-12 14:26:21 -0400293 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
294 return GlobalConstFuncTypeMap;
295 }
296 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
297 return GlobalConstArgumentSet;
298 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500299 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400300
David Netoc6f3ab22018-04-06 18:02:31 -0400301 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500302 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
303 // *not* be converted to a storage buffer, replace each such global variable
304 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindGlobalConstVars(Module &M, const DataLayout &DL);
306 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
307 // ModuleOrderedResourceVars.
308 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400309 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400310 bool FindExtInst(Module &M);
311 void FindTypePerGlobalVar(GlobalVariable &GV);
312 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400313 void FindTypesForSamplerMap(Module &M);
314 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
316 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400317 void FindType(Type *Ty);
318 void FindConstantPerGlobalVar(GlobalVariable &GV);
319 void FindConstantPerFunc(Function &F);
320 void FindConstant(Value *V);
321 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400322 // Generates instructions for SPIR-V types corresponding to the LLVM types
323 // saved in the |Types| member. A type follows its subtypes. IDs are
324 // allocated sequentially starting with the current value of nextID, and
325 // with a type following its subtypes. Also updates nextID to just beyond
326 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400329 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400331 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400332 // Generate descriptor map entries for resource variables associated with
333 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500334 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400335 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400336 // Generate OpVariables for %clspv.resource.var.* calls.
337 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400338 void GenerateFuncPrologue(Function &F);
339 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400340 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400341 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
342 spv::Op GetSPIRVCastOpcode(Instruction &I);
343 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
344 void GenerateInstruction(Instruction &I);
345 void GenerateFuncEpilogue();
346 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500347 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400348 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400349 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
350 // have been created.
351 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400353 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400354 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400355 // Returns the GLSL extended instruction enum that the given function
356 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400357 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400358 // Returns the GLSL extended instruction enum indirectly used by the given
359 // function. That is, to implement the given function, we use an extended
360 // instruction plus one more instruction. If none, then returns the 0 value,
361 // i.e. GLSLstd4580Bad.
362 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
363 // Returns the single GLSL extended instruction used directly or
364 // indirectly by the given function call.
365 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400366 void PrintResID(SPIRVInstruction *Inst);
367 void PrintOpcode(SPIRVInstruction *Inst);
368 void PrintOperand(SPIRVOperand *Op);
369 void PrintCapability(SPIRVOperand *Op);
370 void PrintExtInst(SPIRVOperand *Op);
371 void PrintAddrModel(SPIRVOperand *Op);
372 void PrintMemModel(SPIRVOperand *Op);
373 void PrintExecModel(SPIRVOperand *Op);
374 void PrintExecMode(SPIRVOperand *Op);
375 void PrintSourceLanguage(SPIRVOperand *Op);
376 void PrintFuncCtrl(SPIRVOperand *Op);
377 void PrintStorageClass(SPIRVOperand *Op);
378 void PrintDecoration(SPIRVOperand *Op);
379 void PrintBuiltIn(SPIRVOperand *Op);
380 void PrintSelectionControl(SPIRVOperand *Op);
381 void PrintLoopControl(SPIRVOperand *Op);
382 void PrintDimensionality(SPIRVOperand *Op);
383 void PrintImageFormat(SPIRVOperand *Op);
384 void PrintMemoryAccess(SPIRVOperand *Op);
385 void PrintImageOperandsType(SPIRVOperand *Op);
386 void WriteSPIRVAssembly();
387 void WriteOneWord(uint32_t Word);
388 void WriteResultID(SPIRVInstruction *Inst);
389 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
390 void WriteOperand(SPIRVOperand *Op);
391 void WriteSPIRVBinary();
392
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500394 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400395
Alan Bakerfcda9482018-10-02 17:09:59 -0400396 // Populate UBO remapped type maps.
397 void PopulateUBOTypeMaps(Module &module);
398
399 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
400 // uses the internal map, otherwise it falls back on the data layout.
401 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
402 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
403 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
404
alan-baker5b86ed72019-02-15 08:26:50 -0500405 // Returns the base pointer of |v|.
406 Value *GetBasePointer(Value *v);
407
408 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
409 // |address_space|.
410 void setVariablePointersCapabilities(unsigned address_space);
411
412 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
413 // variable.
414 bool sameResource(Value *lhs, Value *rhs) const;
415
416 // Returns true if |inst| is phi or select that selects from the same
417 // structure (or null).
418 bool selectFromSameObject(Instruction *inst);
419
alan-bakere9308012019-03-15 10:25:13 -0400420 // Returns true if |Arg| is called with a coherent resource.
421 bool CalledWithCoherentResource(Argument &Arg);
422
David Neto22f144c2017-06-12 14:26:21 -0400423private:
424 static char ID;
David Neto44795152017-07-13 15:45:28 -0400425 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400426 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400427
428 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
429 // convert to other formats on demand?
430
431 // When emitting a C initialization list, the WriteSPIRVBinary method
432 // will actually write its words to this vector via binaryTempOut.
433 SmallVector<char, 100> binaryTempUnderlyingVector;
434 raw_svector_ostream binaryTempOut;
435
436 // Binary output writes to this stream, which might be |out| or
437 // |binaryTempOut|. It's the latter when we really want to write a C
438 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500439 raw_pwrite_stream* binaryOut;
440 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400441 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400442 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400443 uint64_t patchBoundOffset;
444 uint32_t nextID;
445
David Neto19a1bad2017-08-25 15:01:41 -0400446 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400447 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400448 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400449 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400450 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400451 TypeList Types;
452 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400453 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400454 ValueMapType ValueMap;
455 ValueMapType AllocatedValueMap;
456 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400457
David Neto22f144c2017-06-12 14:26:21 -0400458 EntryPointVecType EntryPointVec;
459 DeferredInstVecType DeferredInstVec;
460 ValueList EntryPointInterfacesVec;
461 uint32_t OpExtInstImportID;
462 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500463 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400464 bool HasVariablePointers;
465 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500466 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700467
468 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700469 // will map F's type to (G, index of the parameter), where in a first phase
470 // G is F's type. During FindTypePerFunc, G will be changed to F's type
471 // but replacing the pointer-to-constant parameter with
472 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700473 // TODO(dneto): This doesn't seem general enough? A function might have
474 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400475 GlobalConstFuncMapType GlobalConstFuncTypeMap;
476 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400477 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700478 // or array types, and which point into transparent memory (StorageBuffer
479 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400480 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700481 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400482
483 // This is truly ugly, but works around what look like driver bugs.
484 // For get_local_size, an earlier part of the flow has created a module-scope
485 // variable in Private address space to hold the value for the workgroup
486 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
487 // When this is present, save the IDs of the initializer value and variable
488 // in these two variables. We only ever do a vector load from it, and
489 // when we see one of those, substitute just the value of the intializer.
490 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700491 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400492 uint32_t WorkgroupSizeValueID;
493 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400494
David Neto862b7d82018-06-14 18:48:37 -0400495 // Bookkeeping for mapping kernel arguments to resource variables.
496 struct ResourceVarInfo {
497 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400498 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400499 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400500 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400501 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
502 const int index; // Index into ResourceVarInfoList
503 const unsigned descriptor_set;
504 const unsigned binding;
505 Function *const var_fn; // The @clspv.resource.var.* function.
506 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400507 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400508 const unsigned addr_space; // The LLVM address space
509 // The SPIR-V ID of the OpVariable. Not populated at construction time.
510 uint32_t var_id = 0;
511 };
512 // A list of resource var info. Each one correponds to a module-scope
513 // resource variable we will have to create. Resource var indices are
514 // indices into this vector.
515 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
516 // This is a vector of pointers of all the resource vars, but ordered by
517 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500518 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400519 // Map a function to the ordered list of resource variables it uses, one for
520 // each argument. If an argument does not use a resource variable, it
521 // will have a null pointer entry.
522 using FunctionToResourceVarsMapType =
523 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
524 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
525
526 // What LLVM types map to SPIR-V types needing layout? These are the
527 // arrays and structures supporting storage buffers and uniform buffers.
528 TypeList TypesNeedingLayout;
529 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
530 UniqueVector<StructType *> StructTypesNeedingBlock;
531 // For a call that represents a load from an opaque type (samplers, images),
532 // map it to the variable id it should load from.
533 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700534
Alan Baker202c8c72018-08-13 13:47:44 -0400535 // One larger than the maximum used SpecId for pointer-to-local arguments.
536 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400537 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500538 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400539 LocalArgList LocalArgs;
540 // Information about a pointer-to-local argument.
541 struct LocalArgInfo {
542 // The SPIR-V ID of the array variable.
543 uint32_t variable_id;
544 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500545 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400546 // The ID of the array type.
547 uint32_t array_size_id;
548 // The ID of the array type.
549 uint32_t array_type_id;
550 // The ID of the pointer to the array type.
551 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400552 // The specialization constant ID of the array size.
553 int spec_id;
554 };
Alan Baker202c8c72018-08-13 13:47:44 -0400555 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500556 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400557 // A mapping from SpecId to its LocalArgInfo.
558 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400559 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500560 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400561 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500562 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
563 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400564
565 // The ID of 32-bit integer zero constant. This is only valid after
566 // GenerateSPIRVConstants has run.
567 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400568};
569
570char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400571
alan-bakerb6b09dc2018-11-08 16:59:28 -0500572} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400573
574namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500575ModulePass *createSPIRVProducerPass(
576 raw_pwrite_stream &out,
577 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
578 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
579 bool outputCInitList) {
580 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
581 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400582}
David Netoc2c368d2017-06-30 16:50:17 -0400583} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400584
585bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400586 binaryOut = outputCInitList ? &binaryTempOut : &out;
587
David Neto257c3892018-04-11 13:19:45 -0400588 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
589
Alan Bakerfcda9482018-10-02 17:09:59 -0400590 PopulateUBOTypeMaps(module);
591
David Neto22f144c2017-06-12 14:26:21 -0400592 // SPIR-V always begins with its header information
593 outputHeader();
594
David Netoc6f3ab22018-04-06 18:02:31 -0400595 const DataLayout &DL = module.getDataLayout();
596
David Neto22f144c2017-06-12 14:26:21 -0400597 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400598 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400599
David Neto22f144c2017-06-12 14:26:21 -0400600 // Collect information on global variables too.
601 for (GlobalVariable &GV : module.globals()) {
602 // If the GV is one of our special __spirv_* variables, remove the
603 // initializer as it was only placed there to force LLVM to not throw the
604 // value away.
605 if (GV.getName().startswith("__spirv_")) {
606 GV.setInitializer(nullptr);
607 }
608
609 // Collect types' information from global variable.
610 FindTypePerGlobalVar(GV);
611
612 // Collect constant information from global variable.
613 FindConstantPerGlobalVar(GV);
614
615 // If the variable is an input, entry points need to know about it.
616 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400617 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400618 }
619 }
620
621 // If there are extended instructions, generate OpExtInstImport.
622 if (FindExtInst(module)) {
623 GenerateExtInstImport();
624 }
625
626 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400627 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400628
629 // Generate SPIRV constants.
630 GenerateSPIRVConstants();
631
632 // If we have a sampler map, we might have literal samplers to generate.
633 if (0 < getSamplerMap().size()) {
634 GenerateSamplers(module);
635 }
636
637 // Generate SPIRV variables.
638 for (GlobalVariable &GV : module.globals()) {
639 GenerateGlobalVar(GV);
640 }
David Neto862b7d82018-06-14 18:48:37 -0400641 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400642 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400643
644 // Generate SPIRV instructions for each function.
645 for (Function &F : module) {
646 if (F.isDeclaration()) {
647 continue;
648 }
649
David Neto862b7d82018-06-14 18:48:37 -0400650 GenerateDescriptorMapInfo(DL, F);
651
David Neto22f144c2017-06-12 14:26:21 -0400652 // Generate Function Prologue.
653 GenerateFuncPrologue(F);
654
655 // Generate SPIRV instructions for function body.
656 GenerateFuncBody(F);
657
658 // Generate Function Epilogue.
659 GenerateFuncEpilogue();
660 }
661
662 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400663 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400664
665 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400666 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400667
668 if (outputAsm) {
669 WriteSPIRVAssembly();
670 } else {
671 WriteSPIRVBinary();
672 }
673
674 // We need to patch the SPIR-V header to set bound correctly.
675 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400676
677 if (outputCInitList) {
678 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400679 std::ostringstream os;
680
David Neto57fb0b92017-08-04 15:35:09 -0400681 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400682 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400683 os << ",\n";
684 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400685 first = false;
686 };
687
688 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400689 const std::string str(binaryTempOut.str());
690 for (unsigned i = 0; i < str.size(); i += 4) {
691 const uint32_t a = static_cast<unsigned char>(str[i]);
692 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
693 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
694 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
695 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400696 }
697 os << "}\n";
698 out << os.str();
699 }
700
David Neto22f144c2017-06-12 14:26:21 -0400701 return false;
702}
703
704void SPIRVProducerPass::outputHeader() {
705 if (outputAsm) {
706 // for ASM output the header goes into 5 comments at the beginning of the
707 // file
708 out << "; SPIR-V\n";
709
710 // the major version number is in the 2nd highest byte
711 const uint32_t major = (spv::Version >> 16) & 0xFF;
712
713 // the minor version number is in the 2nd lowest byte
714 const uint32_t minor = (spv::Version >> 8) & 0xFF;
715 out << "; Version: " << major << "." << minor << "\n";
716
717 // use Codeplay's vendor ID
718 out << "; Generator: Codeplay; 0\n";
719
720 out << "; Bound: ";
721
722 // we record where we need to come back to and patch in the bound value
723 patchBoundOffset = out.tell();
724
725 // output one space per digit for the max size of a 32 bit unsigned integer
726 // (which is the maximum ID we could possibly be using)
727 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
728 out << " ";
729 }
730
731 out << "\n";
732
733 out << "; Schema: 0\n";
734 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400735 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500736 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400737 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500738 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400739
740 // use Codeplay's vendor ID
741 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400742 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400743
744 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400745 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400746
747 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400748 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400749
750 // output the schema (reserved for use and must be 0)
751 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400752 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400753 }
754}
755
756void SPIRVProducerPass::patchHeader() {
757 if (outputAsm) {
758 // get the string representation of the max bound used (nextID will be the
759 // max ID used)
760 auto asString = std::to_string(nextID);
761 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
762 } else {
763 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400764 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
765 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400766 }
767}
768
David Netoc6f3ab22018-04-06 18:02:31 -0400769void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400770 // This function generates LLVM IR for function such as global variable for
771 // argument, constant and pointer type for argument access. These information
772 // is artificial one because we need Vulkan SPIR-V output. This function is
773 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400774 LLVMContext &Context = M.getContext();
775
David Neto862b7d82018-06-14 18:48:37 -0400776 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400777
David Neto862b7d82018-06-14 18:48:37 -0400778 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400779
780 bool HasWorkGroupBuiltin = false;
781 for (GlobalVariable &GV : M.globals()) {
782 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
783 if (spv::BuiltInWorkgroupSize == BuiltinType) {
784 HasWorkGroupBuiltin = true;
785 }
786 }
787
David Neto862b7d82018-06-14 18:48:37 -0400788 FindTypesForSamplerMap(M);
789 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400790 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400791
David Neto862b7d82018-06-14 18:48:37 -0400792 // These function calls need a <2 x i32> as an intermediate result but not
793 // the final result.
794 std::unordered_set<std::string> NeedsIVec2{
795 "_Z15get_image_width14ocl_image2d_ro",
796 "_Z15get_image_width14ocl_image2d_wo",
797 "_Z16get_image_height14ocl_image2d_ro",
798 "_Z16get_image_height14ocl_image2d_wo",
799 };
800
David Neto22f144c2017-06-12 14:26:21 -0400801 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000802 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400803 continue;
804 }
805
806 for (BasicBlock &BB : F) {
807 for (Instruction &I : BB) {
808 if (I.getOpcode() == Instruction::ZExt ||
809 I.getOpcode() == Instruction::SExt ||
810 I.getOpcode() == Instruction::UIToFP) {
811 // If there is zext with i1 type, it will be changed to OpSelect. The
812 // OpSelect needs constant 0 and 1 so the constants are added here.
813
814 auto OpTy = I.getOperand(0)->getType();
815
Kévin Petit24272b62018-10-18 19:16:12 +0000816 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400817 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400818 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000819 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400820 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400821 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000822 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400823 } else {
824 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
825 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
826 }
827 }
828 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400829 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400830
831 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400832 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400833 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400834 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400835 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
836 TypeMapType &OpImageTypeMap = getImageTypeMap();
837 Type *ImageTy =
838 Call->getArgOperand(0)->getType()->getPointerElementType();
839 OpImageTypeMap[ImageTy] = 0;
840
841 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
842 }
David Neto5c22a252018-03-15 16:07:41 -0400843
David Neto862b7d82018-06-14 18:48:37 -0400844 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400845 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
846 }
David Neto22f144c2017-06-12 14:26:21 -0400847 }
848 }
849 }
850
Kévin Petitabef4522019-03-27 13:08:01 +0000851 // More things to do on kernel functions
852 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
853 if (const MDNode *MD =
854 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
855 // We generate constants if the WorkgroupSize builtin is being used.
856 if (HasWorkGroupBuiltin) {
857 // Collect constant information for work group size.
858 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
859 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
860 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400861 }
862 }
863 }
864
865 if (M.getTypeByName("opencl.image2d_ro_t") ||
866 M.getTypeByName("opencl.image2d_wo_t") ||
867 M.getTypeByName("opencl.image3d_ro_t") ||
868 M.getTypeByName("opencl.image3d_wo_t")) {
869 // Assume Image type's sampled type is float type.
870 FindType(Type::getFloatTy(Context));
871 }
872
873 // Collect types' information from function.
874 FindTypePerFunc(F);
875
876 // Collect constant information from function.
877 FindConstantPerFunc(F);
878 }
879}
880
David Neto862b7d82018-06-14 18:48:37 -0400881void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
882 SmallVector<GlobalVariable *, 8> GVList;
883 SmallVector<GlobalVariable *, 8> DeadGVList;
884 for (GlobalVariable &GV : M.globals()) {
885 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
886 if (GV.use_empty()) {
887 DeadGVList.push_back(&GV);
888 } else {
889 GVList.push_back(&GV);
890 }
891 }
892 }
893
894 // Remove dead global __constant variables.
895 for (auto GV : DeadGVList) {
896 GV->eraseFromParent();
897 }
898 DeadGVList.clear();
899
900 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
901 // For now, we only support a single storage buffer.
902 if (GVList.size() > 0) {
903 assert(GVList.size() == 1);
904 const auto *GV = GVList[0];
905 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400906 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400907 const size_t kConstantMaxSize = 65536;
908 if (constants_byte_size > kConstantMaxSize) {
909 outs() << "Max __constant capacity of " << kConstantMaxSize
910 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
911 llvm_unreachable("Max __constant capacity exceeded");
912 }
913 }
914 } else {
915 // Change global constant variable's address space to ModuleScopePrivate.
916 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
917 for (auto GV : GVList) {
918 // Create new gv with ModuleScopePrivate address space.
919 Type *NewGVTy = GV->getType()->getPointerElementType();
920 GlobalVariable *NewGV = new GlobalVariable(
921 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
922 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
923 NewGV->takeName(GV);
924
925 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
926 SmallVector<User *, 8> CandidateUsers;
927
928 auto record_called_function_type_as_user =
929 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
930 // Find argument index.
931 unsigned index = 0;
932 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
933 if (gv == call->getOperand(i)) {
934 // TODO(dneto): Should we break here?
935 index = i;
936 }
937 }
938
939 // Record function type with global constant.
940 GlobalConstFuncTyMap[call->getFunctionType()] =
941 std::make_pair(call->getFunctionType(), index);
942 };
943
944 for (User *GVU : GVUsers) {
945 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
946 record_called_function_type_as_user(GV, Call);
947 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
948 // Check GEP users.
949 for (User *GEPU : GEP->users()) {
950 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
951 record_called_function_type_as_user(GEP, GEPCall);
952 }
953 }
954 }
955
956 CandidateUsers.push_back(GVU);
957 }
958
959 for (User *U : CandidateUsers) {
960 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500961 if (!isa<Constant>(U)) {
962 // #254: Can't change operands of a constant, but this shouldn't be
963 // something that sticks around in the module.
964 U->replaceUsesOfWith(GV, NewGV);
965 }
David Neto862b7d82018-06-14 18:48:37 -0400966 }
967
968 // Delete original gv.
969 GV->eraseFromParent();
970 }
971 }
972}
973
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100974void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400975 ResourceVarInfoList.clear();
976 FunctionToResourceVarsMap.clear();
977 ModuleOrderedResourceVars.reset();
978 // Normally, there is one resource variable per clspv.resource.var.*
979 // function, since that is unique'd by arg type and index. By design,
980 // we can share these resource variables across kernels because all
981 // kernels use the same descriptor set.
982 //
983 // But if the user requested distinct descriptor sets per kernel, then
984 // the descriptor allocator has made different (set,binding) pairs for
985 // the same (type,arg_index) pair. Since we can decorate a resource
986 // variable with only exactly one DescriptorSet and Binding, we are
987 // forced in this case to make distinct resource variables whenever
988 // the same clspv.reource.var.X function is seen with disintct
989 // (set,binding) values.
990 const bool always_distinct_sets =
991 clspv::Option::DistinctKernelDescriptorSets();
992 for (Function &F : M) {
993 // Rely on the fact the resource var functions have a stable ordering
994 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400995 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400996 // Find all calls to this function with distinct set and binding pairs.
997 // Save them in ResourceVarInfoList.
998
999 // Determine uniqueness of the (set,binding) pairs only withing this
1000 // one resource-var builtin function.
1001 using SetAndBinding = std::pair<unsigned, unsigned>;
1002 // Maps set and binding to the resource var info.
1003 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1004 bool first_use = true;
1005 for (auto &U : F.uses()) {
1006 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1007 const auto set = unsigned(
1008 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1009 const auto binding = unsigned(
1010 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1011 const auto arg_kind = clspv::ArgKind(
1012 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1013 const auto arg_index = unsigned(
1014 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -04001015 const auto coherent = unsigned(
1016 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04001017
1018 // Find or make the resource var info for this combination.
1019 ResourceVarInfo *rv = nullptr;
1020 if (always_distinct_sets) {
1021 // Make a new resource var any time we see a different
1022 // (set,binding) pair.
1023 SetAndBinding key{set, binding};
1024 auto where = set_and_binding_map.find(key);
1025 if (where == set_and_binding_map.end()) {
1026 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001027 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001028 ResourceVarInfoList.emplace_back(rv);
1029 set_and_binding_map[key] = rv;
1030 } else {
1031 rv = where->second;
1032 }
1033 } else {
1034 // The default is to make exactly one resource for each
1035 // clspv.resource.var.* function.
1036 if (first_use) {
1037 first_use = false;
1038 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -04001039 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -04001040 ResourceVarInfoList.emplace_back(rv);
1041 } else {
1042 rv = ResourceVarInfoList.back().get();
1043 }
1044 }
1045
1046 // Now populate FunctionToResourceVarsMap.
1047 auto &mapping =
1048 FunctionToResourceVarsMap[call->getParent()->getParent()];
1049 while (mapping.size() <= arg_index) {
1050 mapping.push_back(nullptr);
1051 }
1052 mapping[arg_index] = rv;
1053 }
1054 }
1055 }
1056 }
1057
1058 // Populate ModuleOrderedResourceVars.
1059 for (Function &F : M) {
1060 auto where = FunctionToResourceVarsMap.find(&F);
1061 if (where != FunctionToResourceVarsMap.end()) {
1062 for (auto &rv : where->second) {
1063 if (rv != nullptr) {
1064 ModuleOrderedResourceVars.insert(rv);
1065 }
1066 }
1067 }
1068 }
1069 if (ShowResourceVars) {
1070 for (auto *info : ModuleOrderedResourceVars) {
1071 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1072 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1073 << "\n";
1074 }
1075 }
1076}
1077
David Neto22f144c2017-06-12 14:26:21 -04001078bool SPIRVProducerPass::FindExtInst(Module &M) {
1079 LLVMContext &Context = M.getContext();
1080 bool HasExtInst = false;
1081
1082 for (Function &F : M) {
1083 for (BasicBlock &BB : F) {
1084 for (Instruction &I : BB) {
1085 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1086 Function *Callee = Call->getCalledFunction();
1087 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001088 auto callee_name = Callee->getName();
1089 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1090 const glsl::ExtInst IndirectEInst =
1091 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001092
David Neto3fbb4072017-10-16 11:28:14 -04001093 HasExtInst |=
1094 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1095
1096 if (IndirectEInst) {
1097 // Register extra constants if needed.
1098
1099 // Registers a type and constant for computing the result of the
1100 // given instruction. If the result of the instruction is a vector,
1101 // then make a splat vector constant with the same number of
1102 // elements.
1103 auto register_constant = [this, &I](Constant *constant) {
1104 FindType(constant->getType());
1105 FindConstant(constant);
1106 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1107 // Register the splat vector of the value with the same
1108 // width as the result of the instruction.
1109 auto *vec_constant = ConstantVector::getSplat(
1110 static_cast<unsigned>(vectorTy->getNumElements()),
1111 constant);
1112 FindConstant(vec_constant);
1113 FindType(vec_constant->getType());
1114 }
1115 };
1116 switch (IndirectEInst) {
1117 case glsl::ExtInstFindUMsb:
1118 // clz needs OpExtInst and OpISub with constant 31, or splat
1119 // vector of 31. Add it to the constant list here.
1120 register_constant(
1121 ConstantInt::get(Type::getInt32Ty(Context), 31));
1122 break;
1123 case glsl::ExtInstAcos:
1124 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001125 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001126 case glsl::ExtInstAtan2:
1127 // We need 1/pi for acospi, asinpi, atan2pi.
1128 register_constant(
1129 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1130 break;
1131 default:
1132 assert(false && "internally inconsistent");
1133 }
David Neto22f144c2017-06-12 14:26:21 -04001134 }
1135 }
1136 }
1137 }
1138 }
1139
1140 return HasExtInst;
1141}
1142
1143void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1144 // Investigate global variable's type.
1145 FindType(GV.getType());
1146}
1147
1148void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1149 // Investigate function's type.
1150 FunctionType *FTy = F.getFunctionType();
1151
1152 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1153 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001154 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001155 if (GlobalConstFuncTyMap.count(FTy)) {
1156 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1157 SmallVector<Type *, 4> NewFuncParamTys;
1158 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1159 Type *ParamTy = FTy->getParamType(i);
1160 if (i == GVCstArgIdx) {
1161 Type *EleTy = ParamTy->getPointerElementType();
1162 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1163 }
1164
1165 NewFuncParamTys.push_back(ParamTy);
1166 }
1167
1168 FunctionType *NewFTy =
1169 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1170 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1171 FTy = NewFTy;
1172 }
1173
1174 FindType(FTy);
1175 } else {
1176 // As kernel functions do not have parameters, create new function type and
1177 // add it to type map.
1178 SmallVector<Type *, 4> NewFuncParamTys;
1179 FunctionType *NewFTy =
1180 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1181 FindType(NewFTy);
1182 }
1183
1184 // Investigate instructions' type in function body.
1185 for (BasicBlock &BB : F) {
1186 for (Instruction &I : BB) {
1187 if (isa<ShuffleVectorInst>(I)) {
1188 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1189 // Ignore type for mask of shuffle vector instruction.
1190 if (i == 2) {
1191 continue;
1192 }
1193
1194 Value *Op = I.getOperand(i);
1195 if (!isa<MetadataAsValue>(Op)) {
1196 FindType(Op->getType());
1197 }
1198 }
1199
1200 FindType(I.getType());
1201 continue;
1202 }
1203
David Neto862b7d82018-06-14 18:48:37 -04001204 CallInst *Call = dyn_cast<CallInst>(&I);
1205
1206 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001207 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001208 // This is a fake call representing access to a resource variable.
1209 // We handle that elsewhere.
1210 continue;
1211 }
1212
Alan Baker202c8c72018-08-13 13:47:44 -04001213 if (Call && Call->getCalledFunction()->getName().startswith(
1214 clspv::WorkgroupAccessorFunction())) {
1215 // This is a fake call representing access to a workgroup variable.
1216 // We handle that elsewhere.
1217 continue;
1218 }
1219
David Neto22f144c2017-06-12 14:26:21 -04001220 // Work through the operands of the instruction.
1221 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1222 Value *const Op = I.getOperand(i);
1223 // If any of the operands is a constant, find the type!
1224 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1225 FindType(Op->getType());
1226 }
1227 }
1228
1229 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001230 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001231 // Avoid to check call instruction's type.
1232 break;
1233 }
Alan Baker202c8c72018-08-13 13:47:44 -04001234 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1235 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1236 clspv::WorkgroupAccessorFunction())) {
1237 // This is a fake call representing access to a workgroup variable.
1238 // We handle that elsewhere.
1239 continue;
1240 }
1241 }
David Neto22f144c2017-06-12 14:26:21 -04001242 if (!isa<MetadataAsValue>(&Op)) {
1243 FindType(Op->getType());
1244 continue;
1245 }
1246 }
1247
David Neto22f144c2017-06-12 14:26:21 -04001248 // We don't want to track the type of this call as we are going to replace
1249 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001250 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001251 Call->getCalledFunction()->getName())) {
1252 continue;
1253 }
1254
1255 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1256 // If gep's base operand has ModuleScopePrivate address space, make gep
1257 // return ModuleScopePrivate address space.
1258 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1259 // Add pointer type with private address space for global constant to
1260 // type list.
1261 Type *EleTy = I.getType()->getPointerElementType();
1262 Type *NewPTy =
1263 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1264
1265 FindType(NewPTy);
1266 continue;
1267 }
1268 }
1269
1270 FindType(I.getType());
1271 }
1272 }
1273}
1274
David Neto862b7d82018-06-14 18:48:37 -04001275void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1276 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001277 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001278 0 < getSamplerMap().size()) {
1279 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1280 if (!SamplerStructTy) {
1281 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1282 }
1283
1284 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1285
1286 FindType(SamplerTy);
1287 }
1288}
1289
1290void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1291 // Record types so they are generated.
1292 TypesNeedingLayout.reset();
1293 StructTypesNeedingBlock.reset();
1294
1295 // To match older clspv codegen, generate the float type first if required
1296 // for images.
1297 for (const auto *info : ModuleOrderedResourceVars) {
1298 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1299 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1300 // We need "float" for the sampled component type.
1301 FindType(Type::getFloatTy(M.getContext()));
1302 // We only need to find it once.
1303 break;
1304 }
1305 }
1306
1307 for (const auto *info : ModuleOrderedResourceVars) {
1308 Type *type = info->var_fn->getReturnType();
1309
1310 switch (info->arg_kind) {
1311 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001312 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001313 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1314 StructTypesNeedingBlock.insert(sty);
1315 } else {
1316 errs() << *type << "\n";
1317 llvm_unreachable("Buffer arguments must map to structures!");
1318 }
1319 break;
1320 case clspv::ArgKind::Pod:
1321 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1322 StructTypesNeedingBlock.insert(sty);
1323 } else {
1324 errs() << *type << "\n";
1325 llvm_unreachable("POD arguments must map to structures!");
1326 }
1327 break;
1328 case clspv::ArgKind::ReadOnlyImage:
1329 case clspv::ArgKind::WriteOnlyImage:
1330 case clspv::ArgKind::Sampler:
1331 // Sampler and image types map to the pointee type but
1332 // in the uniform constant address space.
1333 type = PointerType::get(type->getPointerElementType(),
1334 clspv::AddressSpace::UniformConstant);
1335 break;
1336 default:
1337 break;
1338 }
1339
1340 // The converted type is the type of the OpVariable we will generate.
1341 // If the pointee type is an array of size zero, FindType will convert it
1342 // to a runtime array.
1343 FindType(type);
1344 }
1345
1346 // Traverse the arrays and structures underneath each Block, and
1347 // mark them as needing layout.
1348 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1349 StructTypesNeedingBlock.end());
1350 while (!work_list.empty()) {
1351 Type *type = work_list.back();
1352 work_list.pop_back();
1353 TypesNeedingLayout.insert(type);
1354 switch (type->getTypeID()) {
1355 case Type::ArrayTyID:
1356 work_list.push_back(type->getArrayElementType());
1357 if (!Hack_generate_runtime_array_stride_early) {
1358 // Remember this array type for deferred decoration.
1359 TypesNeedingArrayStride.insert(type);
1360 }
1361 break;
1362 case Type::StructTyID:
1363 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1364 work_list.push_back(elem_ty);
1365 }
1366 default:
1367 // This type and its contained types don't get layout.
1368 break;
1369 }
1370 }
1371}
1372
Alan Baker202c8c72018-08-13 13:47:44 -04001373void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1374 // The SpecId assignment for pointer-to-local arguments is recorded in
1375 // module-level metadata. Translate that information into local argument
1376 // information.
1377 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001378 if (!nmd)
1379 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001380 for (auto operand : nmd->operands()) {
1381 MDTuple *tuple = cast<MDTuple>(operand);
1382 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1383 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001384 ConstantAsMetadata *arg_index_md =
1385 cast<ConstantAsMetadata>(tuple->getOperand(1));
1386 int arg_index = static_cast<int>(
1387 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1388 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001389
1390 ConstantAsMetadata *spec_id_md =
1391 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001392 int spec_id = static_cast<int>(
1393 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001394
1395 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1396 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001397 if (LocalSpecIdInfoMap.count(spec_id))
1398 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001399
1400 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1401 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1402 nextID + 1, nextID + 2,
1403 nextID + 3, spec_id};
1404 LocalSpecIdInfoMap[spec_id] = info;
1405 nextID += 4;
1406
1407 // Ensure the types necessary for this argument get generated.
1408 Type *IdxTy = Type::getInt32Ty(M.getContext());
1409 FindConstant(ConstantInt::get(IdxTy, 0));
1410 FindType(IdxTy);
1411 FindType(arg->getType());
1412 }
1413}
1414
David Neto22f144c2017-06-12 14:26:21 -04001415void SPIRVProducerPass::FindType(Type *Ty) {
1416 TypeList &TyList = getTypeList();
1417
1418 if (0 != TyList.idFor(Ty)) {
1419 return;
1420 }
1421
1422 if (Ty->isPointerTy()) {
1423 auto AddrSpace = Ty->getPointerAddressSpace();
1424 if ((AddressSpace::Constant == AddrSpace) ||
1425 (AddressSpace::Global == AddrSpace)) {
1426 auto PointeeTy = Ty->getPointerElementType();
1427
1428 if (PointeeTy->isStructTy() &&
1429 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1430 FindType(PointeeTy);
1431 auto ActualPointerTy =
1432 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1433 FindType(ActualPointerTy);
1434 return;
1435 }
1436 }
1437 }
1438
David Neto862b7d82018-06-14 18:48:37 -04001439 // By convention, LLVM array type with 0 elements will map to
1440 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1441 // has a constant number of elements. We need to support type of the
1442 // constant.
1443 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1444 if (arrayTy->getNumElements() > 0) {
1445 LLVMContext &Context = Ty->getContext();
1446 FindType(Type::getInt32Ty(Context));
1447 }
David Neto22f144c2017-06-12 14:26:21 -04001448 }
1449
1450 for (Type *SubTy : Ty->subtypes()) {
1451 FindType(SubTy);
1452 }
1453
1454 TyList.insert(Ty);
1455}
1456
1457void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1458 // If the global variable has a (non undef) initializer.
1459 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001460 // Generate the constant if it's not the initializer to a module scope
1461 // constant that we will expect in a storage buffer.
1462 const bool module_scope_constant_external_init =
1463 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1464 clspv::Option::ModuleConstantsInStorageBuffer();
1465 if (!module_scope_constant_external_init) {
1466 FindConstant(GV.getInitializer());
1467 }
David Neto22f144c2017-06-12 14:26:21 -04001468 }
1469}
1470
1471void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1472 // Investigate constants in function body.
1473 for (BasicBlock &BB : F) {
1474 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001475 if (auto *call = dyn_cast<CallInst>(&I)) {
1476 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001477 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001478 // We've handled these constants elsewhere, so skip it.
1479 continue;
1480 }
Alan Baker202c8c72018-08-13 13:47:44 -04001481 if (name.startswith(clspv::ResourceAccessorFunction())) {
1482 continue;
1483 }
1484 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001485 continue;
1486 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001487 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1488 // Skip the first operand that has the SPIR-V Opcode
1489 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1490 if (isa<Constant>(I.getOperand(i)) &&
1491 !isa<GlobalValue>(I.getOperand(i))) {
1492 FindConstant(I.getOperand(i));
1493 }
1494 }
1495 continue;
1496 }
David Neto22f144c2017-06-12 14:26:21 -04001497 }
1498
1499 if (isa<AllocaInst>(I)) {
1500 // Alloca instruction has constant for the number of element. Ignore it.
1501 continue;
1502 } else if (isa<ShuffleVectorInst>(I)) {
1503 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1504 // Ignore constant for mask of shuffle vector instruction.
1505 if (i == 2) {
1506 continue;
1507 }
1508
1509 if (isa<Constant>(I.getOperand(i)) &&
1510 !isa<GlobalValue>(I.getOperand(i))) {
1511 FindConstant(I.getOperand(i));
1512 }
1513 }
1514
1515 continue;
1516 } else if (isa<InsertElementInst>(I)) {
1517 // Handle InsertElement with <4 x i8> specially.
1518 Type *CompositeTy = I.getOperand(0)->getType();
1519 if (is4xi8vec(CompositeTy)) {
1520 LLVMContext &Context = CompositeTy->getContext();
1521 if (isa<Constant>(I.getOperand(0))) {
1522 FindConstant(I.getOperand(0));
1523 }
1524
1525 if (isa<Constant>(I.getOperand(1))) {
1526 FindConstant(I.getOperand(1));
1527 }
1528
1529 // Add mask constant 0xFF.
1530 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1531 FindConstant(CstFF);
1532
1533 // Add shift amount constant.
1534 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1535 uint64_t Idx = CI->getZExtValue();
1536 Constant *CstShiftAmount =
1537 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1538 FindConstant(CstShiftAmount);
1539 }
1540
1541 continue;
1542 }
1543
1544 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1545 // Ignore constant for index of InsertElement instruction.
1546 if (i == 2) {
1547 continue;
1548 }
1549
1550 if (isa<Constant>(I.getOperand(i)) &&
1551 !isa<GlobalValue>(I.getOperand(i))) {
1552 FindConstant(I.getOperand(i));
1553 }
1554 }
1555
1556 continue;
1557 } else if (isa<ExtractElementInst>(I)) {
1558 // Handle ExtractElement with <4 x i8> specially.
1559 Type *CompositeTy = I.getOperand(0)->getType();
1560 if (is4xi8vec(CompositeTy)) {
1561 LLVMContext &Context = CompositeTy->getContext();
1562 if (isa<Constant>(I.getOperand(0))) {
1563 FindConstant(I.getOperand(0));
1564 }
1565
1566 // Add mask constant 0xFF.
1567 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1568 FindConstant(CstFF);
1569
1570 // Add shift amount constant.
1571 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1572 uint64_t Idx = CI->getZExtValue();
1573 Constant *CstShiftAmount =
1574 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1575 FindConstant(CstShiftAmount);
1576 } else {
1577 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1578 FindConstant(Cst8);
1579 }
1580
1581 continue;
1582 }
1583
1584 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1585 // Ignore constant for index of ExtractElement instruction.
1586 if (i == 1) {
1587 continue;
1588 }
1589
1590 if (isa<Constant>(I.getOperand(i)) &&
1591 !isa<GlobalValue>(I.getOperand(i))) {
1592 FindConstant(I.getOperand(i));
1593 }
1594 }
1595
1596 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001597 } else if ((Instruction::Xor == I.getOpcode()) &&
1598 I.getType()->isIntegerTy(1)) {
1599 // We special case for Xor where the type is i1 and one of the arguments
1600 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1601 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001602 bool foundConstantTrue = false;
1603 for (Use &Op : I.operands()) {
1604 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1605 auto CI = cast<ConstantInt>(Op);
1606
1607 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001608 // If we already found the true constant, we might (probably only
1609 // on -O0) have an OpLogicalNot which is taking a constant
1610 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001611 FindConstant(Op);
1612 } else {
1613 foundConstantTrue = true;
1614 }
1615 }
1616 }
1617
1618 continue;
David Netod2de94a2017-08-28 17:27:47 -04001619 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001620 // Special case if i8 is not generally handled.
1621 if (!clspv::Option::Int8Support()) {
1622 // For truncation to i8 we mask against 255.
1623 Type *ToTy = I.getType();
1624 if (8u == ToTy->getPrimitiveSizeInBits()) {
1625 LLVMContext &Context = ToTy->getContext();
1626 Constant *Cst255 =
1627 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1628 FindConstant(Cst255);
1629 }
David Netod2de94a2017-08-28 17:27:47 -04001630 }
Neil Henning39672102017-09-29 14:33:13 +01001631 } else if (isa<AtomicRMWInst>(I)) {
1632 LLVMContext &Context = I.getContext();
1633
1634 FindConstant(
1635 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1636 FindConstant(ConstantInt::get(
1637 Type::getInt32Ty(Context),
1638 spv::MemorySemanticsUniformMemoryMask |
1639 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001640 }
1641
1642 for (Use &Op : I.operands()) {
1643 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1644 FindConstant(Op);
1645 }
1646 }
1647 }
1648 }
1649}
1650
1651void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001652 ValueList &CstList = getConstantList();
1653
David Netofb9a7972017-08-25 17:08:24 -04001654 // If V is already tracked, ignore it.
1655 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001656 return;
1657 }
1658
David Neto862b7d82018-06-14 18:48:37 -04001659 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1660 return;
1661 }
1662
David Neto22f144c2017-06-12 14:26:21 -04001663 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001664 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001665
1666 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001667 if (is4xi8vec(CstTy)) {
1668 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001669 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001670 }
1671 }
1672
1673 if (Cst->getNumOperands()) {
1674 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1675 ++I) {
1676 FindConstant(*I);
1677 }
1678
David Netofb9a7972017-08-25 17:08:24 -04001679 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001680 return;
1681 } else if (const ConstantDataSequential *CDS =
1682 dyn_cast<ConstantDataSequential>(Cst)) {
1683 // Add constants for each element to constant list.
1684 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1685 Constant *EleCst = CDS->getElementAsConstant(i);
1686 FindConstant(EleCst);
1687 }
1688 }
1689
1690 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001691 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001692 }
1693}
1694
1695spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1696 switch (AddrSpace) {
1697 default:
1698 llvm_unreachable("Unsupported OpenCL address space");
1699 case AddressSpace::Private:
1700 return spv::StorageClassFunction;
1701 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001702 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001703 case AddressSpace::Constant:
1704 return clspv::Option::ConstantArgsInUniformBuffer()
1705 ? spv::StorageClassUniform
1706 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001707 case AddressSpace::Input:
1708 return spv::StorageClassInput;
1709 case AddressSpace::Local:
1710 return spv::StorageClassWorkgroup;
1711 case AddressSpace::UniformConstant:
1712 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001713 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001714 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001715 case AddressSpace::ModuleScopePrivate:
1716 return spv::StorageClassPrivate;
1717 }
1718}
1719
David Neto862b7d82018-06-14 18:48:37 -04001720spv::StorageClass
1721SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1722 switch (arg_kind) {
1723 case clspv::ArgKind::Buffer:
1724 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001725 case clspv::ArgKind::BufferUBO:
1726 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001727 case clspv::ArgKind::Pod:
1728 return clspv::Option::PodArgsInUniformBuffer()
1729 ? spv::StorageClassUniform
1730 : spv::StorageClassStorageBuffer;
1731 case clspv::ArgKind::Local:
1732 return spv::StorageClassWorkgroup;
1733 case clspv::ArgKind::ReadOnlyImage:
1734 case clspv::ArgKind::WriteOnlyImage:
1735 case clspv::ArgKind::Sampler:
1736 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001737 default:
1738 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001739 }
1740}
1741
David Neto22f144c2017-06-12 14:26:21 -04001742spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1743 return StringSwitch<spv::BuiltIn>(Name)
1744 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1745 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1746 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1747 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1748 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1749 .Default(spv::BuiltInMax);
1750}
1751
1752void SPIRVProducerPass::GenerateExtInstImport() {
1753 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1754 uint32_t &ExtInstImportID = getOpExtInstImportID();
1755
1756 //
1757 // Generate OpExtInstImport.
1758 //
1759 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001760 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001761 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1762 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001763}
1764
alan-bakerb6b09dc2018-11-08 16:59:28 -05001765void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1766 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001767 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1768 ValueMapType &VMap = getValueMap();
1769 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001770 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001771
1772 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1773 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1774 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1775
1776 for (Type *Ty : getTypeList()) {
1777 // Update TypeMap with nextID for reference later.
1778 TypeMap[Ty] = nextID;
1779
1780 switch (Ty->getTypeID()) {
1781 default: {
1782 Ty->print(errs());
1783 llvm_unreachable("Unsupported type???");
1784 break;
1785 }
1786 case Type::MetadataTyID:
1787 case Type::LabelTyID: {
1788 // Ignore these types.
1789 break;
1790 }
1791 case Type::PointerTyID: {
1792 PointerType *PTy = cast<PointerType>(Ty);
1793 unsigned AddrSpace = PTy->getAddressSpace();
1794
1795 // For the purposes of our Vulkan SPIR-V type system, constant and global
1796 // are conflated.
1797 bool UseExistingOpTypePointer = false;
1798 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001799 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1800 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001801 // Check to see if we already created this type (for instance, if we
1802 // had a constant <type>* and a global <type>*, the type would be
1803 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001804 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1805 if (0 < TypeMap.count(GlobalTy)) {
1806 TypeMap[PTy] = TypeMap[GlobalTy];
1807 UseExistingOpTypePointer = true;
1808 break;
1809 }
David Neto22f144c2017-06-12 14:26:21 -04001810 }
1811 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001812 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1813 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001814
alan-bakerb6b09dc2018-11-08 16:59:28 -05001815 // Check to see if we already created this type (for instance, if we
1816 // had a constant <type>* and a global <type>*, the type would be
1817 // created by one of these types, and shared by both).
1818 auto ConstantTy =
1819 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001820 if (0 < TypeMap.count(ConstantTy)) {
1821 TypeMap[PTy] = TypeMap[ConstantTy];
1822 UseExistingOpTypePointer = true;
1823 }
David Neto22f144c2017-06-12 14:26:21 -04001824 }
1825 }
1826
David Neto862b7d82018-06-14 18:48:37 -04001827 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001828
David Neto862b7d82018-06-14 18:48:37 -04001829 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001830 //
1831 // Generate OpTypePointer.
1832 //
1833
1834 // OpTypePointer
1835 // Ops[0] = Storage Class
1836 // Ops[1] = Element Type ID
1837 SPIRVOperandList Ops;
1838
David Neto257c3892018-04-11 13:19:45 -04001839 Ops << MkNum(GetStorageClass(AddrSpace))
1840 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001841
David Neto87846742018-04-11 17:36:22 -04001842 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001843 SPIRVInstList.push_back(Inst);
1844 }
David Neto22f144c2017-06-12 14:26:21 -04001845 break;
1846 }
1847 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001848 StructType *STy = cast<StructType>(Ty);
1849
1850 // Handle sampler type.
1851 if (STy->isOpaque()) {
1852 if (STy->getName().equals("opencl.sampler_t")) {
1853 //
1854 // Generate OpTypeSampler
1855 //
1856 // Empty Ops.
1857 SPIRVOperandList Ops;
1858
David Neto87846742018-04-11 17:36:22 -04001859 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001860 SPIRVInstList.push_back(Inst);
1861 break;
1862 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1863 STy->getName().equals("opencl.image2d_wo_t") ||
1864 STy->getName().equals("opencl.image3d_ro_t") ||
1865 STy->getName().equals("opencl.image3d_wo_t")) {
1866 //
1867 // Generate OpTypeImage
1868 //
1869 // Ops[0] = Sampled Type ID
1870 // Ops[1] = Dim ID
1871 // Ops[2] = Depth (Literal Number)
1872 // Ops[3] = Arrayed (Literal Number)
1873 // Ops[4] = MS (Literal Number)
1874 // Ops[5] = Sampled (Literal Number)
1875 // Ops[6] = Image Format ID
1876 //
1877 SPIRVOperandList Ops;
1878
1879 // TODO: Changed Sampled Type according to situations.
1880 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001881 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001882
1883 spv::Dim DimID = spv::Dim2D;
1884 if (STy->getName().equals("opencl.image3d_ro_t") ||
1885 STy->getName().equals("opencl.image3d_wo_t")) {
1886 DimID = spv::Dim3D;
1887 }
David Neto257c3892018-04-11 13:19:45 -04001888 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001889
1890 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001891 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001892
1893 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001894 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001895
1896 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001897 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001898
1899 // TODO: Set up Sampled.
1900 //
1901 // From Spec
1902 //
1903 // 0 indicates this is only known at run time, not at compile time
1904 // 1 indicates will be used with sampler
1905 // 2 indicates will be used without a sampler (a storage image)
1906 uint32_t Sampled = 1;
1907 if (STy->getName().equals("opencl.image2d_wo_t") ||
1908 STy->getName().equals("opencl.image3d_wo_t")) {
1909 Sampled = 2;
1910 }
David Neto257c3892018-04-11 13:19:45 -04001911 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001912
1913 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001914 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001915
David Neto87846742018-04-11 17:36:22 -04001916 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001917 SPIRVInstList.push_back(Inst);
1918 break;
1919 }
1920 }
1921
1922 //
1923 // Generate OpTypeStruct
1924 //
1925 // Ops[0] ... Ops[n] = Member IDs
1926 SPIRVOperandList Ops;
1927
1928 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001929 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001930 }
1931
David Neto22f144c2017-06-12 14:26:21 -04001932 uint32_t STyID = nextID;
1933
alan-bakerb6b09dc2018-11-08 16:59:28 -05001934 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001935 SPIRVInstList.push_back(Inst);
1936
1937 // Generate OpMemberDecorate.
1938 auto DecoInsertPoint =
1939 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1940 [](SPIRVInstruction *Inst) -> bool {
1941 return Inst->getOpcode() != spv::OpDecorate &&
1942 Inst->getOpcode() != spv::OpMemberDecorate &&
1943 Inst->getOpcode() != spv::OpExtInstImport;
1944 });
1945
David Netoc463b372017-08-10 15:32:21 -04001946 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001947 // Search for the correct offsets if this type was remapped.
1948 std::vector<uint32_t> *offsets = nullptr;
1949 auto iter = RemappedUBOTypeOffsets.find(STy);
1950 if (iter != RemappedUBOTypeOffsets.end()) {
1951 offsets = &iter->second;
1952 }
David Netoc463b372017-08-10 15:32:21 -04001953
David Neto862b7d82018-06-14 18:48:37 -04001954 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001955 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1956 MemberIdx++) {
1957 // Ops[0] = Structure Type ID
1958 // Ops[1] = Member Index(Literal Number)
1959 // Ops[2] = Decoration (Offset)
1960 // Ops[3] = Byte Offset (Literal Number)
1961 Ops.clear();
1962
David Neto257c3892018-04-11 13:19:45 -04001963 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001964
alan-bakerb6b09dc2018-11-08 16:59:28 -05001965 auto ByteOffset =
1966 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001967 if (offsets) {
1968 ByteOffset = (*offsets)[MemberIdx];
1969 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001970 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001971 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001972 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001973
David Neto87846742018-04-11 17:36:22 -04001974 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001975 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001976 }
1977
1978 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001979 if (StructTypesNeedingBlock.idFor(STy)) {
1980 Ops.clear();
1981 // Use Block decorations with StorageBuffer storage class.
1982 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001983
David Neto862b7d82018-06-14 18:48:37 -04001984 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1985 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001986 }
1987 break;
1988 }
1989 case Type::IntegerTyID: {
1990 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1991
1992 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001993 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001994 SPIRVInstList.push_back(Inst);
1995 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001996 if (!clspv::Option::Int8Support()) {
1997 // i8 is added to TypeMap as i32.
1998 // No matter what LLVM type is requested first, always alias the
1999 // second one's SPIR-V type to be the same as the one we generated
2000 // first.
2001 unsigned aliasToWidth = 0;
2002 if (BitWidth == 8) {
2003 aliasToWidth = 32;
2004 BitWidth = 32;
2005 } else if (BitWidth == 32) {
2006 aliasToWidth = 8;
2007 }
2008 if (aliasToWidth) {
2009 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2010 auto where = TypeMap.find(otherType);
2011 if (where == TypeMap.end()) {
2012 // Go ahead and make it, but also map the other type to it.
2013 TypeMap[otherType] = nextID;
2014 } else {
2015 // Alias this SPIR-V type the existing type.
2016 TypeMap[Ty] = where->second;
2017 break;
2018 }
David Neto391aeb12017-08-26 15:51:58 -04002019 }
David Neto22f144c2017-06-12 14:26:21 -04002020 }
2021
David Neto257c3892018-04-11 13:19:45 -04002022 SPIRVOperandList Ops;
2023 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002024
2025 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002026 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002027 }
2028 break;
2029 }
2030 case Type::HalfTyID:
2031 case Type::FloatTyID:
2032 case Type::DoubleTyID: {
2033 SPIRVOperand *WidthOp = new SPIRVOperand(
2034 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2035
2036 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002037 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002038 break;
2039 }
2040 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002041 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002042 const uint64_t Length = ArrTy->getArrayNumElements();
2043 if (Length == 0) {
2044 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002045
David Neto862b7d82018-06-14 18:48:37 -04002046 // Only generate the type once.
2047 // TODO(dneto): Can it ever be generated more than once?
2048 // Doesn't LLVM type uniqueness guarantee we'll only see this
2049 // once?
2050 Type *EleTy = ArrTy->getArrayElementType();
2051 if (OpRuntimeTyMap.count(EleTy) == 0) {
2052 uint32_t OpTypeRuntimeArrayID = nextID;
2053 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002054
David Neto862b7d82018-06-14 18:48:37 -04002055 //
2056 // Generate OpTypeRuntimeArray.
2057 //
David Neto22f144c2017-06-12 14:26:21 -04002058
David Neto862b7d82018-06-14 18:48:37 -04002059 // OpTypeRuntimeArray
2060 // Ops[0] = Element Type ID
2061 SPIRVOperandList Ops;
2062 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002063
David Neto862b7d82018-06-14 18:48:37 -04002064 SPIRVInstList.push_back(
2065 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002066
David Neto862b7d82018-06-14 18:48:37 -04002067 if (Hack_generate_runtime_array_stride_early) {
2068 // Generate OpDecorate.
2069 auto DecoInsertPoint = std::find_if(
2070 SPIRVInstList.begin(), SPIRVInstList.end(),
2071 [](SPIRVInstruction *Inst) -> bool {
2072 return Inst->getOpcode() != spv::OpDecorate &&
2073 Inst->getOpcode() != spv::OpMemberDecorate &&
2074 Inst->getOpcode() != spv::OpExtInstImport;
2075 });
David Neto22f144c2017-06-12 14:26:21 -04002076
David Neto862b7d82018-06-14 18:48:37 -04002077 // Ops[0] = Target ID
2078 // Ops[1] = Decoration (ArrayStride)
2079 // Ops[2] = Stride Number(Literal Number)
2080 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002081
David Neto862b7d82018-06-14 18:48:37 -04002082 Ops << MkId(OpTypeRuntimeArrayID)
2083 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002084 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002085
David Neto862b7d82018-06-14 18:48:37 -04002086 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2087 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2088 }
2089 }
David Neto22f144c2017-06-12 14:26:21 -04002090
David Neto862b7d82018-06-14 18:48:37 -04002091 } else {
David Neto22f144c2017-06-12 14:26:21 -04002092
David Neto862b7d82018-06-14 18:48:37 -04002093 //
2094 // Generate OpConstant and OpTypeArray.
2095 //
2096
2097 //
2098 // Generate OpConstant for array length.
2099 //
2100 // Ops[0] = Result Type ID
2101 // Ops[1] .. Ops[n] = Values LiteralNumber
2102 SPIRVOperandList Ops;
2103
2104 Type *LengthTy = Type::getInt32Ty(Context);
2105 uint32_t ResTyID = lookupType(LengthTy);
2106 Ops << MkId(ResTyID);
2107
2108 assert(Length < UINT32_MAX);
2109 Ops << MkNum(static_cast<uint32_t>(Length));
2110
2111 // Add constant for length to constant list.
2112 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2113 AllocatedVMap[CstLength] = nextID;
2114 VMap[CstLength] = nextID;
2115 uint32_t LengthID = nextID;
2116
2117 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2118 SPIRVInstList.push_back(CstInst);
2119
2120 // Remember to generate ArrayStride later
2121 getTypesNeedingArrayStride().insert(Ty);
2122
2123 //
2124 // Generate OpTypeArray.
2125 //
2126 // Ops[0] = Element Type ID
2127 // Ops[1] = Array Length Constant ID
2128 Ops.clear();
2129
2130 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2131 Ops << MkId(EleTyID) << MkId(LengthID);
2132
2133 // Update TypeMap with nextID.
2134 TypeMap[Ty] = nextID;
2135
2136 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2137 SPIRVInstList.push_back(ArrayInst);
2138 }
David Neto22f144c2017-06-12 14:26:21 -04002139 break;
2140 }
2141 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002142 // <4 x i8> is changed to i32 if i8 is not generally supported.
2143 if (!clspv::Option::Int8Support() &&
2144 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002145 if (Ty->getVectorNumElements() == 4) {
2146 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2147 break;
2148 } else {
2149 Ty->print(errs());
2150 llvm_unreachable("Support above i8 vector type");
2151 }
2152 }
2153
2154 // Ops[0] = Component Type ID
2155 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002156 SPIRVOperandList Ops;
2157 Ops << MkId(lookupType(Ty->getVectorElementType()))
2158 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002159
alan-bakerb6b09dc2018-11-08 16:59:28 -05002160 SPIRVInstruction *inst =
2161 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002162 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002163 break;
2164 }
2165 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002166 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002167 SPIRVInstList.push_back(Inst);
2168 break;
2169 }
2170 case Type::FunctionTyID: {
2171 // Generate SPIRV instruction for function type.
2172 FunctionType *FTy = cast<FunctionType>(Ty);
2173
2174 // Ops[0] = Return Type ID
2175 // Ops[1] ... Ops[n] = Parameter Type IDs
2176 SPIRVOperandList Ops;
2177
2178 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002179 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002180
2181 // Find SPIRV instructions for parameter types
2182 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2183 // Find SPIRV instruction for parameter type.
2184 auto ParamTy = FTy->getParamType(k);
2185 if (ParamTy->isPointerTy()) {
2186 auto PointeeTy = ParamTy->getPointerElementType();
2187 if (PointeeTy->isStructTy() &&
2188 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2189 ParamTy = PointeeTy;
2190 }
2191 }
2192
David Netoc6f3ab22018-04-06 18:02:31 -04002193 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002194 }
2195
David Neto87846742018-04-11 17:36:22 -04002196 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002197 SPIRVInstList.push_back(Inst);
2198 break;
2199 }
2200 }
2201 }
2202
2203 // Generate OpTypeSampledImage.
2204 TypeMapType &OpImageTypeMap = getImageTypeMap();
2205 for (auto &ImageType : OpImageTypeMap) {
2206 //
2207 // Generate OpTypeSampledImage.
2208 //
2209 // Ops[0] = Image Type ID
2210 //
2211 SPIRVOperandList Ops;
2212
2213 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002214 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002215
2216 // Update OpImageTypeMap.
2217 ImageType.second = nextID;
2218
David Neto87846742018-04-11 17:36:22 -04002219 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002220 SPIRVInstList.push_back(Inst);
2221 }
David Netoc6f3ab22018-04-06 18:02:31 -04002222
2223 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002224 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2225 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002226 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002227
2228 // Generate the spec constant.
2229 SPIRVOperandList Ops;
2230 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002231 SPIRVInstList.push_back(
2232 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002233
2234 // Generate the array type.
2235 Ops.clear();
2236 // The element type must have been created.
2237 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2238 assert(elem_ty_id);
2239 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2240
2241 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002242 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002243
2244 Ops.clear();
2245 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002246 SPIRVInstList.push_back(new SPIRVInstruction(
2247 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002248 }
David Neto22f144c2017-06-12 14:26:21 -04002249}
2250
2251void SPIRVProducerPass::GenerateSPIRVConstants() {
2252 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2253 ValueMapType &VMap = getValueMap();
2254 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2255 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002256 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002257
2258 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002259 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002260 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002261
2262 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002263 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002264 continue;
2265 }
2266
David Netofb9a7972017-08-25 17:08:24 -04002267 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002268 VMap[Cst] = nextID;
2269
2270 //
2271 // Generate OpConstant.
2272 //
2273
2274 // Ops[0] = Result Type ID
2275 // Ops[1] .. Ops[n] = Values LiteralNumber
2276 SPIRVOperandList Ops;
2277
David Neto257c3892018-04-11 13:19:45 -04002278 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002279
2280 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002281 spv::Op Opcode = spv::OpNop;
2282
2283 if (isa<UndefValue>(Cst)) {
2284 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002285 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002286 if (hack_undef && IsTypeNullable(Cst->getType())) {
2287 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002288 }
David Neto22f144c2017-06-12 14:26:21 -04002289 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2290 unsigned BitWidth = CI->getBitWidth();
2291 if (BitWidth == 1) {
2292 // If the bitwidth of constant is 1, generate OpConstantTrue or
2293 // OpConstantFalse.
2294 if (CI->getZExtValue()) {
2295 // Ops[0] = Result Type ID
2296 Opcode = spv::OpConstantTrue;
2297 } else {
2298 // Ops[0] = Result Type ID
2299 Opcode = spv::OpConstantFalse;
2300 }
David Neto22f144c2017-06-12 14:26:21 -04002301 } else {
2302 auto V = CI->getZExtValue();
2303 LiteralNum.push_back(V & 0xFFFFFFFF);
2304
2305 if (BitWidth > 32) {
2306 LiteralNum.push_back(V >> 32);
2307 }
2308
2309 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002310
David Neto257c3892018-04-11 13:19:45 -04002311 Ops << MkInteger(LiteralNum);
2312
2313 if (BitWidth == 32 && V == 0) {
2314 constant_i32_zero_id_ = nextID;
2315 }
David Neto22f144c2017-06-12 14:26:21 -04002316 }
2317 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2318 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2319 Type *CFPTy = CFP->getType();
2320 if (CFPTy->isFloatTy()) {
2321 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002322 } else if (CFPTy->isDoubleTy()) {
2323 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2324 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002325 } else {
2326 CFPTy->print(errs());
2327 llvm_unreachable("Implement this ConstantFP Type");
2328 }
2329
2330 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002331
David Neto257c3892018-04-11 13:19:45 -04002332 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002333 } else if (isa<ConstantDataSequential>(Cst) &&
2334 cast<ConstantDataSequential>(Cst)->isString()) {
2335 Cst->print(errs());
2336 llvm_unreachable("Implement this Constant");
2337
2338 } else if (const ConstantDataSequential *CDS =
2339 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002340 // Let's convert <4 x i8> constant to int constant specially.
2341 // This case occurs when all the values are specified as constant
2342 // ints.
2343 Type *CstTy = Cst->getType();
2344 if (is4xi8vec(CstTy)) {
2345 LLVMContext &Context = CstTy->getContext();
2346
2347 //
2348 // Generate OpConstant with OpTypeInt 32 0.
2349 //
Neil Henning39672102017-09-29 14:33:13 +01002350 uint32_t IntValue = 0;
2351 for (unsigned k = 0; k < 4; k++) {
2352 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002353 IntValue = (IntValue << 8) | (Val & 0xffu);
2354 }
2355
2356 Type *i32 = Type::getInt32Ty(Context);
2357 Constant *CstInt = ConstantInt::get(i32, IntValue);
2358 // If this constant is already registered on VMap, use it.
2359 if (VMap.count(CstInt)) {
2360 uint32_t CstID = VMap[CstInt];
2361 VMap[Cst] = CstID;
2362 continue;
2363 }
2364
David Neto257c3892018-04-11 13:19:45 -04002365 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002366
David Neto87846742018-04-11 17:36:22 -04002367 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002368 SPIRVInstList.push_back(CstInst);
2369
2370 continue;
2371 }
2372
2373 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002374 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2375 Constant *EleCst = CDS->getElementAsConstant(k);
2376 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002377 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002378 }
2379
2380 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002381 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2382 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002383 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002384 Type *CstTy = Cst->getType();
2385 if (is4xi8vec(CstTy)) {
2386 LLVMContext &Context = CstTy->getContext();
2387
2388 //
2389 // Generate OpConstant with OpTypeInt 32 0.
2390 //
Neil Henning39672102017-09-29 14:33:13 +01002391 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002392 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2393 I != E; ++I) {
2394 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002395 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002396 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2397 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002398 }
David Neto49351ac2017-08-26 17:32:20 -04002399 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002400 }
2401
David Neto49351ac2017-08-26 17:32:20 -04002402 Type *i32 = Type::getInt32Ty(Context);
2403 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002404 // If this constant is already registered on VMap, use it.
2405 if (VMap.count(CstInt)) {
2406 uint32_t CstID = VMap[CstInt];
2407 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002408 continue;
David Neto22f144c2017-06-12 14:26:21 -04002409 }
2410
David Neto257c3892018-04-11 13:19:45 -04002411 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002412
David Neto87846742018-04-11 17:36:22 -04002413 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002414 SPIRVInstList.push_back(CstInst);
2415
David Neto19a1bad2017-08-25 15:01:41 -04002416 continue;
David Neto22f144c2017-06-12 14:26:21 -04002417 }
2418
2419 // We use a constant composite in SPIR-V for our constant aggregate in
2420 // LLVM.
2421 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002422
2423 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2424 // Look up the ID of the element of this aggregate (which we will
2425 // previously have created a constant for).
2426 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2427
2428 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002429 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002430 }
2431 } else if (Cst->isNullValue()) {
2432 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002433 } else {
2434 Cst->print(errs());
2435 llvm_unreachable("Unsupported Constant???");
2436 }
2437
alan-baker5b86ed72019-02-15 08:26:50 -05002438 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2439 // Null pointer requires variable pointers.
2440 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2441 }
2442
David Neto87846742018-04-11 17:36:22 -04002443 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002444 SPIRVInstList.push_back(CstInst);
2445 }
2446}
2447
2448void SPIRVProducerPass::GenerateSamplers(Module &M) {
2449 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002450
alan-bakerb6b09dc2018-11-08 16:59:28 -05002451 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002452 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002453 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002454 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2455 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002456
David Neto862b7d82018-06-14 18:48:37 -04002457 // We might have samplers in the sampler map that are not used
2458 // in the translation unit. We need to allocate variables
2459 // for them and bindings too.
2460 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002461
Kévin Petitdf71de32019-04-09 14:09:50 +01002462 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002463 if (!var_fn)
2464 return;
David Neto862b7d82018-06-14 18:48:37 -04002465 for (auto user : var_fn->users()) {
2466 // Populate SamplerLiteralToDescriptorSetMap and
2467 // SamplerLiteralToBindingMap.
2468 //
2469 // Look for calls like
2470 // call %opencl.sampler_t addrspace(2)*
2471 // @clspv.sampler.var.literal(
2472 // i32 descriptor,
2473 // i32 binding,
2474 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002475 if (auto *call = dyn_cast<CallInst>(user)) {
2476 const size_t index_into_sampler_map = static_cast<size_t>(
2477 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002478 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002479 errs() << "Out of bounds index to sampler map: "
2480 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002481 llvm_unreachable("bad sampler init: out of bounds");
2482 }
2483
2484 auto sampler_value = sampler_map[index_into_sampler_map].first;
2485 const auto descriptor_set = static_cast<unsigned>(
2486 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2487 const auto binding = static_cast<unsigned>(
2488 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2489
2490 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2491 SamplerLiteralToBindingMap[sampler_value] = binding;
2492 used_bindings.insert(binding);
2493 }
2494 }
2495
2496 unsigned index = 0;
2497 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002498 // Generate OpVariable.
2499 //
2500 // GIDOps[0] : Result Type ID
2501 // GIDOps[1] : Storage Class
2502 SPIRVOperandList Ops;
2503
David Neto257c3892018-04-11 13:19:45 -04002504 Ops << MkId(lookupType(SamplerTy))
2505 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002506
David Neto862b7d82018-06-14 18:48:37 -04002507 auto sampler_var_id = nextID++;
2508 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002509 SPIRVInstList.push_back(Inst);
2510
David Neto862b7d82018-06-14 18:48:37 -04002511 SamplerMapIndexToIDMap[index] = sampler_var_id;
2512 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002513
2514 // Find Insert Point for OpDecorate.
2515 auto DecoInsertPoint =
2516 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2517 [](SPIRVInstruction *Inst) -> bool {
2518 return Inst->getOpcode() != spv::OpDecorate &&
2519 Inst->getOpcode() != spv::OpMemberDecorate &&
2520 Inst->getOpcode() != spv::OpExtInstImport;
2521 });
2522
2523 // Ops[0] = Target ID
2524 // Ops[1] = Decoration (DescriptorSet)
2525 // Ops[2] = LiteralNumber according to Decoration
2526 Ops.clear();
2527
David Neto862b7d82018-06-14 18:48:37 -04002528 unsigned descriptor_set;
2529 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002530 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2531 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002532 // This sampler is not actually used. Find the next one.
2533 for (binding = 0; used_bindings.count(binding); binding++)
2534 ;
2535 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2536 used_bindings.insert(binding);
2537 } else {
2538 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2539 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2540 }
2541
2542 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2543 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002544
alan-bakerf5e5f692018-11-27 08:33:24 -05002545 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2546 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002547
David Neto87846742018-04-11 17:36:22 -04002548 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002549 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2550
2551 // Ops[0] = Target ID
2552 // Ops[1] = Decoration (Binding)
2553 // Ops[2] = LiteralNumber according to Decoration
2554 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002555 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2556 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002557
David Neto87846742018-04-11 17:36:22 -04002558 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002559 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002560
2561 index++;
David Neto22f144c2017-06-12 14:26:21 -04002562 }
David Neto862b7d82018-06-14 18:48:37 -04002563}
David Neto22f144c2017-06-12 14:26:21 -04002564
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002565void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002566 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2567 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002568
David Neto862b7d82018-06-14 18:48:37 -04002569 // Generate variables. Make one for each of resource var info object.
2570 for (auto *info : ModuleOrderedResourceVars) {
2571 Type *type = info->var_fn->getReturnType();
2572 // Remap the address space for opaque types.
2573 switch (info->arg_kind) {
2574 case clspv::ArgKind::Sampler:
2575 case clspv::ArgKind::ReadOnlyImage:
2576 case clspv::ArgKind::WriteOnlyImage:
2577 type = PointerType::get(type->getPointerElementType(),
2578 clspv::AddressSpace::UniformConstant);
2579 break;
2580 default:
2581 break;
2582 }
David Neto22f144c2017-06-12 14:26:21 -04002583
David Neto862b7d82018-06-14 18:48:37 -04002584 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002585
David Neto862b7d82018-06-14 18:48:37 -04002586 const auto type_id = lookupType(type);
2587 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2588 SPIRVOperandList Ops;
2589 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002590
David Neto862b7d82018-06-14 18:48:37 -04002591 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2592 SPIRVInstList.push_back(Inst);
2593
2594 // Map calls to the variable-builtin-function.
2595 for (auto &U : info->var_fn->uses()) {
2596 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2597 const auto set = unsigned(
2598 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2599 const auto binding = unsigned(
2600 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2601 if (set == info->descriptor_set && binding == info->binding) {
2602 switch (info->arg_kind) {
2603 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002604 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002605 case clspv::ArgKind::Pod:
2606 // The call maps to the variable directly.
2607 VMap[call] = info->var_id;
2608 break;
2609 case clspv::ArgKind::Sampler:
2610 case clspv::ArgKind::ReadOnlyImage:
2611 case clspv::ArgKind::WriteOnlyImage:
2612 // The call maps to a load we generate later.
2613 ResourceVarDeferredLoadCalls[call] = info->var_id;
2614 break;
2615 default:
2616 llvm_unreachable("Unhandled arg kind");
2617 }
2618 }
David Neto22f144c2017-06-12 14:26:21 -04002619 }
David Neto862b7d82018-06-14 18:48:37 -04002620 }
2621 }
David Neto22f144c2017-06-12 14:26:21 -04002622
David Neto862b7d82018-06-14 18:48:37 -04002623 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002624
David Neto862b7d82018-06-14 18:48:37 -04002625 // Find Insert Point for OpDecorate.
2626 auto DecoInsertPoint =
2627 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2628 [](SPIRVInstruction *Inst) -> bool {
2629 return Inst->getOpcode() != spv::OpDecorate &&
2630 Inst->getOpcode() != spv::OpMemberDecorate &&
2631 Inst->getOpcode() != spv::OpExtInstImport;
2632 });
2633
2634 SPIRVOperandList Ops;
2635 for (auto *info : ModuleOrderedResourceVars) {
2636 // Decorate with DescriptorSet and Binding.
2637 Ops.clear();
2638 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2639 << MkNum(info->descriptor_set);
2640 SPIRVInstList.insert(DecoInsertPoint,
2641 new SPIRVInstruction(spv::OpDecorate, Ops));
2642
2643 Ops.clear();
2644 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2645 << MkNum(info->binding);
2646 SPIRVInstList.insert(DecoInsertPoint,
2647 new SPIRVInstruction(spv::OpDecorate, Ops));
2648
alan-bakere9308012019-03-15 10:25:13 -04002649 if (info->coherent) {
2650 // Decorate with Coherent if required for the variable.
2651 Ops.clear();
2652 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2653 SPIRVInstList.insert(DecoInsertPoint,
2654 new SPIRVInstruction(spv::OpDecorate, Ops));
2655 }
2656
David Neto862b7d82018-06-14 18:48:37 -04002657 // Generate NonWritable and NonReadable
2658 switch (info->arg_kind) {
2659 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002660 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002661 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2662 clspv::AddressSpace::Constant) {
2663 Ops.clear();
2664 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2665 SPIRVInstList.insert(DecoInsertPoint,
2666 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002667 }
David Neto862b7d82018-06-14 18:48:37 -04002668 break;
David Neto862b7d82018-06-14 18:48:37 -04002669 case clspv::ArgKind::WriteOnlyImage:
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2672 SPIRVInstList.insert(DecoInsertPoint,
2673 new SPIRVInstruction(spv::OpDecorate, Ops));
2674 break;
2675 default:
2676 break;
David Neto22f144c2017-06-12 14:26:21 -04002677 }
2678 }
2679}
2680
2681void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002682 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002683 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2684 ValueMapType &VMap = getValueMap();
2685 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002686 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002687
2688 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2689 Type *Ty = GV.getType();
2690 PointerType *PTy = cast<PointerType>(Ty);
2691
2692 uint32_t InitializerID = 0;
2693
2694 // Workgroup size is handled differently (it goes into a constant)
2695 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2696 std::vector<bool> HasMDVec;
2697 uint32_t PrevXDimCst = 0xFFFFFFFF;
2698 uint32_t PrevYDimCst = 0xFFFFFFFF;
2699 uint32_t PrevZDimCst = 0xFFFFFFFF;
2700 for (Function &Func : *GV.getParent()) {
2701 if (Func.isDeclaration()) {
2702 continue;
2703 }
2704
2705 // We only need to check kernels.
2706 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2707 continue;
2708 }
2709
2710 if (const MDNode *MD =
2711 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2712 uint32_t CurXDimCst = static_cast<uint32_t>(
2713 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2714 uint32_t CurYDimCst = static_cast<uint32_t>(
2715 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2716 uint32_t CurZDimCst = static_cast<uint32_t>(
2717 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2718
2719 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2720 PrevZDimCst == 0xFFFFFFFF) {
2721 PrevXDimCst = CurXDimCst;
2722 PrevYDimCst = CurYDimCst;
2723 PrevZDimCst = CurZDimCst;
2724 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2725 CurZDimCst != PrevZDimCst) {
2726 llvm_unreachable(
2727 "reqd_work_group_size must be the same across all kernels");
2728 } else {
2729 continue;
2730 }
2731
2732 //
2733 // Generate OpConstantComposite.
2734 //
2735 // Ops[0] : Result Type ID
2736 // Ops[1] : Constant size for x dimension.
2737 // Ops[2] : Constant size for y dimension.
2738 // Ops[3] : Constant size for z dimension.
2739 SPIRVOperandList Ops;
2740
2741 uint32_t XDimCstID =
2742 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2743 uint32_t YDimCstID =
2744 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2745 uint32_t ZDimCstID =
2746 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2747
2748 InitializerID = nextID;
2749
David Neto257c3892018-04-11 13:19:45 -04002750 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2751 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto87846742018-04-11 17:36:22 -04002753 auto *Inst =
2754 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVInstList.push_back(Inst);
2756
2757 HasMDVec.push_back(true);
2758 } else {
2759 HasMDVec.push_back(false);
2760 }
2761 }
2762
2763 // Check all kernels have same definitions for work_group_size.
2764 bool HasMD = false;
2765 if (!HasMDVec.empty()) {
2766 HasMD = HasMDVec[0];
2767 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2768 if (HasMD != HasMDVec[i]) {
2769 llvm_unreachable(
2770 "Kernels should have consistent work group size definition");
2771 }
2772 }
2773 }
2774
2775 // If all kernels do not have metadata for reqd_work_group_size, generate
2776 // OpSpecConstants for x/y/z dimension.
2777 if (!HasMD) {
2778 //
2779 // Generate OpSpecConstants for x/y/z dimension.
2780 //
2781 // Ops[0] : Result Type ID
2782 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2783 uint32_t XDimCstID = 0;
2784 uint32_t YDimCstID = 0;
2785 uint32_t ZDimCstID = 0;
2786
David Neto22f144c2017-06-12 14:26:21 -04002787 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002788 uint32_t result_type_id =
2789 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002790
David Neto257c3892018-04-11 13:19:45 -04002791 // X Dimension
2792 Ops << MkId(result_type_id) << MkNum(1);
2793 XDimCstID = nextID++;
2794 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002795 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002796
2797 // Y Dimension
2798 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002799 Ops << MkId(result_type_id) << MkNum(1);
2800 YDimCstID = nextID++;
2801 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002802 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002803
2804 // Z Dimension
2805 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002806 Ops << MkId(result_type_id) << MkNum(1);
2807 ZDimCstID = nextID++;
2808 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002809 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002810
David Neto257c3892018-04-11 13:19:45 -04002811 BuiltinDimVec.push_back(XDimCstID);
2812 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002813 BuiltinDimVec.push_back(ZDimCstID);
2814
David Neto22f144c2017-06-12 14:26:21 -04002815 //
2816 // Generate OpSpecConstantComposite.
2817 //
2818 // Ops[0] : Result Type ID
2819 // Ops[1] : Constant size for x dimension.
2820 // Ops[2] : Constant size for y dimension.
2821 // Ops[3] : Constant size for z dimension.
2822 InitializerID = nextID;
2823
2824 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002825 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2826 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002827
David Neto87846742018-04-11 17:36:22 -04002828 auto *Inst =
2829 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002830 SPIRVInstList.push_back(Inst);
2831 }
2832 }
2833
David Neto22f144c2017-06-12 14:26:21 -04002834 VMap[&GV] = nextID;
2835
2836 //
2837 // Generate OpVariable.
2838 //
2839 // GIDOps[0] : Result Type ID
2840 // GIDOps[1] : Storage Class
2841 SPIRVOperandList Ops;
2842
David Neto85082642018-03-24 06:55:20 -07002843 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002844 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002845
David Neto85082642018-03-24 06:55:20 -07002846 if (GV.hasInitializer()) {
2847 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002848 }
2849
David Neto85082642018-03-24 06:55:20 -07002850 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002851 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002852 clspv::Option::ModuleConstantsInStorageBuffer();
2853
2854 if (0 != InitializerID) {
2855 if (!module_scope_constant_external_init) {
2856 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002857 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002858 }
2859 }
2860 const uint32_t var_id = nextID++;
2861
David Neto87846742018-04-11 17:36:22 -04002862 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002863 SPIRVInstList.push_back(Inst);
2864
2865 // If we have a builtin.
2866 if (spv::BuiltInMax != BuiltinType) {
2867 // Find Insert Point for OpDecorate.
2868 auto DecoInsertPoint =
2869 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2870 [](SPIRVInstruction *Inst) -> bool {
2871 return Inst->getOpcode() != spv::OpDecorate &&
2872 Inst->getOpcode() != spv::OpMemberDecorate &&
2873 Inst->getOpcode() != spv::OpExtInstImport;
2874 });
2875 //
2876 // Generate OpDecorate.
2877 //
2878 // DOps[0] = Target ID
2879 // DOps[1] = Decoration (Builtin)
2880 // DOps[2] = BuiltIn ID
2881 uint32_t ResultID;
2882
2883 // WorkgroupSize is different, we decorate the constant composite that has
2884 // its value, rather than the variable that we use to access the value.
2885 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2886 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002887 // Save both the value and variable IDs for later.
2888 WorkgroupSizeValueID = InitializerID;
2889 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002890 } else {
2891 ResultID = VMap[&GV];
2892 }
2893
2894 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002895 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2896 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002897
David Neto87846742018-04-11 17:36:22 -04002898 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002899 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002900 } else if (module_scope_constant_external_init) {
2901 // This module scope constant is initialized from a storage buffer with data
2902 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002903 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002904
David Neto862b7d82018-06-14 18:48:37 -04002905 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002906 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2907 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002908 std::string hexbytes;
2909 llvm::raw_string_ostream str(hexbytes);
2910 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2911 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2912 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002913
2914 // Find Insert Point for OpDecorate.
2915 auto DecoInsertPoint =
2916 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2917 [](SPIRVInstruction *Inst) -> bool {
2918 return Inst->getOpcode() != spv::OpDecorate &&
2919 Inst->getOpcode() != spv::OpMemberDecorate &&
2920 Inst->getOpcode() != spv::OpExtInstImport;
2921 });
2922
David Neto257c3892018-04-11 13:19:45 -04002923 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002924 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002925 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2926 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002927 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002928
2929 // OpDecorate %var DescriptorSet <descriptor_set>
2930 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002931 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2932 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002933 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002934 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002935 }
2936}
2937
David Netoc6f3ab22018-04-06 18:02:31 -04002938void SPIRVProducerPass::GenerateWorkgroupVars() {
2939 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002940 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2941 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002942 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002943
2944 // Generate OpVariable.
2945 //
2946 // GIDOps[0] : Result Type ID
2947 // GIDOps[1] : Storage Class
2948 SPIRVOperandList Ops;
2949 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2950
2951 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002952 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002953 }
2954}
2955
David Neto862b7d82018-06-14 18:48:37 -04002956void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2957 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002958 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2959 return;
2960 }
David Neto862b7d82018-06-14 18:48:37 -04002961 // Gather the list of resources that are used by this function's arguments.
2962 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2963
alan-bakerf5e5f692018-11-27 08:33:24 -05002964 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2965 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002966 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002967 std::string kind =
2968 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2969 ? "pod_ubo"
2970 : argKind;
2971 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002972 };
2973
2974 auto *fty = F.getType()->getPointerElementType();
2975 auto *func_ty = dyn_cast<FunctionType>(fty);
2976
2977 // If we've clustereed POD arguments, then argument details are in metadata.
2978 // If an argument maps to a resource variable, then get descriptor set and
2979 // binding from the resoure variable. Other info comes from the metadata.
2980 const auto *arg_map = F.getMetadata("kernel_arg_map");
2981 if (arg_map) {
2982 for (const auto &arg : arg_map->operands()) {
2983 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002984 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002985 const auto name =
2986 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2987 const auto old_index =
2988 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2989 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002990 const size_t new_index = static_cast<size_t>(
2991 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002992 const auto offset =
2993 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002994 const auto arg_size =
2995 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002996 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002997 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002998 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002999 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003000
3001 uint32_t descriptor_set = 0;
3002 uint32_t binding = 0;
3003 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3004 F.getName(),
3005 name,
3006 static_cast<uint32_t>(old_index),
3007 argKind,
3008 static_cast<uint32_t>(spec_id),
3009 // This will be set below for pointer-to-local args.
3010 0,
3011 static_cast<uint32_t>(offset),
3012 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 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003023 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003024 }
3025 } else {
3026 // There is no argument map.
3027 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003028 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003029
3030 SmallVector<Argument *, 4> arguments;
3031 for (auto &arg : F.args()) {
3032 arguments.push_back(&arg);
3033 }
3034
3035 unsigned arg_index = 0;
3036 for (auto *info : resource_var_at_index) {
3037 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003038 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003039 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003040 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003041 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003042 }
3043
alan-bakerf5e5f692018-11-27 08:33:24 -05003044 // Local pointer arguments are unused in this case. Offset is always zero.
3045 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3046 F.getName(), arg->getName(),
3047 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3048 0, 0,
3049 0, arg_size};
3050 descriptorMapEntries->emplace_back(std::move(kernel_data),
3051 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003052 }
3053 arg_index++;
3054 }
3055 // Generate mappings for pointer-to-local arguments.
3056 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3057 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003058 auto where = LocalArgSpecIds.find(arg);
3059 if (where != LocalArgSpecIds.end()) {
3060 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003061 // Pod arguments members are unused in this case.
3062 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3063 F.getName(),
3064 arg->getName(),
3065 arg_index,
3066 ArgKind::Local,
3067 static_cast<uint32_t>(local_arg_info.spec_id),
3068 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3069 0,
3070 0};
3071 // Pointer-to-local arguments do not utilize descriptor set and binding.
3072 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003073 }
3074 }
3075 }
3076}
3077
David Neto22f144c2017-06-12 14:26:21 -04003078void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3079 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3080 ValueMapType &VMap = getValueMap();
3081 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003082 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3083 auto &GlobalConstArgSet = getGlobalConstArgSet();
3084
3085 FunctionType *FTy = F.getFunctionType();
3086
3087 //
David Neto22f144c2017-06-12 14:26:21 -04003088 // Generate OPFunction.
3089 //
3090
3091 // FOps[0] : Result Type ID
3092 // FOps[1] : Function Control
3093 // FOps[2] : Function Type ID
3094 SPIRVOperandList FOps;
3095
3096 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003097 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003098
3099 // Check function attributes for SPIRV Function Control.
3100 uint32_t FuncControl = spv::FunctionControlMaskNone;
3101 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3102 FuncControl |= spv::FunctionControlInlineMask;
3103 }
3104 if (F.hasFnAttribute(Attribute::NoInline)) {
3105 FuncControl |= spv::FunctionControlDontInlineMask;
3106 }
3107 // TODO: Check llvm attribute for Function Control Pure.
3108 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3109 FuncControl |= spv::FunctionControlPureMask;
3110 }
3111 // TODO: Check llvm attribute for Function Control Const.
3112 if (F.hasFnAttribute(Attribute::ReadNone)) {
3113 FuncControl |= spv::FunctionControlConstMask;
3114 }
3115
David Neto257c3892018-04-11 13:19:45 -04003116 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003117
3118 uint32_t FTyID;
3119 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3120 SmallVector<Type *, 4> NewFuncParamTys;
3121 FunctionType *NewFTy =
3122 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3123 FTyID = lookupType(NewFTy);
3124 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003125 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003126 if (GlobalConstFuncTyMap.count(FTy)) {
3127 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3128 } else {
3129 FTyID = lookupType(FTy);
3130 }
3131 }
3132
David Neto257c3892018-04-11 13:19:45 -04003133 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003134
3135 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3136 EntryPoints.push_back(std::make_pair(&F, nextID));
3137 }
3138
3139 VMap[&F] = nextID;
3140
David Neto482550a2018-03-24 05:21:07 -07003141 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003142 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3143 }
David Neto22f144c2017-06-12 14:26:21 -04003144 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003145 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003146 SPIRVInstList.push_back(FuncInst);
3147
3148 //
3149 // Generate OpFunctionParameter for Normal function.
3150 //
3151
3152 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003153
3154 // Find Insert Point for OpDecorate.
3155 auto DecoInsertPoint =
3156 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3157 [](SPIRVInstruction *Inst) -> bool {
3158 return Inst->getOpcode() != spv::OpDecorate &&
3159 Inst->getOpcode() != spv::OpMemberDecorate &&
3160 Inst->getOpcode() != spv::OpExtInstImport;
3161 });
3162
David Neto22f144c2017-06-12 14:26:21 -04003163 // Iterate Argument for name instead of param type from function type.
3164 unsigned ArgIdx = 0;
3165 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003166 uint32_t param_id = nextID++;
3167 VMap[&Arg] = param_id;
3168
3169 if (CalledWithCoherentResource(Arg)) {
3170 // If the arg is passed a coherent resource ever, then decorate this
3171 // parameter with Coherent too.
3172 SPIRVOperandList decoration_ops;
3173 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
3174 SPIRVInstList.insert(DecoInsertPoint,
3175 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
3176 }
David Neto22f144c2017-06-12 14:26:21 -04003177
3178 // ParamOps[0] : Result Type ID
3179 SPIRVOperandList ParamOps;
3180
3181 // Find SPIRV instruction for parameter type.
3182 uint32_t ParamTyID = lookupType(Arg.getType());
3183 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3184 if (GlobalConstFuncTyMap.count(FTy)) {
3185 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3186 Type *EleTy = PTy->getPointerElementType();
3187 Type *ArgTy =
3188 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3189 ParamTyID = lookupType(ArgTy);
3190 GlobalConstArgSet.insert(&Arg);
3191 }
3192 }
3193 }
David Neto257c3892018-04-11 13:19:45 -04003194 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003195
3196 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003197 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003198 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003199 SPIRVInstList.push_back(ParamInst);
3200
3201 ArgIdx++;
3202 }
3203 }
3204}
3205
alan-bakerb6b09dc2018-11-08 16:59:28 -05003206void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003207 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3208 EntryPointVecType &EntryPoints = getEntryPointVec();
3209 ValueMapType &VMap = getValueMap();
3210 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3211 uint32_t &ExtInstImportID = getOpExtInstImportID();
3212 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3213
3214 // Set up insert point.
3215 auto InsertPoint = SPIRVInstList.begin();
3216
3217 //
3218 // Generate OpCapability
3219 //
3220 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3221
3222 // Ops[0] = Capability
3223 SPIRVOperandList Ops;
3224
David Neto87846742018-04-11 17:36:22 -04003225 auto *CapInst =
3226 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003227 SPIRVInstList.insert(InsertPoint, CapInst);
3228
3229 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003230 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3231 // Generate OpCapability for i8 type.
3232 SPIRVInstList.insert(InsertPoint,
3233 new SPIRVInstruction(spv::OpCapability,
3234 {MkNum(spv::CapabilityInt8)}));
3235 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003236 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003237 SPIRVInstList.insert(InsertPoint,
3238 new SPIRVInstruction(spv::OpCapability,
3239 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003240 } else if (Ty->isIntegerTy(64)) {
3241 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003242 SPIRVInstList.insert(InsertPoint,
3243 new SPIRVInstruction(spv::OpCapability,
3244 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003245 } else if (Ty->isHalfTy()) {
3246 // Generate OpCapability for half type.
3247 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003248 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3249 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003250 } else if (Ty->isDoubleTy()) {
3251 // Generate OpCapability for double type.
3252 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003253 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3254 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003255 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3256 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003257 if (STy->getName().equals("opencl.image2d_wo_t") ||
3258 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003259 // Generate OpCapability for write only image type.
3260 SPIRVInstList.insert(
3261 InsertPoint,
3262 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003263 spv::OpCapability,
3264 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003265 }
3266 }
3267 }
3268 }
3269
David Neto5c22a252018-03-15 16:07:41 -04003270 { // OpCapability ImageQuery
3271 bool hasImageQuery = false;
3272 for (const char *imageQuery : {
3273 "_Z15get_image_width14ocl_image2d_ro",
3274 "_Z15get_image_width14ocl_image2d_wo",
3275 "_Z16get_image_height14ocl_image2d_ro",
3276 "_Z16get_image_height14ocl_image2d_wo",
3277 }) {
3278 if (module.getFunction(imageQuery)) {
3279 hasImageQuery = true;
3280 break;
3281 }
3282 }
3283 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003284 auto *ImageQueryCapInst = new SPIRVInstruction(
3285 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003286 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3287 }
3288 }
3289
David Neto22f144c2017-06-12 14:26:21 -04003290 if (hasVariablePointers()) {
3291 //
David Neto22f144c2017-06-12 14:26:21 -04003292 // Generate OpCapability.
3293 //
3294 // Ops[0] = Capability
3295 //
3296 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003297 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003298
David Neto87846742018-04-11 17:36:22 -04003299 SPIRVInstList.insert(InsertPoint,
3300 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003301 } else if (hasVariablePointersStorageBuffer()) {
3302 //
3303 // Generate OpCapability.
3304 //
3305 // Ops[0] = Capability
3306 //
3307 Ops.clear();
3308 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003309
alan-baker5b86ed72019-02-15 08:26:50 -05003310 SPIRVInstList.insert(InsertPoint,
3311 new SPIRVInstruction(spv::OpCapability, Ops));
3312 }
3313
3314 // Always add the storage buffer extension
3315 {
David Neto22f144c2017-06-12 14:26:21 -04003316 //
3317 // Generate OpExtension.
3318 //
3319 // Ops[0] = Name (Literal String)
3320 //
alan-baker5b86ed72019-02-15 08:26:50 -05003321 auto *ExtensionInst = new SPIRVInstruction(
3322 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3323 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3324 }
David Neto22f144c2017-06-12 14:26:21 -04003325
alan-baker5b86ed72019-02-15 08:26:50 -05003326 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3327 //
3328 // Generate OpExtension.
3329 //
3330 // Ops[0] = Name (Literal String)
3331 //
3332 auto *ExtensionInst = new SPIRVInstruction(
3333 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3334 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003335 }
3336
3337 if (ExtInstImportID) {
3338 ++InsertPoint;
3339 }
3340
3341 //
3342 // Generate OpMemoryModel
3343 //
3344 // Memory model for Vulkan will always be GLSL450.
3345
3346 // Ops[0] = Addressing Model
3347 // Ops[1] = Memory Model
3348 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003349 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003350
David Neto87846742018-04-11 17:36:22 -04003351 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003352 SPIRVInstList.insert(InsertPoint, MemModelInst);
3353
3354 //
3355 // Generate OpEntryPoint
3356 //
3357 for (auto EntryPoint : EntryPoints) {
3358 // Ops[0] = Execution Model
3359 // Ops[1] = EntryPoint ID
3360 // Ops[2] = Name (Literal String)
3361 // ...
3362 //
3363 // TODO: Do we need to consider Interface ID for forward references???
3364 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003365 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003366 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3367 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003368
David Neto22f144c2017-06-12 14:26:21 -04003369 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003370 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003371 }
3372
David Neto87846742018-04-11 17:36:22 -04003373 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003374 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3375 }
3376
3377 for (auto EntryPoint : EntryPoints) {
3378 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3379 ->getMetadata("reqd_work_group_size")) {
3380
3381 if (!BuiltinDimVec.empty()) {
3382 llvm_unreachable(
3383 "Kernels should have consistent work group size definition");
3384 }
3385
3386 //
3387 // Generate OpExecutionMode
3388 //
3389
3390 // Ops[0] = Entry Point ID
3391 // Ops[1] = Execution Mode
3392 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3393 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003394 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003395
3396 uint32_t XDim = static_cast<uint32_t>(
3397 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3398 uint32_t YDim = static_cast<uint32_t>(
3399 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3400 uint32_t ZDim = static_cast<uint32_t>(
3401 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3402
David Neto257c3892018-04-11 13:19:45 -04003403 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003404
David Neto87846742018-04-11 17:36:22 -04003405 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003406 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3407 }
3408 }
3409
3410 //
3411 // Generate OpSource.
3412 //
3413 // Ops[0] = SourceLanguage ID
3414 // Ops[1] = Version (LiteralNum)
3415 //
3416 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003417 if (clspv::Option::CPlusPlus()) {
3418 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3419 } else {
3420 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3421 }
David Neto22f144c2017-06-12 14:26:21 -04003422
David Neto87846742018-04-11 17:36:22 -04003423 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003424 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3425
3426 if (!BuiltinDimVec.empty()) {
3427 //
3428 // Generate OpDecorates for x/y/z dimension.
3429 //
3430 // Ops[0] = Target ID
3431 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003432 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003433
3434 // X Dimension
3435 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003436 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003437 SPIRVInstList.insert(InsertPoint,
3438 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003439
3440 // Y Dimension
3441 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003442 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003443 SPIRVInstList.insert(InsertPoint,
3444 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003445
3446 // Z Dimension
3447 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003448 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003449 SPIRVInstList.insert(InsertPoint,
3450 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003451 }
3452}
3453
David Netob6e2e062018-04-25 10:32:06 -04003454void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3455 // Work around a driver bug. Initializers on Private variables might not
3456 // work. So the start of the kernel should store the initializer value to the
3457 // variables. Yes, *every* entry point pays this cost if *any* entry point
3458 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3459 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003460 // TODO(dneto): Remove this at some point once fixed drivers are widely
3461 // available.
David Netob6e2e062018-04-25 10:32:06 -04003462 if (WorkgroupSizeVarID) {
3463 assert(WorkgroupSizeValueID);
3464
3465 SPIRVOperandList Ops;
3466 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3467
3468 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3469 getSPIRVInstList().push_back(Inst);
3470 }
3471}
3472
David Neto22f144c2017-06-12 14:26:21 -04003473void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3474 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3475 ValueMapType &VMap = getValueMap();
3476
David Netob6e2e062018-04-25 10:32:06 -04003477 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003478
3479 for (BasicBlock &BB : F) {
3480 // Register BasicBlock to ValueMap.
3481 VMap[&BB] = nextID;
3482
3483 //
3484 // Generate OpLabel for Basic Block.
3485 //
3486 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003487 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003488 SPIRVInstList.push_back(Inst);
3489
David Neto6dcd4712017-06-23 11:06:47 -04003490 // OpVariable instructions must come first.
3491 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003492 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3493 // Allocating a pointer requires variable pointers.
3494 if (alloca->getAllocatedType()->isPointerTy()) {
3495 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3496 }
David Neto6dcd4712017-06-23 11:06:47 -04003497 GenerateInstruction(I);
3498 }
3499 }
3500
David Neto22f144c2017-06-12 14:26:21 -04003501 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003502 if (clspv::Option::HackInitializers()) {
3503 GenerateEntryPointInitialStores();
3504 }
David Neto22f144c2017-06-12 14:26:21 -04003505 }
3506
3507 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003508 if (!isa<AllocaInst>(I)) {
3509 GenerateInstruction(I);
3510 }
David Neto22f144c2017-06-12 14:26:21 -04003511 }
3512 }
3513}
3514
3515spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3516 const std::map<CmpInst::Predicate, spv::Op> Map = {
3517 {CmpInst::ICMP_EQ, spv::OpIEqual},
3518 {CmpInst::ICMP_NE, spv::OpINotEqual},
3519 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3520 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3521 {CmpInst::ICMP_ULT, spv::OpULessThan},
3522 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3523 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3524 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3525 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3526 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3527 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3528 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3529 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3530 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3531 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3532 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3533 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3534 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3535 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3536 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3537 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3538 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3539
3540 assert(0 != Map.count(I->getPredicate()));
3541
3542 return Map.at(I->getPredicate());
3543}
3544
3545spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3546 const std::map<unsigned, spv::Op> Map{
3547 {Instruction::Trunc, spv::OpUConvert},
3548 {Instruction::ZExt, spv::OpUConvert},
3549 {Instruction::SExt, spv::OpSConvert},
3550 {Instruction::FPToUI, spv::OpConvertFToU},
3551 {Instruction::FPToSI, spv::OpConvertFToS},
3552 {Instruction::UIToFP, spv::OpConvertUToF},
3553 {Instruction::SIToFP, spv::OpConvertSToF},
3554 {Instruction::FPTrunc, spv::OpFConvert},
3555 {Instruction::FPExt, spv::OpFConvert},
3556 {Instruction::BitCast, spv::OpBitcast}};
3557
3558 assert(0 != Map.count(I.getOpcode()));
3559
3560 return Map.at(I.getOpcode());
3561}
3562
3563spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003564 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003565 switch (I.getOpcode()) {
3566 default:
3567 break;
3568 case Instruction::Or:
3569 return spv::OpLogicalOr;
3570 case Instruction::And:
3571 return spv::OpLogicalAnd;
3572 case Instruction::Xor:
3573 return spv::OpLogicalNotEqual;
3574 }
3575 }
3576
alan-bakerb6b09dc2018-11-08 16:59:28 -05003577 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003578 {Instruction::Add, spv::OpIAdd},
3579 {Instruction::FAdd, spv::OpFAdd},
3580 {Instruction::Sub, spv::OpISub},
3581 {Instruction::FSub, spv::OpFSub},
3582 {Instruction::Mul, spv::OpIMul},
3583 {Instruction::FMul, spv::OpFMul},
3584 {Instruction::UDiv, spv::OpUDiv},
3585 {Instruction::SDiv, spv::OpSDiv},
3586 {Instruction::FDiv, spv::OpFDiv},
3587 {Instruction::URem, spv::OpUMod},
3588 {Instruction::SRem, spv::OpSRem},
3589 {Instruction::FRem, spv::OpFRem},
3590 {Instruction::Or, spv::OpBitwiseOr},
3591 {Instruction::Xor, spv::OpBitwiseXor},
3592 {Instruction::And, spv::OpBitwiseAnd},
3593 {Instruction::Shl, spv::OpShiftLeftLogical},
3594 {Instruction::LShr, spv::OpShiftRightLogical},
3595 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3596
3597 assert(0 != Map.count(I.getOpcode()));
3598
3599 return Map.at(I.getOpcode());
3600}
3601
3602void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3603 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3604 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003605 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3606 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3607
3608 // Register Instruction to ValueMap.
3609 if (0 == VMap[&I]) {
3610 VMap[&I] = nextID;
3611 }
3612
3613 switch (I.getOpcode()) {
3614 default: {
3615 if (Instruction::isCast(I.getOpcode())) {
3616 //
3617 // Generate SPIRV instructions for cast operators.
3618 //
3619
David Netod2de94a2017-08-28 17:27:47 -04003620 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003621 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003622 auto toI8 = Ty == Type::getInt8Ty(Context);
3623 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003624 // Handle zext, sext and uitofp with i1 type specially.
3625 if ((I.getOpcode() == Instruction::ZExt ||
3626 I.getOpcode() == Instruction::SExt ||
3627 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003628 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003629 //
3630 // Generate OpSelect.
3631 //
3632
3633 // Ops[0] = Result Type ID
3634 // Ops[1] = Condition ID
3635 // Ops[2] = True Constant ID
3636 // Ops[3] = False Constant ID
3637 SPIRVOperandList Ops;
3638
David Neto257c3892018-04-11 13:19:45 -04003639 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003640
David Neto22f144c2017-06-12 14:26:21 -04003641 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003642 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003643
3644 uint32_t TrueID = 0;
3645 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003646 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003647 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003648 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003649 } else {
3650 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3651 }
David Neto257c3892018-04-11 13:19:45 -04003652 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003653
3654 uint32_t FalseID = 0;
3655 if (I.getOpcode() == Instruction::ZExt) {
3656 FalseID = VMap[Constant::getNullValue(I.getType())];
3657 } else if (I.getOpcode() == Instruction::SExt) {
3658 FalseID = VMap[Constant::getNullValue(I.getType())];
3659 } else {
3660 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3661 }
David Neto257c3892018-04-11 13:19:45 -04003662 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003663
David Neto87846742018-04-11 17:36:22 -04003664 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003665 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003666 } else if (!clspv::Option::Int8Support() &&
3667 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003668 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3669 // 8 bits.
3670 // Before:
3671 // %result = trunc i32 %a to i8
3672 // After
3673 // %result = OpBitwiseAnd %uint %a %uint_255
3674
3675 SPIRVOperandList Ops;
3676
David Neto257c3892018-04-11 13:19:45 -04003677 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003678
3679 Type *UintTy = Type::getInt32Ty(Context);
3680 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003681 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003682
David Neto87846742018-04-11 17:36:22 -04003683 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003684 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003685 } else {
3686 // Ops[0] = Result Type ID
3687 // Ops[1] = Source Value ID
3688 SPIRVOperandList Ops;
3689
David Neto257c3892018-04-11 13:19:45 -04003690 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003691
David Neto87846742018-04-11 17:36:22 -04003692 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003693 SPIRVInstList.push_back(Inst);
3694 }
3695 } else if (isa<BinaryOperator>(I)) {
3696 //
3697 // Generate SPIRV instructions for binary operators.
3698 //
3699
3700 // Handle xor with i1 type specially.
3701 if (I.getOpcode() == Instruction::Xor &&
3702 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003703 ((isa<ConstantInt>(I.getOperand(0)) &&
3704 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3705 (isa<ConstantInt>(I.getOperand(1)) &&
3706 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003707 //
3708 // Generate OpLogicalNot.
3709 //
3710 // Ops[0] = Result Type ID
3711 // Ops[1] = Operand
3712 SPIRVOperandList Ops;
3713
David Neto257c3892018-04-11 13:19:45 -04003714 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003715
3716 Value *CondV = I.getOperand(0);
3717 if (isa<Constant>(I.getOperand(0))) {
3718 CondV = I.getOperand(1);
3719 }
David Neto257c3892018-04-11 13:19:45 -04003720 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003721
David Neto87846742018-04-11 17:36:22 -04003722 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003723 SPIRVInstList.push_back(Inst);
3724 } else {
3725 // Ops[0] = Result Type ID
3726 // Ops[1] = Operand 0
3727 // Ops[2] = Operand 1
3728 SPIRVOperandList Ops;
3729
David Neto257c3892018-04-11 13:19:45 -04003730 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3731 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003732
David Neto87846742018-04-11 17:36:22 -04003733 auto *Inst =
3734 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003735 SPIRVInstList.push_back(Inst);
3736 }
3737 } else {
3738 I.print(errs());
3739 llvm_unreachable("Unsupported instruction???");
3740 }
3741 break;
3742 }
3743 case Instruction::GetElementPtr: {
3744 auto &GlobalConstArgSet = getGlobalConstArgSet();
3745
3746 //
3747 // Generate OpAccessChain.
3748 //
3749 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3750
3751 //
3752 // Generate OpAccessChain.
3753 //
3754
3755 // Ops[0] = Result Type ID
3756 // Ops[1] = Base ID
3757 // Ops[2] ... Ops[n] = Indexes ID
3758 SPIRVOperandList Ops;
3759
alan-bakerb6b09dc2018-11-08 16:59:28 -05003760 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003761 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3762 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3763 // Use pointer type with private address space for global constant.
3764 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003765 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003766 }
David Neto257c3892018-04-11 13:19:45 -04003767
3768 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003769
David Neto862b7d82018-06-14 18:48:37 -04003770 // Generate the base pointer.
3771 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003772
David Neto862b7d82018-06-14 18:48:37 -04003773 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003774
3775 //
3776 // Follows below rules for gep.
3777 //
David Neto862b7d82018-06-14 18:48:37 -04003778 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3779 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003780 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3781 // first index.
3782 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3783 // use gep's first index.
3784 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3785 // gep's first index.
3786 //
3787 spv::Op Opcode = spv::OpAccessChain;
3788 unsigned offset = 0;
3789 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003790 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003791 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003792 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003793 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003794 }
David Neto862b7d82018-06-14 18:48:37 -04003795 } else {
David Neto22f144c2017-06-12 14:26:21 -04003796 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003797 }
3798
3799 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003800 // Do we need to generate ArrayStride? Check against the GEP result type
3801 // rather than the pointer type of the base because when indexing into
3802 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3803 // for something else in the SPIR-V.
3804 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003805 auto address_space = ResultType->getAddressSpace();
3806 setVariablePointersCapabilities(address_space);
3807 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003808 case spv::StorageClassStorageBuffer:
3809 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003810 // Save the need to generate an ArrayStride decoration. But defer
3811 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003812 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003813 break;
3814 default:
3815 break;
David Neto1a1a0582017-07-07 12:01:44 -04003816 }
David Neto22f144c2017-06-12 14:26:21 -04003817 }
3818
3819 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003820 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003821 }
3822
David Neto87846742018-04-11 17:36:22 -04003823 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003824 SPIRVInstList.push_back(Inst);
3825 break;
3826 }
3827 case Instruction::ExtractValue: {
3828 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3829 // Ops[0] = Result Type ID
3830 // Ops[1] = Composite ID
3831 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3832 SPIRVOperandList Ops;
3833
David Neto257c3892018-04-11 13:19:45 -04003834 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003835
3836 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003837 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003838
3839 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003840 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003841 }
3842
David Neto87846742018-04-11 17:36:22 -04003843 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003844 SPIRVInstList.push_back(Inst);
3845 break;
3846 }
3847 case Instruction::InsertValue: {
3848 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3849 // Ops[0] = Result Type ID
3850 // Ops[1] = Object ID
3851 // Ops[2] = Composite ID
3852 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3853 SPIRVOperandList Ops;
3854
3855 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003856 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003857
3858 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003859 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003860
3861 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003862 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003863
3864 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003865 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003866 }
3867
David Neto87846742018-04-11 17:36:22 -04003868 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003869 SPIRVInstList.push_back(Inst);
3870 break;
3871 }
3872 case Instruction::Select: {
3873 //
3874 // Generate OpSelect.
3875 //
3876
3877 // Ops[0] = Result Type ID
3878 // Ops[1] = Condition ID
3879 // Ops[2] = True Constant ID
3880 // Ops[3] = False Constant ID
3881 SPIRVOperandList Ops;
3882
3883 // Find SPIRV instruction for parameter type.
3884 auto Ty = I.getType();
3885 if (Ty->isPointerTy()) {
3886 auto PointeeTy = Ty->getPointerElementType();
3887 if (PointeeTy->isStructTy() &&
3888 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3889 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003890 } else {
3891 // Selecting between pointers requires variable pointers.
3892 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3893 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3894 setVariablePointers(true);
3895 }
David Neto22f144c2017-06-12 14:26:21 -04003896 }
3897 }
3898
David Neto257c3892018-04-11 13:19:45 -04003899 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3900 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003901
David Neto87846742018-04-11 17:36:22 -04003902 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003903 SPIRVInstList.push_back(Inst);
3904 break;
3905 }
3906 case Instruction::ExtractElement: {
3907 // Handle <4 x i8> type manually.
3908 Type *CompositeTy = I.getOperand(0)->getType();
3909 if (is4xi8vec(CompositeTy)) {
3910 //
3911 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3912 // <4 x i8>.
3913 //
3914
3915 //
3916 // Generate OpShiftRightLogical
3917 //
3918 // Ops[0] = Result Type ID
3919 // Ops[1] = Operand 0
3920 // Ops[2] = Operand 1
3921 //
3922 SPIRVOperandList Ops;
3923
David Neto257c3892018-04-11 13:19:45 -04003924 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003925
3926 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003927 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003928
3929 uint32_t Op1ID = 0;
3930 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3931 // Handle constant index.
3932 uint64_t Idx = CI->getZExtValue();
3933 Value *ShiftAmount =
3934 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3935 Op1ID = VMap[ShiftAmount];
3936 } else {
3937 // Handle variable index.
3938 SPIRVOperandList TmpOps;
3939
David Neto257c3892018-04-11 13:19:45 -04003940 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3941 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003942
3943 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003944 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003945
3946 Op1ID = nextID;
3947
David Neto87846742018-04-11 17:36:22 -04003948 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003949 SPIRVInstList.push_back(TmpInst);
3950 }
David Neto257c3892018-04-11 13:19:45 -04003951 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003952
3953 uint32_t ShiftID = nextID;
3954
David Neto87846742018-04-11 17:36:22 -04003955 auto *Inst =
3956 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003957 SPIRVInstList.push_back(Inst);
3958
3959 //
3960 // Generate OpBitwiseAnd
3961 //
3962 // Ops[0] = Result Type ID
3963 // Ops[1] = Operand 0
3964 // Ops[2] = Operand 1
3965 //
3966 Ops.clear();
3967
David Neto257c3892018-04-11 13:19:45 -04003968 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003969
3970 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003971 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003972
David Neto9b2d6252017-09-06 15:47:37 -04003973 // Reset mapping for this value to the result of the bitwise and.
3974 VMap[&I] = nextID;
3975
David Neto87846742018-04-11 17:36:22 -04003976 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003977 SPIRVInstList.push_back(Inst);
3978 break;
3979 }
3980
3981 // Ops[0] = Result Type ID
3982 // Ops[1] = Composite ID
3983 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3984 SPIRVOperandList Ops;
3985
David Neto257c3892018-04-11 13:19:45 -04003986 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003987
3988 spv::Op Opcode = spv::OpCompositeExtract;
3989 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003990 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003991 } else {
David Neto257c3892018-04-11 13:19:45 -04003992 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003993 Opcode = spv::OpVectorExtractDynamic;
3994 }
3995
David Neto87846742018-04-11 17:36:22 -04003996 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003997 SPIRVInstList.push_back(Inst);
3998 break;
3999 }
4000 case Instruction::InsertElement: {
4001 // Handle <4 x i8> type manually.
4002 Type *CompositeTy = I.getOperand(0)->getType();
4003 if (is4xi8vec(CompositeTy)) {
4004 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4005 uint32_t CstFFID = VMap[CstFF];
4006
4007 uint32_t ShiftAmountID = 0;
4008 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4009 // Handle constant index.
4010 uint64_t Idx = CI->getZExtValue();
4011 Value *ShiftAmount =
4012 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4013 ShiftAmountID = VMap[ShiftAmount];
4014 } else {
4015 // Handle variable index.
4016 SPIRVOperandList TmpOps;
4017
David Neto257c3892018-04-11 13:19:45 -04004018 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4019 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004020
4021 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004022 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004023
4024 ShiftAmountID = nextID;
4025
David Neto87846742018-04-11 17:36:22 -04004026 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004027 SPIRVInstList.push_back(TmpInst);
4028 }
4029
4030 //
4031 // Generate mask operations.
4032 //
4033
4034 // ShiftLeft mask according to index of insertelement.
4035 SPIRVOperandList Ops;
4036
David Neto257c3892018-04-11 13:19:45 -04004037 const uint32_t ResTyID = lookupType(CompositeTy);
4038 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004039
4040 uint32_t MaskID = nextID;
4041
David Neto87846742018-04-11 17:36:22 -04004042 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004043 SPIRVInstList.push_back(Inst);
4044
4045 // Inverse mask.
4046 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004047 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004048
4049 uint32_t InvMaskID = nextID;
4050
David Neto87846742018-04-11 17:36:22 -04004051 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004052 SPIRVInstList.push_back(Inst);
4053
4054 // Apply mask.
4055 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004056 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004057
4058 uint32_t OrgValID = nextID;
4059
David Neto87846742018-04-11 17:36:22 -04004060 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004061 SPIRVInstList.push_back(Inst);
4062
4063 // Create correct value according to index of insertelement.
4064 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004065 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4066 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004067
4068 uint32_t InsertValID = nextID;
4069
David Neto87846742018-04-11 17:36:22 -04004070 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004071 SPIRVInstList.push_back(Inst);
4072
4073 // Insert value to original value.
4074 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004075 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004076
David Netoa394f392017-08-26 20:45:29 -04004077 VMap[&I] = nextID;
4078
David Neto87846742018-04-11 17:36:22 -04004079 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004080 SPIRVInstList.push_back(Inst);
4081
4082 break;
4083 }
4084
David Neto22f144c2017-06-12 14:26:21 -04004085 SPIRVOperandList Ops;
4086
James Priced26efea2018-06-09 23:28:32 +01004087 // Ops[0] = Result Type ID
4088 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004089
4090 spv::Op Opcode = spv::OpCompositeInsert;
4091 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004092 const auto value = CI->getZExtValue();
4093 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004094 // Ops[1] = Object ID
4095 // Ops[2] = Composite ID
4096 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004097 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004098 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004099 } else {
James Priced26efea2018-06-09 23:28:32 +01004100 // Ops[1] = Composite ID
4101 // Ops[2] = Object ID
4102 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004103 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004104 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004105 Opcode = spv::OpVectorInsertDynamic;
4106 }
4107
David Neto87846742018-04-11 17:36:22 -04004108 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004109 SPIRVInstList.push_back(Inst);
4110 break;
4111 }
4112 case Instruction::ShuffleVector: {
4113 // Ops[0] = Result Type ID
4114 // Ops[1] = Vector 1 ID
4115 // Ops[2] = Vector 2 ID
4116 // Ops[3] ... Ops[n] = Components (Literal Number)
4117 SPIRVOperandList Ops;
4118
David Neto257c3892018-04-11 13:19:45 -04004119 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4120 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004121
4122 uint64_t NumElements = 0;
4123 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4124 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4125
4126 if (Cst->isNullValue()) {
4127 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004128 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004129 }
4130 } else if (const ConstantDataSequential *CDS =
4131 dyn_cast<ConstantDataSequential>(Cst)) {
4132 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4133 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004134 const auto value = CDS->getElementAsInteger(i);
4135 assert(value <= UINT32_MAX);
4136 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004137 }
4138 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4139 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4140 auto Op = CV->getOperand(i);
4141
4142 uint32_t literal = 0;
4143
4144 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4145 literal = static_cast<uint32_t>(CI->getZExtValue());
4146 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4147 literal = 0xFFFFFFFFu;
4148 } else {
4149 Op->print(errs());
4150 llvm_unreachable("Unsupported element in ConstantVector!");
4151 }
4152
David Neto257c3892018-04-11 13:19:45 -04004153 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004154 }
4155 } else {
4156 Cst->print(errs());
4157 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4158 }
4159 }
4160
David Neto87846742018-04-11 17:36:22 -04004161 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004162 SPIRVInstList.push_back(Inst);
4163 break;
4164 }
4165 case Instruction::ICmp:
4166 case Instruction::FCmp: {
4167 CmpInst *CmpI = cast<CmpInst>(&I);
4168
David Netod4ca2e62017-07-06 18:47:35 -04004169 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004170 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004171 if (isa<PointerType>(ArgTy)) {
4172 CmpI->print(errs());
4173 std::string name = I.getParent()->getParent()->getName();
4174 errs()
4175 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4176 << "in function " << name << "\n";
4177 llvm_unreachable("Pointer equality check is invalid");
4178 break;
4179 }
4180
David Neto257c3892018-04-11 13:19:45 -04004181 // Ops[0] = Result Type ID
4182 // Ops[1] = Operand 1 ID
4183 // Ops[2] = Operand 2 ID
4184 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004185
David Neto257c3892018-04-11 13:19:45 -04004186 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4187 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004188
4189 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004190 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004191 SPIRVInstList.push_back(Inst);
4192 break;
4193 }
4194 case Instruction::Br: {
4195 // Branch instrucion is deferred because it needs label's ID. Record slot's
4196 // location on SPIRVInstructionList.
4197 DeferredInsts.push_back(
4198 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4199 break;
4200 }
4201 case Instruction::Switch: {
4202 I.print(errs());
4203 llvm_unreachable("Unsupported instruction???");
4204 break;
4205 }
4206 case Instruction::IndirectBr: {
4207 I.print(errs());
4208 llvm_unreachable("Unsupported instruction???");
4209 break;
4210 }
4211 case Instruction::PHI: {
4212 // Branch instrucion is deferred because it needs label's ID. Record slot's
4213 // location on SPIRVInstructionList.
4214 DeferredInsts.push_back(
4215 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4216 break;
4217 }
4218 case Instruction::Alloca: {
4219 //
4220 // Generate OpVariable.
4221 //
4222 // Ops[0] : Result Type ID
4223 // Ops[1] : Storage Class
4224 SPIRVOperandList Ops;
4225
David Neto257c3892018-04-11 13:19:45 -04004226 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004227
David Neto87846742018-04-11 17:36:22 -04004228 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004229 SPIRVInstList.push_back(Inst);
4230 break;
4231 }
4232 case Instruction::Load: {
4233 LoadInst *LD = cast<LoadInst>(&I);
4234 //
4235 // Generate OpLoad.
4236 //
alan-baker5b86ed72019-02-15 08:26:50 -05004237
4238 if (LD->getType()->isPointerTy()) {
4239 // Loading a pointer requires variable pointers.
4240 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4241 }
David Neto22f144c2017-06-12 14:26:21 -04004242
David Neto0a2f98d2017-09-15 19:38:40 -04004243 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004244 uint32_t PointerID = VMap[LD->getPointerOperand()];
4245
4246 // This is a hack to work around what looks like a driver bug.
4247 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004248 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4249 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004250 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004251 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004252 // Generate a bitwise-and of the original value with itself.
4253 // We should have been able to get away with just an OpCopyObject,
4254 // but we need something more complex to get past certain driver bugs.
4255 // This is ridiculous, but necessary.
4256 // TODO(dneto): Revisit this once drivers fix their bugs.
4257
4258 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004259 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4260 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004261
David Neto87846742018-04-11 17:36:22 -04004262 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004263 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004264 break;
4265 }
4266
4267 // This is the normal path. Generate a load.
4268
David Neto22f144c2017-06-12 14:26:21 -04004269 // Ops[0] = Result Type ID
4270 // Ops[1] = Pointer ID
4271 // Ops[2] ... Ops[n] = Optional Memory Access
4272 //
4273 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004274
David Neto22f144c2017-06-12 14:26:21 -04004275 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004276 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004277
David Neto87846742018-04-11 17:36:22 -04004278 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004279 SPIRVInstList.push_back(Inst);
4280 break;
4281 }
4282 case Instruction::Store: {
4283 StoreInst *ST = cast<StoreInst>(&I);
4284 //
4285 // Generate OpStore.
4286 //
4287
alan-baker5b86ed72019-02-15 08:26:50 -05004288 if (ST->getValueOperand()->getType()->isPointerTy()) {
4289 // Storing a pointer requires variable pointers.
4290 setVariablePointersCapabilities(
4291 ST->getValueOperand()->getType()->getPointerAddressSpace());
4292 }
4293
David Neto22f144c2017-06-12 14:26:21 -04004294 // Ops[0] = Pointer ID
4295 // Ops[1] = Object ID
4296 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4297 //
4298 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004299 SPIRVOperandList Ops;
4300 Ops << MkId(VMap[ST->getPointerOperand()])
4301 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004302
David Neto87846742018-04-11 17:36:22 -04004303 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004304 SPIRVInstList.push_back(Inst);
4305 break;
4306 }
4307 case Instruction::AtomicCmpXchg: {
4308 I.print(errs());
4309 llvm_unreachable("Unsupported instruction???");
4310 break;
4311 }
4312 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004313 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4314
4315 spv::Op opcode;
4316
4317 switch (AtomicRMW->getOperation()) {
4318 default:
4319 I.print(errs());
4320 llvm_unreachable("Unsupported instruction???");
4321 case llvm::AtomicRMWInst::Add:
4322 opcode = spv::OpAtomicIAdd;
4323 break;
4324 case llvm::AtomicRMWInst::Sub:
4325 opcode = spv::OpAtomicISub;
4326 break;
4327 case llvm::AtomicRMWInst::Xchg:
4328 opcode = spv::OpAtomicExchange;
4329 break;
4330 case llvm::AtomicRMWInst::Min:
4331 opcode = spv::OpAtomicSMin;
4332 break;
4333 case llvm::AtomicRMWInst::Max:
4334 opcode = spv::OpAtomicSMax;
4335 break;
4336 case llvm::AtomicRMWInst::UMin:
4337 opcode = spv::OpAtomicUMin;
4338 break;
4339 case llvm::AtomicRMWInst::UMax:
4340 opcode = spv::OpAtomicUMax;
4341 break;
4342 case llvm::AtomicRMWInst::And:
4343 opcode = spv::OpAtomicAnd;
4344 break;
4345 case llvm::AtomicRMWInst::Or:
4346 opcode = spv::OpAtomicOr;
4347 break;
4348 case llvm::AtomicRMWInst::Xor:
4349 opcode = spv::OpAtomicXor;
4350 break;
4351 }
4352
4353 //
4354 // Generate OpAtomic*.
4355 //
4356 SPIRVOperandList Ops;
4357
David Neto257c3892018-04-11 13:19:45 -04004358 Ops << MkId(lookupType(I.getType()))
4359 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004360
4361 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004362 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004364
4365 const auto ConstantMemorySemantics = ConstantInt::get(
4366 IntTy, spv::MemorySemanticsUniformMemoryMask |
4367 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004368 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004369
David Neto257c3892018-04-11 13:19:45 -04004370 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004371
4372 VMap[&I] = nextID;
4373
David Neto87846742018-04-11 17:36:22 -04004374 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004375 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004376 break;
4377 }
4378 case Instruction::Fence: {
4379 I.print(errs());
4380 llvm_unreachable("Unsupported instruction???");
4381 break;
4382 }
4383 case Instruction::Call: {
4384 CallInst *Call = dyn_cast<CallInst>(&I);
4385 Function *Callee = Call->getCalledFunction();
4386
Alan Baker202c8c72018-08-13 13:47:44 -04004387 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004388 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4389 // Generate an OpLoad
4390 SPIRVOperandList Ops;
4391 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004392
David Neto862b7d82018-06-14 18:48:37 -04004393 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4394 << MkId(ResourceVarDeferredLoadCalls[Call]);
4395
4396 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4397 SPIRVInstList.push_back(Inst);
4398 VMap[Call] = load_id;
4399 break;
4400
4401 } else {
4402 // This maps to an OpVariable we've already generated.
4403 // No code is generated for the call.
4404 }
4405 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004406 } else if (Callee->getName().startswith(
4407 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004408 // Don't codegen an instruction here, but instead map this call directly
4409 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004410 int spec_id = static_cast<int>(
4411 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004412 const auto &info = LocalSpecIdInfoMap[spec_id];
4413 VMap[Call] = info.variable_id;
4414 break;
David Neto862b7d82018-06-14 18:48:37 -04004415 }
4416
4417 // Sampler initializers become a load of the corresponding sampler.
4418
Kévin Petitdf71de32019-04-09 14:09:50 +01004419 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004420 // Map this to a load from the variable.
4421 const auto index_into_sampler_map =
4422 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4423
4424 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004425 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004426 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004427
David Neto257c3892018-04-11 13:19:45 -04004428 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004429 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4430 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004431
David Neto862b7d82018-06-14 18:48:37 -04004432 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004433 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004434 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004435 break;
4436 }
4437
Kévin Petit349c9502019-03-28 17:24:14 +00004438 // Handle SPIR-V intrinsics
4439 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
Kévin Petit349c9502019-03-28 17:24:14 +00004440 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4441 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4442 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4443 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4444 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4445 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
4446 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4447 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4448 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4449 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4450 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4451 .Case("spirv.atomic_or", spv::OpAtomicOr)
4452 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4453 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4454 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
Kévin Petitfd6c24f2019-04-03 15:30:59 +01004455 .StartsWith("spirv.store_null", spv::OpStore)
Kévin Petit349c9502019-03-28 17:24:14 +00004456 .StartsWith("__spirv_isinf", spv::OpIsInf)
4457 .StartsWith("__spirv_isnan", spv::OpIsNan)
4458 .StartsWith("__spirv_allDv", spv::OpAll)
4459 .StartsWith("__spirv_anyDv", spv::OpAny)
4460 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004461
Kévin Petit617a76d2019-04-04 13:54:16 +01004462 // If the switch above didn't have an entry maybe the intrinsic
4463 // is using the name mangling logic.
4464 bool usesMangler = false;
4465 if (opcode == spv::OpNop) {
4466 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4467 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4468 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4469 usesMangler = true;
4470 }
4471 }
4472
Kévin Petit349c9502019-03-28 17:24:14 +00004473 if (opcode != spv::OpNop) {
4474
David Neto22f144c2017-06-12 14:26:21 -04004475 SPIRVOperandList Ops;
4476
Kévin Petit349c9502019-03-28 17:24:14 +00004477 if (!I.getType()->isVoidTy()) {
4478 Ops << MkId(lookupType(I.getType()));
4479 }
David Neto22f144c2017-06-12 14:26:21 -04004480
Kévin Petit617a76d2019-04-04 13:54:16 +01004481 unsigned firstOperand = usesMangler ? 1 : 0;
4482 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004483 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004484 }
4485
Kévin Petit349c9502019-03-28 17:24:14 +00004486 if (!I.getType()->isVoidTy()) {
4487 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004488 }
4489
Kévin Petit349c9502019-03-28 17:24:14 +00004490 SPIRVInstruction *Inst;
4491 if (!I.getType()->isVoidTy()) {
4492 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4493 } else {
4494 Inst = new SPIRVInstruction(opcode, Ops);
4495 }
Kévin Petit8a560882019-03-21 15:24:34 +00004496 SPIRVInstList.push_back(Inst);
4497 break;
4498 }
4499
David Neto22f144c2017-06-12 14:26:21 -04004500 if (Callee->getName().startswith("_Z3dot")) {
4501 // If the argument is a vector type, generate OpDot
4502 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4503 //
4504 // Generate OpDot.
4505 //
4506 SPIRVOperandList Ops;
4507
David Neto257c3892018-04-11 13:19:45 -04004508 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004509
4510 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004511 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004512 }
4513
4514 VMap[&I] = nextID;
4515
David Neto87846742018-04-11 17:36:22 -04004516 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004517 SPIRVInstList.push_back(Inst);
4518 } else {
4519 //
4520 // Generate OpFMul.
4521 //
4522 SPIRVOperandList Ops;
4523
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004525
4526 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004527 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004528 }
4529
4530 VMap[&I] = nextID;
4531
David Neto87846742018-04-11 17:36:22 -04004532 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004533 SPIRVInstList.push_back(Inst);
4534 }
4535 break;
4536 }
4537
David Neto8505ebf2017-10-13 18:50:50 -04004538 if (Callee->getName().startswith("_Z4fmod")) {
4539 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4540 // The sign for a non-zero result is taken from x.
4541 // (Try an example.)
4542 // So translate to OpFRem
4543
4544 SPIRVOperandList Ops;
4545
David Neto257c3892018-04-11 13:19:45 -04004546 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004547
4548 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004549 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004550 }
4551
4552 VMap[&I] = nextID;
4553
David Neto87846742018-04-11 17:36:22 -04004554 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004555 SPIRVInstList.push_back(Inst);
4556 break;
4557 }
4558
David Neto22f144c2017-06-12 14:26:21 -04004559 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4560 if (Callee->getName().startswith("spirv.copy_memory")) {
4561 //
4562 // Generate OpCopyMemory.
4563 //
4564
4565 // Ops[0] = Dst ID
4566 // Ops[1] = Src ID
4567 // Ops[2] = Memory Access
4568 // Ops[3] = Alignment
4569
4570 auto IsVolatile =
4571 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4572
4573 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4574 : spv::MemoryAccessMaskNone;
4575
4576 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4577
4578 auto Alignment =
4579 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4580
David Neto257c3892018-04-11 13:19:45 -04004581 SPIRVOperandList Ops;
4582 Ops << MkId(VMap[Call->getArgOperand(0)])
4583 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4584 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004585
David Neto87846742018-04-11 17:36:22 -04004586 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004587
4588 SPIRVInstList.push_back(Inst);
4589
4590 break;
4591 }
4592
David Neto22f144c2017-06-12 14:26:21 -04004593 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4594 // Additionally, OpTypeSampledImage is generated.
4595 if (Callee->getName().equals(
4596 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4597 Callee->getName().equals(
4598 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4599 //
4600 // Generate OpSampledImage.
4601 //
4602 // Ops[0] = Result Type ID
4603 // Ops[1] = Image ID
4604 // Ops[2] = Sampler ID
4605 //
4606 SPIRVOperandList Ops;
4607
4608 Value *Image = Call->getArgOperand(0);
4609 Value *Sampler = Call->getArgOperand(1);
4610 Value *Coordinate = Call->getArgOperand(2);
4611
4612 TypeMapType &OpImageTypeMap = getImageTypeMap();
4613 Type *ImageTy = Image->getType()->getPointerElementType();
4614 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004615 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004616 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004617
4618 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004619
4620 uint32_t SampledImageID = nextID;
4621
David Neto87846742018-04-11 17:36:22 -04004622 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004623 SPIRVInstList.push_back(Inst);
4624
4625 //
4626 // Generate OpImageSampleExplicitLod.
4627 //
4628 // Ops[0] = Result Type ID
4629 // Ops[1] = Sampled Image ID
4630 // Ops[2] = Coordinate ID
4631 // Ops[3] = Image Operands Type ID
4632 // Ops[4] ... Ops[n] = Operands ID
4633 //
4634 Ops.clear();
4635
David Neto257c3892018-04-11 13:19:45 -04004636 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4637 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004638
4639 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004640 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004641
4642 VMap[&I] = nextID;
4643
David Neto87846742018-04-11 17:36:22 -04004644 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004645 SPIRVInstList.push_back(Inst);
4646 break;
4647 }
4648
4649 // write_imagef is mapped to OpImageWrite.
4650 if (Callee->getName().equals(
4651 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4652 Callee->getName().equals(
4653 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4654 //
4655 // Generate OpImageWrite.
4656 //
4657 // Ops[0] = Image ID
4658 // Ops[1] = Coordinate ID
4659 // Ops[2] = Texel ID
4660 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4661 // Ops[4] ... Ops[n] = (Optional) Operands ID
4662 //
4663 SPIRVOperandList Ops;
4664
4665 Value *Image = Call->getArgOperand(0);
4666 Value *Coordinate = Call->getArgOperand(1);
4667 Value *Texel = Call->getArgOperand(2);
4668
4669 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004670 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004671 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004672 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004673
David Neto87846742018-04-11 17:36:22 -04004674 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004675 SPIRVInstList.push_back(Inst);
4676 break;
4677 }
4678
David Neto5c22a252018-03-15 16:07:41 -04004679 // get_image_width is mapped to OpImageQuerySize
4680 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4681 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4682 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4683 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4684 //
4685 // Generate OpImageQuerySize, then pull out the right component.
4686 // Assume 2D image for now.
4687 //
4688 // Ops[0] = Image ID
4689 //
4690 // %sizes = OpImageQuerySizes %uint2 %im
4691 // %result = OpCompositeExtract %uint %sizes 0-or-1
4692 SPIRVOperandList Ops;
4693
4694 // Implement:
4695 // %sizes = OpImageQuerySizes %uint2 %im
4696 uint32_t SizesTypeID =
4697 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004698 Value *Image = Call->getArgOperand(0);
4699 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004700 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004701
4702 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004703 auto *QueryInst =
4704 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004705 SPIRVInstList.push_back(QueryInst);
4706
4707 // Reset value map entry since we generated an intermediate instruction.
4708 VMap[&I] = nextID;
4709
4710 // Implement:
4711 // %result = OpCompositeExtract %uint %sizes 0-or-1
4712 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004713 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004714
4715 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004716 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004717
David Neto87846742018-04-11 17:36:22 -04004718 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004719 SPIRVInstList.push_back(Inst);
4720 break;
4721 }
4722
David Neto22f144c2017-06-12 14:26:21 -04004723 // Call instrucion is deferred because it needs function's ID. Record
4724 // slot's location on SPIRVInstructionList.
4725 DeferredInsts.push_back(
4726 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4727
David Neto3fbb4072017-10-16 11:28:14 -04004728 // Check whether the implementation of this call uses an extended
4729 // instruction plus one more value-producing instruction. If so, then
4730 // reserve the id for the extra value-producing slot.
4731 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4732 if (EInst != kGlslExtInstBad) {
4733 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004734 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004735 VMap[&I] = nextID;
4736 nextID++;
4737 }
4738 break;
4739 }
4740 case Instruction::Ret: {
4741 unsigned NumOps = I.getNumOperands();
4742 if (NumOps == 0) {
4743 //
4744 // Generate OpReturn.
4745 //
David Neto87846742018-04-11 17:36:22 -04004746 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004747 } else {
4748 //
4749 // Generate OpReturnValue.
4750 //
4751
4752 // Ops[0] = Return Value ID
4753 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004754
4755 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004756
David Neto87846742018-04-11 17:36:22 -04004757 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004758 SPIRVInstList.push_back(Inst);
4759 break;
4760 }
4761 break;
4762 }
4763 }
4764}
4765
4766void SPIRVProducerPass::GenerateFuncEpilogue() {
4767 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4768
4769 //
4770 // Generate OpFunctionEnd
4771 //
4772
David Neto87846742018-04-11 17:36:22 -04004773 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004774 SPIRVInstList.push_back(Inst);
4775}
4776
4777bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004778 // Don't specialize <4 x i8> if i8 is generally supported.
4779 if (clspv::Option::Int8Support())
4780 return false;
4781
David Neto22f144c2017-06-12 14:26:21 -04004782 LLVMContext &Context = Ty->getContext();
4783 if (Ty->isVectorTy()) {
4784 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4785 Ty->getVectorNumElements() == 4) {
4786 return true;
4787 }
4788 }
4789
4790 return false;
4791}
4792
David Neto257c3892018-04-11 13:19:45 -04004793uint32_t SPIRVProducerPass::GetI32Zero() {
4794 if (0 == constant_i32_zero_id_) {
4795 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4796 "defined in the SPIR-V module");
4797 }
4798 return constant_i32_zero_id_;
4799}
4800
David Neto22f144c2017-06-12 14:26:21 -04004801void SPIRVProducerPass::HandleDeferredInstruction() {
4802 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4803 ValueMapType &VMap = getValueMap();
4804 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4805
4806 for (auto DeferredInst = DeferredInsts.rbegin();
4807 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4808 Value *Inst = std::get<0>(*DeferredInst);
4809 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4810 if (InsertPoint != SPIRVInstList.end()) {
4811 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4812 ++InsertPoint;
4813 }
4814 }
4815
4816 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4817 // Check whether basic block, which has this branch instruction, is loop
4818 // header or not. If it is loop header, generate OpLoopMerge and
4819 // OpBranchConditional.
4820 Function *Func = Br->getParent()->getParent();
4821 DominatorTree &DT =
4822 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4823 const LoopInfo &LI =
4824 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4825
4826 BasicBlock *BrBB = Br->getParent();
4827 if (LI.isLoopHeader(BrBB)) {
4828 Value *ContinueBB = nullptr;
4829 Value *MergeBB = nullptr;
4830
4831 Loop *L = LI.getLoopFor(BrBB);
4832 MergeBB = L->getExitBlock();
4833 if (!MergeBB) {
4834 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4835 // has regions with single entry/exit. As a result, loop should not
4836 // have multiple exits.
4837 llvm_unreachable("Loop has multiple exits???");
4838 }
4839
4840 if (L->isLoopLatch(BrBB)) {
4841 ContinueBB = BrBB;
4842 } else {
4843 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4844 // block.
4845 BasicBlock *Header = L->getHeader();
4846 BasicBlock *Latch = L->getLoopLatch();
4847 for (BasicBlock *BB : L->blocks()) {
4848 if (BB == Header) {
4849 continue;
4850 }
4851
4852 // Check whether block dominates block with back-edge.
4853 if (DT.dominates(BB, Latch)) {
4854 ContinueBB = BB;
4855 }
4856 }
4857
4858 if (!ContinueBB) {
4859 llvm_unreachable("Wrong continue block from loop");
4860 }
4861 }
4862
4863 //
4864 // Generate OpLoopMerge.
4865 //
4866 // Ops[0] = Merge Block ID
4867 // Ops[1] = Continue Target ID
4868 // Ops[2] = Selection Control
4869 SPIRVOperandList Ops;
4870
4871 // StructurizeCFG pass already manipulated CFG. Just use false block of
4872 // branch instruction as merge block.
4873 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004874 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004875 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4876 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004877
David Neto87846742018-04-11 17:36:22 -04004878 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004879 SPIRVInstList.insert(InsertPoint, MergeInst);
4880
4881 } else if (Br->isConditional()) {
4882 bool HasBackEdge = false;
4883
4884 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4885 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4886 HasBackEdge = true;
4887 }
4888 }
4889 if (!HasBackEdge) {
4890 //
4891 // Generate OpSelectionMerge.
4892 //
4893 // Ops[0] = Merge Block ID
4894 // Ops[1] = Selection Control
4895 SPIRVOperandList Ops;
4896
4897 // StructurizeCFG pass already manipulated CFG. Just use false block
4898 // of branch instruction as merge block.
4899 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004900 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004901
David Neto87846742018-04-11 17:36:22 -04004902 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004903 SPIRVInstList.insert(InsertPoint, MergeInst);
4904 }
4905 }
4906
4907 if (Br->isConditional()) {
4908 //
4909 // Generate OpBranchConditional.
4910 //
4911 // Ops[0] = Condition ID
4912 // Ops[1] = True Label ID
4913 // Ops[2] = False Label ID
4914 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4915 SPIRVOperandList Ops;
4916
4917 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004918 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004919 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004920
4921 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004922
David Neto87846742018-04-11 17:36:22 -04004923 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004924 SPIRVInstList.insert(InsertPoint, BrInst);
4925 } else {
4926 //
4927 // Generate OpBranch.
4928 //
4929 // Ops[0] = Target Label ID
4930 SPIRVOperandList Ops;
4931
4932 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004933 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004934
David Neto87846742018-04-11 17:36:22 -04004935 SPIRVInstList.insert(InsertPoint,
4936 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004937 }
4938 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004939 if (PHI->getType()->isPointerTy()) {
4940 // OpPhi on pointers requires variable pointers.
4941 setVariablePointersCapabilities(
4942 PHI->getType()->getPointerAddressSpace());
4943 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4944 setVariablePointers(true);
4945 }
4946 }
4947
David Neto22f144c2017-06-12 14:26:21 -04004948 //
4949 // Generate OpPhi.
4950 //
4951 // Ops[0] = Result Type ID
4952 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4953 SPIRVOperandList Ops;
4954
David Neto257c3892018-04-11 13:19:45 -04004955 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004956
David Neto22f144c2017-06-12 14:26:21 -04004957 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4958 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004959 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004960 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004961 }
4962
4963 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004964 InsertPoint,
4965 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004966 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4967 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004968 auto callee_name = Callee->getName();
4969 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004970
4971 if (EInst) {
4972 uint32_t &ExtInstImportID = getOpExtInstImportID();
4973
4974 //
4975 // Generate OpExtInst.
4976 //
4977
4978 // Ops[0] = Result Type ID
4979 // Ops[1] = Set ID (OpExtInstImport ID)
4980 // Ops[2] = Instruction Number (Literal Number)
4981 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4982 SPIRVOperandList Ops;
4983
David Neto862b7d82018-06-14 18:48:37 -04004984 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4985 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004986
David Neto22f144c2017-06-12 14:26:21 -04004987 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4988 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004989 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004990 }
4991
David Neto87846742018-04-11 17:36:22 -04004992 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4993 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004994 SPIRVInstList.insert(InsertPoint, ExtInst);
4995
David Neto3fbb4072017-10-16 11:28:14 -04004996 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4997 if (IndirectExtInst != kGlslExtInstBad) {
4998 // Generate one more instruction that uses the result of the extended
4999 // instruction. Its result id is one more than the id of the
5000 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005001 LLVMContext &Context =
5002 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005003
David Neto3fbb4072017-10-16 11:28:14 -04005004 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5005 &VMap, &SPIRVInstList, &InsertPoint](
5006 spv::Op opcode, Constant *constant) {
5007 //
5008 // Generate instruction like:
5009 // result = opcode constant <extinst-result>
5010 //
5011 // Ops[0] = Result Type ID
5012 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5013 // Ops[2] = Operand 1 ;; the result of the extended instruction
5014 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005015
David Neto3fbb4072017-10-16 11:28:14 -04005016 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005017 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005018
5019 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5020 constant = ConstantVector::getSplat(
5021 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5022 }
David Neto257c3892018-04-11 13:19:45 -04005023 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005024
5025 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005026 InsertPoint, new SPIRVInstruction(
5027 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005028 };
5029
5030 switch (IndirectExtInst) {
5031 case glsl::ExtInstFindUMsb: // Implementing clz
5032 generate_extra_inst(
5033 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5034 break;
5035 case glsl::ExtInstAcos: // Implementing acospi
5036 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005037 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005038 case glsl::ExtInstAtan2: // Implementing atan2pi
5039 generate_extra_inst(
5040 spv::OpFMul,
5041 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5042 break;
5043
5044 default:
5045 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005046 }
David Neto22f144c2017-06-12 14:26:21 -04005047 }
David Neto3fbb4072017-10-16 11:28:14 -04005048
alan-bakerb39c8262019-03-08 14:03:37 -05005049 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005050 //
5051 // Generate OpBitCount
5052 //
5053 // Ops[0] = Result Type ID
5054 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005055 SPIRVOperandList Ops;
5056 Ops << MkId(lookupType(Call->getType()))
5057 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005058
5059 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005060 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005061 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005062
David Neto862b7d82018-06-14 18:48:37 -04005063 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005064
5065 // Generate an OpCompositeConstruct
5066 SPIRVOperandList Ops;
5067
5068 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005069 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005070
5071 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005072 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005073 }
5074
5075 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005076 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5077 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005078
Alan Baker202c8c72018-08-13 13:47:44 -04005079 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5080
5081 // We have already mapped the call's result value to an ID.
5082 // Don't generate any code now.
5083
5084 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005085
5086 // We have already mapped the call's result value to an ID.
5087 // Don't generate any code now.
5088
David Neto22f144c2017-06-12 14:26:21 -04005089 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005090 if (Call->getType()->isPointerTy()) {
5091 // Functions returning pointers require variable pointers.
5092 setVariablePointersCapabilities(
5093 Call->getType()->getPointerAddressSpace());
5094 }
5095
David Neto22f144c2017-06-12 14:26:21 -04005096 //
5097 // Generate OpFunctionCall.
5098 //
5099
5100 // Ops[0] = Result Type ID
5101 // Ops[1] = Callee Function ID
5102 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5103 SPIRVOperandList Ops;
5104
David Neto862b7d82018-06-14 18:48:37 -04005105 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005106
5107 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005108 if (CalleeID == 0) {
5109 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005110 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005111 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5112 // causes an infinite loop. Instead, go ahead and generate
5113 // the bad function call. A validator will catch the 0-Id.
5114 // llvm_unreachable("Can't translate function call");
5115 }
David Neto22f144c2017-06-12 14:26:21 -04005116
David Neto257c3892018-04-11 13:19:45 -04005117 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005118
David Neto22f144c2017-06-12 14:26:21 -04005119 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5120 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005121 auto *operand = Call->getOperand(i);
5122 if (operand->getType()->isPointerTy()) {
5123 auto sc =
5124 GetStorageClass(operand->getType()->getPointerAddressSpace());
5125 if (sc == spv::StorageClassStorageBuffer) {
5126 // Passing SSBO by reference requires variable pointers storage
5127 // buffer.
5128 setVariablePointersStorageBuffer(true);
5129 } else if (sc == spv::StorageClassWorkgroup) {
5130 // Workgroup references require variable pointers if they are not
5131 // memory object declarations.
5132 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5133 // Workgroup accessor represents a variable reference.
5134 if (!operand_call->getCalledFunction()->getName().startswith(
5135 clspv::WorkgroupAccessorFunction()))
5136 setVariablePointers(true);
5137 } else {
5138 // Arguments are function parameters.
5139 if (!isa<Argument>(operand))
5140 setVariablePointers(true);
5141 }
5142 }
5143 }
5144 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005145 }
5146
David Neto87846742018-04-11 17:36:22 -04005147 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5148 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005149 SPIRVInstList.insert(InsertPoint, CallInst);
5150 }
5151 }
5152 }
5153}
5154
David Neto1a1a0582017-07-07 12:01:44 -04005155void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005156 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005157 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005158 }
David Neto1a1a0582017-07-07 12:01:44 -04005159
5160 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005161
5162 // Find an iterator pointing just past the last decoration.
5163 bool seen_decorations = false;
5164 auto DecoInsertPoint =
5165 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5166 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5167 const bool is_decoration =
5168 Inst->getOpcode() == spv::OpDecorate ||
5169 Inst->getOpcode() == spv::OpMemberDecorate;
5170 if (is_decoration) {
5171 seen_decorations = true;
5172 return false;
5173 } else {
5174 return seen_decorations;
5175 }
5176 });
5177
David Netoc6f3ab22018-04-06 18:02:31 -04005178 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5179 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005180 for (auto *type : getTypesNeedingArrayStride()) {
5181 Type *elemTy = nullptr;
5182 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5183 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005184 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005185 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005186 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005187 elemTy = seqTy->getSequentialElementType();
5188 } else {
5189 errs() << "Unhandled strided type " << *type << "\n";
5190 llvm_unreachable("Unhandled strided type");
5191 }
David Neto1a1a0582017-07-07 12:01:44 -04005192
5193 // Ops[0] = Target ID
5194 // Ops[1] = Decoration (ArrayStride)
5195 // Ops[2] = Stride number (Literal Number)
5196 SPIRVOperandList Ops;
5197
David Neto85082642018-03-24 06:55:20 -07005198 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005199 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005200
5201 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5202 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005203
David Neto87846742018-04-11 17:36:22 -04005204 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005205 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5206 }
David Netoc6f3ab22018-04-06 18:02:31 -04005207
5208 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005209 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5210 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005211 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005212 SPIRVOperandList Ops;
5213 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5214 << MkNum(arg_info.spec_id);
5215 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005216 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005217 }
David Neto1a1a0582017-07-07 12:01:44 -04005218}
5219
David Neto22f144c2017-06-12 14:26:21 -04005220glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5221 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005222 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5223 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5224 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5225 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005226 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5227 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5228 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5229 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005230 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5231 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5232 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5233 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005234 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5235 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5236 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5237 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005238 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5239 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5240 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5241 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5242 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5243 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5244 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5245 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005246 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5247 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5248 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5249 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5250 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5251 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5252 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5253 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005254 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5255 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5256 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5257 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5258 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5259 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5260 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5261 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005262 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5263 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5264 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5265 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5266 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5267 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5268 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5269 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005270 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5271 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5272 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5273 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005274 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5275 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5276 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5277 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5278 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5279 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5280 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5281 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005282 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5283 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5284 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5285 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5286 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5287 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5288 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5289 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005290 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5291 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5292 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5293 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5294 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5295 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5296 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5297 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005298 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5299 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5300 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5301 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5302 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5303 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5304 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5305 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005306 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5307 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5308 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5309 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5310 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005311 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5312 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5313 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5314 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5315 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5316 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5317 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5318 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005319 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5320 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5321 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5322 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5323 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5324 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5325 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5326 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005327 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5328 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5329 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5330 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5331 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5332 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5333 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5334 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005335 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5336 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5337 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5338 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5339 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5340 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5341 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5342 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005343 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5344 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5345 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5346 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5347 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5348 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5349 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5350 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5351 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5352 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5353 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5354 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5355 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5356 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5357 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5358 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5359 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5360 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5361 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5362 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5363 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5364 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5365 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5366 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5367 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5368 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5369 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5370 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5371 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5372 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5373 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5374 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5375 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5376 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5377 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5378 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5379 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5380 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5381 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5382 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5383 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005384 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005385 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5386 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5387 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5388 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5389 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5390 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5391 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5392 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5393 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5394 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5395 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5396 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5397 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5398 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5399 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5400 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5401 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005402 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005403 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005404 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005405 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005406 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005407 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5408 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005409 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005410 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5411 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5412 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005413 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5414 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5415 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5416 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005417 .Default(kGlslExtInstBad);
5418}
5419
5420glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5421 // Check indirect cases.
5422 return StringSwitch<glsl::ExtInst>(Name)
5423 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5424 // Use exact match on float arg because these need a multiply
5425 // of a constant of the right floating point type.
5426 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5427 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5428 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5429 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5430 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5431 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5432 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5433 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005434 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5435 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5436 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5437 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005438 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5439 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5440 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5441 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5442 .Default(kGlslExtInstBad);
5443}
5444
alan-bakerb6b09dc2018-11-08 16:59:28 -05005445glsl::ExtInst
5446SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005447 auto direct = getExtInstEnum(Name);
5448 if (direct != kGlslExtInstBad)
5449 return direct;
5450 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005451}
5452
5453void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5454 out << "%" << Inst->getResultID();
5455}
5456
5457void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5458 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5459 out << "\t" << spv::getOpName(Opcode);
5460}
5461
5462void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5463 SPIRVOperandType OpTy = Op->getType();
5464 switch (OpTy) {
5465 default: {
5466 llvm_unreachable("Unsupported SPIRV Operand Type???");
5467 break;
5468 }
5469 case SPIRVOperandType::NUMBERID: {
5470 out << "%" << Op->getNumID();
5471 break;
5472 }
5473 case SPIRVOperandType::LITERAL_STRING: {
5474 out << "\"" << Op->getLiteralStr() << "\"";
5475 break;
5476 }
5477 case SPIRVOperandType::LITERAL_INTEGER: {
5478 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005479 auto Words = Op->getLiteralNum();
5480 auto NumWords = Words.size();
5481
5482 if (NumWords == 1) {
5483 out << Words[0];
5484 } else if (NumWords == 2) {
5485 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5486 out << Val;
5487 } else {
5488 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005489 }
5490 break;
5491 }
5492 case SPIRVOperandType::LITERAL_FLOAT: {
5493 // TODO: Handle LiteralNum carefully.
5494 for (auto Word : Op->getLiteralNum()) {
5495 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5496 SmallString<8> Str;
5497 APF.toString(Str, 6, 2);
5498 out << Str;
5499 }
5500 break;
5501 }
5502 }
5503}
5504
5505void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5506 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5507 out << spv::getCapabilityName(Cap);
5508}
5509
5510void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5511 auto LiteralNum = Op->getLiteralNum();
5512 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5513 out << glsl::getExtInstName(Ext);
5514}
5515
5516void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5517 spv::AddressingModel AddrModel =
5518 static_cast<spv::AddressingModel>(Op->getNumID());
5519 out << spv::getAddressingModelName(AddrModel);
5520}
5521
5522void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5523 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5524 out << spv::getMemoryModelName(MemModel);
5525}
5526
5527void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5528 spv::ExecutionModel ExecModel =
5529 static_cast<spv::ExecutionModel>(Op->getNumID());
5530 out << spv::getExecutionModelName(ExecModel);
5531}
5532
5533void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5534 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5535 out << spv::getExecutionModeName(ExecMode);
5536}
5537
5538void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005539 spv::SourceLanguage SourceLang =
5540 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005541 out << spv::getSourceLanguageName(SourceLang);
5542}
5543
5544void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5545 spv::FunctionControlMask FuncCtrl =
5546 static_cast<spv::FunctionControlMask>(Op->getNumID());
5547 out << spv::getFunctionControlName(FuncCtrl);
5548}
5549
5550void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5551 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5552 out << getStorageClassName(StClass);
5553}
5554
5555void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5556 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5557 out << getDecorationName(Deco);
5558}
5559
5560void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5561 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5562 out << getBuiltInName(BIn);
5563}
5564
5565void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5566 spv::SelectionControlMask BIn =
5567 static_cast<spv::SelectionControlMask>(Op->getNumID());
5568 out << getSelectionControlName(BIn);
5569}
5570
5571void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5572 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5573 out << getLoopControlName(BIn);
5574}
5575
5576void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5577 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5578 out << getDimName(DIM);
5579}
5580
5581void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5582 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5583 out << getImageFormatName(Format);
5584}
5585
5586void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5587 out << spv::getMemoryAccessName(
5588 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5589}
5590
5591void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5592 auto LiteralNum = Op->getLiteralNum();
5593 spv::ImageOperandsMask Type =
5594 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5595 out << getImageOperandsName(Type);
5596}
5597
5598void SPIRVProducerPass::WriteSPIRVAssembly() {
5599 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5600
5601 for (auto Inst : SPIRVInstList) {
5602 SPIRVOperandList Ops = Inst->getOperands();
5603 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5604
5605 switch (Opcode) {
5606 default: {
5607 llvm_unreachable("Unsupported SPIRV instruction");
5608 break;
5609 }
5610 case spv::OpCapability: {
5611 // Ops[0] = Capability
5612 PrintOpcode(Inst);
5613 out << " ";
5614 PrintCapability(Ops[0]);
5615 out << "\n";
5616 break;
5617 }
5618 case spv::OpMemoryModel: {
5619 // Ops[0] = Addressing Model
5620 // Ops[1] = Memory Model
5621 PrintOpcode(Inst);
5622 out << " ";
5623 PrintAddrModel(Ops[0]);
5624 out << " ";
5625 PrintMemModel(Ops[1]);
5626 out << "\n";
5627 break;
5628 }
5629 case spv::OpEntryPoint: {
5630 // Ops[0] = Execution Model
5631 // Ops[1] = EntryPoint ID
5632 // Ops[2] = Name (Literal String)
5633 // Ops[3] ... Ops[n] = Interface ID
5634 PrintOpcode(Inst);
5635 out << " ";
5636 PrintExecModel(Ops[0]);
5637 for (uint32_t i = 1; i < Ops.size(); i++) {
5638 out << " ";
5639 PrintOperand(Ops[i]);
5640 }
5641 out << "\n";
5642 break;
5643 }
5644 case spv::OpExecutionMode: {
5645 // Ops[0] = Entry Point ID
5646 // Ops[1] = Execution Mode
5647 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5648 PrintOpcode(Inst);
5649 out << " ";
5650 PrintOperand(Ops[0]);
5651 out << " ";
5652 PrintExecMode(Ops[1]);
5653 for (uint32_t i = 2; i < Ops.size(); i++) {
5654 out << " ";
5655 PrintOperand(Ops[i]);
5656 }
5657 out << "\n";
5658 break;
5659 }
5660 case spv::OpSource: {
5661 // Ops[0] = SourceLanguage ID
5662 // Ops[1] = Version (LiteralNum)
5663 PrintOpcode(Inst);
5664 out << " ";
5665 PrintSourceLanguage(Ops[0]);
5666 out << " ";
5667 PrintOperand(Ops[1]);
5668 out << "\n";
5669 break;
5670 }
5671 case spv::OpDecorate: {
5672 // Ops[0] = Target ID
5673 // Ops[1] = Decoration (Block or BufferBlock)
5674 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5675 PrintOpcode(Inst);
5676 out << " ";
5677 PrintOperand(Ops[0]);
5678 out << " ";
5679 PrintDecoration(Ops[1]);
5680 // Handle BuiltIn OpDecorate specially.
5681 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5682 out << " ";
5683 PrintBuiltIn(Ops[2]);
5684 } else {
5685 for (uint32_t i = 2; i < Ops.size(); i++) {
5686 out << " ";
5687 PrintOperand(Ops[i]);
5688 }
5689 }
5690 out << "\n";
5691 break;
5692 }
5693 case spv::OpMemberDecorate: {
5694 // Ops[0] = Structure Type ID
5695 // Ops[1] = Member Index(Literal Number)
5696 // Ops[2] = Decoration
5697 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5698 PrintOpcode(Inst);
5699 out << " ";
5700 PrintOperand(Ops[0]);
5701 out << " ";
5702 PrintOperand(Ops[1]);
5703 out << " ";
5704 PrintDecoration(Ops[2]);
5705 for (uint32_t i = 3; i < Ops.size(); i++) {
5706 out << " ";
5707 PrintOperand(Ops[i]);
5708 }
5709 out << "\n";
5710 break;
5711 }
5712 case spv::OpTypePointer: {
5713 // Ops[0] = Storage Class
5714 // Ops[1] = Element Type ID
5715 PrintResID(Inst);
5716 out << " = ";
5717 PrintOpcode(Inst);
5718 out << " ";
5719 PrintStorageClass(Ops[0]);
5720 out << " ";
5721 PrintOperand(Ops[1]);
5722 out << "\n";
5723 break;
5724 }
5725 case spv::OpTypeImage: {
5726 // Ops[0] = Sampled Type ID
5727 // Ops[1] = Dim ID
5728 // Ops[2] = Depth (Literal Number)
5729 // Ops[3] = Arrayed (Literal Number)
5730 // Ops[4] = MS (Literal Number)
5731 // Ops[5] = Sampled (Literal Number)
5732 // Ops[6] = Image Format ID
5733 PrintResID(Inst);
5734 out << " = ";
5735 PrintOpcode(Inst);
5736 out << " ";
5737 PrintOperand(Ops[0]);
5738 out << " ";
5739 PrintDimensionality(Ops[1]);
5740 out << " ";
5741 PrintOperand(Ops[2]);
5742 out << " ";
5743 PrintOperand(Ops[3]);
5744 out << " ";
5745 PrintOperand(Ops[4]);
5746 out << " ";
5747 PrintOperand(Ops[5]);
5748 out << " ";
5749 PrintImageFormat(Ops[6]);
5750 out << "\n";
5751 break;
5752 }
5753 case spv::OpFunction: {
5754 // Ops[0] : Result Type ID
5755 // Ops[1] : Function Control
5756 // Ops[2] : Function Type ID
5757 PrintResID(Inst);
5758 out << " = ";
5759 PrintOpcode(Inst);
5760 out << " ";
5761 PrintOperand(Ops[0]);
5762 out << " ";
5763 PrintFuncCtrl(Ops[1]);
5764 out << " ";
5765 PrintOperand(Ops[2]);
5766 out << "\n";
5767 break;
5768 }
5769 case spv::OpSelectionMerge: {
5770 // Ops[0] = Merge Block ID
5771 // Ops[1] = Selection Control
5772 PrintOpcode(Inst);
5773 out << " ";
5774 PrintOperand(Ops[0]);
5775 out << " ";
5776 PrintSelectionControl(Ops[1]);
5777 out << "\n";
5778 break;
5779 }
5780 case spv::OpLoopMerge: {
5781 // Ops[0] = Merge Block ID
5782 // Ops[1] = Continue Target ID
5783 // Ops[2] = Selection Control
5784 PrintOpcode(Inst);
5785 out << " ";
5786 PrintOperand(Ops[0]);
5787 out << " ";
5788 PrintOperand(Ops[1]);
5789 out << " ";
5790 PrintLoopControl(Ops[2]);
5791 out << "\n";
5792 break;
5793 }
5794 case spv::OpImageSampleExplicitLod: {
5795 // Ops[0] = Result Type ID
5796 // Ops[1] = Sampled Image ID
5797 // Ops[2] = Coordinate ID
5798 // Ops[3] = Image Operands Type ID
5799 // Ops[4] ... Ops[n] = Operands ID
5800 PrintResID(Inst);
5801 out << " = ";
5802 PrintOpcode(Inst);
5803 for (uint32_t i = 0; i < 3; i++) {
5804 out << " ";
5805 PrintOperand(Ops[i]);
5806 }
5807 out << " ";
5808 PrintImageOperandsType(Ops[3]);
5809 for (uint32_t i = 4; i < Ops.size(); i++) {
5810 out << " ";
5811 PrintOperand(Ops[i]);
5812 }
5813 out << "\n";
5814 break;
5815 }
5816 case spv::OpVariable: {
5817 // Ops[0] : Result Type ID
5818 // Ops[1] : Storage Class
5819 // Ops[2] ... Ops[n] = Initializer IDs
5820 PrintResID(Inst);
5821 out << " = ";
5822 PrintOpcode(Inst);
5823 out << " ";
5824 PrintOperand(Ops[0]);
5825 out << " ";
5826 PrintStorageClass(Ops[1]);
5827 for (uint32_t i = 2; i < Ops.size(); i++) {
5828 out << " ";
5829 PrintOperand(Ops[i]);
5830 }
5831 out << "\n";
5832 break;
5833 }
5834 case spv::OpExtInst: {
5835 // Ops[0] = Result Type ID
5836 // Ops[1] = Set ID (OpExtInstImport ID)
5837 // Ops[2] = Instruction Number (Literal Number)
5838 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5839 PrintResID(Inst);
5840 out << " = ";
5841 PrintOpcode(Inst);
5842 out << " ";
5843 PrintOperand(Ops[0]);
5844 out << " ";
5845 PrintOperand(Ops[1]);
5846 out << " ";
5847 PrintExtInst(Ops[2]);
5848 for (uint32_t i = 3; i < Ops.size(); i++) {
5849 out << " ";
5850 PrintOperand(Ops[i]);
5851 }
5852 out << "\n";
5853 break;
5854 }
5855 case spv::OpCopyMemory: {
5856 // Ops[0] = Addressing Model
5857 // Ops[1] = Memory Model
5858 PrintOpcode(Inst);
5859 out << " ";
5860 PrintOperand(Ops[0]);
5861 out << " ";
5862 PrintOperand(Ops[1]);
5863 out << " ";
5864 PrintMemoryAccess(Ops[2]);
5865 out << " ";
5866 PrintOperand(Ops[3]);
5867 out << "\n";
5868 break;
5869 }
5870 case spv::OpExtension:
5871 case spv::OpControlBarrier:
5872 case spv::OpMemoryBarrier:
5873 case spv::OpBranch:
5874 case spv::OpBranchConditional:
5875 case spv::OpStore:
5876 case spv::OpImageWrite:
5877 case spv::OpReturnValue:
5878 case spv::OpReturn:
5879 case spv::OpFunctionEnd: {
5880 PrintOpcode(Inst);
5881 for (uint32_t i = 0; i < Ops.size(); i++) {
5882 out << " ";
5883 PrintOperand(Ops[i]);
5884 }
5885 out << "\n";
5886 break;
5887 }
5888 case spv::OpExtInstImport:
5889 case spv::OpTypeRuntimeArray:
5890 case spv::OpTypeStruct:
5891 case spv::OpTypeSampler:
5892 case spv::OpTypeSampledImage:
5893 case spv::OpTypeInt:
5894 case spv::OpTypeFloat:
5895 case spv::OpTypeArray:
5896 case spv::OpTypeVector:
5897 case spv::OpTypeBool:
5898 case spv::OpTypeVoid:
5899 case spv::OpTypeFunction:
5900 case spv::OpFunctionParameter:
5901 case spv::OpLabel:
5902 case spv::OpPhi:
5903 case spv::OpLoad:
5904 case spv::OpSelect:
5905 case spv::OpAccessChain:
5906 case spv::OpPtrAccessChain:
5907 case spv::OpInBoundsAccessChain:
5908 case spv::OpUConvert:
5909 case spv::OpSConvert:
5910 case spv::OpConvertFToU:
5911 case spv::OpConvertFToS:
5912 case spv::OpConvertUToF:
5913 case spv::OpConvertSToF:
5914 case spv::OpFConvert:
5915 case spv::OpConvertPtrToU:
5916 case spv::OpConvertUToPtr:
5917 case spv::OpBitcast:
5918 case spv::OpIAdd:
5919 case spv::OpFAdd:
5920 case spv::OpISub:
5921 case spv::OpFSub:
5922 case spv::OpIMul:
5923 case spv::OpFMul:
5924 case spv::OpUDiv:
5925 case spv::OpSDiv:
5926 case spv::OpFDiv:
5927 case spv::OpUMod:
5928 case spv::OpSRem:
5929 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005930 case spv::OpUMulExtended:
5931 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005932 case spv::OpBitwiseOr:
5933 case spv::OpBitwiseXor:
5934 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005935 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005936 case spv::OpShiftLeftLogical:
5937 case spv::OpShiftRightLogical:
5938 case spv::OpShiftRightArithmetic:
5939 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005940 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005941 case spv::OpCompositeExtract:
5942 case spv::OpVectorExtractDynamic:
5943 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005944 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005945 case spv::OpVectorInsertDynamic:
5946 case spv::OpVectorShuffle:
5947 case spv::OpIEqual:
5948 case spv::OpINotEqual:
5949 case spv::OpUGreaterThan:
5950 case spv::OpUGreaterThanEqual:
5951 case spv::OpULessThan:
5952 case spv::OpULessThanEqual:
5953 case spv::OpSGreaterThan:
5954 case spv::OpSGreaterThanEqual:
5955 case spv::OpSLessThan:
5956 case spv::OpSLessThanEqual:
5957 case spv::OpFOrdEqual:
5958 case spv::OpFOrdGreaterThan:
5959 case spv::OpFOrdGreaterThanEqual:
5960 case spv::OpFOrdLessThan:
5961 case spv::OpFOrdLessThanEqual:
5962 case spv::OpFOrdNotEqual:
5963 case spv::OpFUnordEqual:
5964 case spv::OpFUnordGreaterThan:
5965 case spv::OpFUnordGreaterThanEqual:
5966 case spv::OpFUnordLessThan:
5967 case spv::OpFUnordLessThanEqual:
5968 case spv::OpFUnordNotEqual:
5969 case spv::OpSampledImage:
5970 case spv::OpFunctionCall:
5971 case spv::OpConstantTrue:
5972 case spv::OpConstantFalse:
5973 case spv::OpConstant:
5974 case spv::OpSpecConstant:
5975 case spv::OpConstantComposite:
5976 case spv::OpSpecConstantComposite:
5977 case spv::OpConstantNull:
5978 case spv::OpLogicalOr:
5979 case spv::OpLogicalAnd:
5980 case spv::OpLogicalNot:
5981 case spv::OpLogicalNotEqual:
5982 case spv::OpUndef:
5983 case spv::OpIsInf:
5984 case spv::OpIsNan:
5985 case spv::OpAny:
5986 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005987 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005988 case spv::OpAtomicIAdd:
5989 case spv::OpAtomicISub:
5990 case spv::OpAtomicExchange:
5991 case spv::OpAtomicIIncrement:
5992 case spv::OpAtomicIDecrement:
5993 case spv::OpAtomicCompareExchange:
5994 case spv::OpAtomicUMin:
5995 case spv::OpAtomicSMin:
5996 case spv::OpAtomicUMax:
5997 case spv::OpAtomicSMax:
5998 case spv::OpAtomicAnd:
5999 case spv::OpAtomicOr:
6000 case spv::OpAtomicXor:
6001 case spv::OpDot: {
6002 PrintResID(Inst);
6003 out << " = ";
6004 PrintOpcode(Inst);
6005 for (uint32_t i = 0; i < Ops.size(); i++) {
6006 out << " ";
6007 PrintOperand(Ops[i]);
6008 }
6009 out << "\n";
6010 break;
6011 }
6012 }
6013 }
6014}
6015
6016void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006017 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006018}
6019
6020void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6021 WriteOneWord(Inst->getResultID());
6022}
6023
6024void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6025 // High 16 bit : Word Count
6026 // Low 16 bit : Opcode
6027 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006028 const uint32_t count = Inst->getWordCount();
6029 if (count > 65535) {
6030 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6031 llvm_unreachable("Word count too high");
6032 }
David Neto22f144c2017-06-12 14:26:21 -04006033 Word |= Inst->getWordCount() << 16;
6034 WriteOneWord(Word);
6035}
6036
6037void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6038 SPIRVOperandType OpTy = Op->getType();
6039 switch (OpTy) {
6040 default: {
6041 llvm_unreachable("Unsupported SPIRV Operand Type???");
6042 break;
6043 }
6044 case SPIRVOperandType::NUMBERID: {
6045 WriteOneWord(Op->getNumID());
6046 break;
6047 }
6048 case SPIRVOperandType::LITERAL_STRING: {
6049 std::string Str = Op->getLiteralStr();
6050 const char *Data = Str.c_str();
6051 size_t WordSize = Str.size() / 4;
6052 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6053 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6054 }
6055
6056 uint32_t Remainder = Str.size() % 4;
6057 uint32_t LastWord = 0;
6058 if (Remainder) {
6059 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6060 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6061 }
6062 }
6063
6064 WriteOneWord(LastWord);
6065 break;
6066 }
6067 case SPIRVOperandType::LITERAL_INTEGER:
6068 case SPIRVOperandType::LITERAL_FLOAT: {
6069 auto LiteralNum = Op->getLiteralNum();
6070 // TODO: Handle LiteranNum carefully.
6071 for (auto Word : LiteralNum) {
6072 WriteOneWord(Word);
6073 }
6074 break;
6075 }
6076 }
6077}
6078
6079void SPIRVProducerPass::WriteSPIRVBinary() {
6080 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6081
6082 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006083 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006084 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6085
6086 switch (Opcode) {
6087 default: {
David Neto5c22a252018-03-15 16:07:41 -04006088 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006089 llvm_unreachable("Unsupported SPIRV instruction");
6090 break;
6091 }
6092 case spv::OpCapability:
6093 case spv::OpExtension:
6094 case spv::OpMemoryModel:
6095 case spv::OpEntryPoint:
6096 case spv::OpExecutionMode:
6097 case spv::OpSource:
6098 case spv::OpDecorate:
6099 case spv::OpMemberDecorate:
6100 case spv::OpBranch:
6101 case spv::OpBranchConditional:
6102 case spv::OpSelectionMerge:
6103 case spv::OpLoopMerge:
6104 case spv::OpStore:
6105 case spv::OpImageWrite:
6106 case spv::OpReturnValue:
6107 case spv::OpControlBarrier:
6108 case spv::OpMemoryBarrier:
6109 case spv::OpReturn:
6110 case spv::OpFunctionEnd:
6111 case spv::OpCopyMemory: {
6112 WriteWordCountAndOpcode(Inst);
6113 for (uint32_t i = 0; i < Ops.size(); i++) {
6114 WriteOperand(Ops[i]);
6115 }
6116 break;
6117 }
6118 case spv::OpTypeBool:
6119 case spv::OpTypeVoid:
6120 case spv::OpTypeSampler:
6121 case spv::OpLabel:
6122 case spv::OpExtInstImport:
6123 case spv::OpTypePointer:
6124 case spv::OpTypeRuntimeArray:
6125 case spv::OpTypeStruct:
6126 case spv::OpTypeImage:
6127 case spv::OpTypeSampledImage:
6128 case spv::OpTypeInt:
6129 case spv::OpTypeFloat:
6130 case spv::OpTypeArray:
6131 case spv::OpTypeVector:
6132 case spv::OpTypeFunction: {
6133 WriteWordCountAndOpcode(Inst);
6134 WriteResultID(Inst);
6135 for (uint32_t i = 0; i < Ops.size(); i++) {
6136 WriteOperand(Ops[i]);
6137 }
6138 break;
6139 }
6140 case spv::OpFunction:
6141 case spv::OpFunctionParameter:
6142 case spv::OpAccessChain:
6143 case spv::OpPtrAccessChain:
6144 case spv::OpInBoundsAccessChain:
6145 case spv::OpUConvert:
6146 case spv::OpSConvert:
6147 case spv::OpConvertFToU:
6148 case spv::OpConvertFToS:
6149 case spv::OpConvertUToF:
6150 case spv::OpConvertSToF:
6151 case spv::OpFConvert:
6152 case spv::OpConvertPtrToU:
6153 case spv::OpConvertUToPtr:
6154 case spv::OpBitcast:
6155 case spv::OpIAdd:
6156 case spv::OpFAdd:
6157 case spv::OpISub:
6158 case spv::OpFSub:
6159 case spv::OpIMul:
6160 case spv::OpFMul:
6161 case spv::OpUDiv:
6162 case spv::OpSDiv:
6163 case spv::OpFDiv:
6164 case spv::OpUMod:
6165 case spv::OpSRem:
6166 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006167 case spv::OpUMulExtended:
6168 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006169 case spv::OpBitwiseOr:
6170 case spv::OpBitwiseXor:
6171 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006172 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006173 case spv::OpShiftLeftLogical:
6174 case spv::OpShiftRightLogical:
6175 case spv::OpShiftRightArithmetic:
6176 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006177 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006178 case spv::OpCompositeExtract:
6179 case spv::OpVectorExtractDynamic:
6180 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006181 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006182 case spv::OpVectorInsertDynamic:
6183 case spv::OpVectorShuffle:
6184 case spv::OpIEqual:
6185 case spv::OpINotEqual:
6186 case spv::OpUGreaterThan:
6187 case spv::OpUGreaterThanEqual:
6188 case spv::OpULessThan:
6189 case spv::OpULessThanEqual:
6190 case spv::OpSGreaterThan:
6191 case spv::OpSGreaterThanEqual:
6192 case spv::OpSLessThan:
6193 case spv::OpSLessThanEqual:
6194 case spv::OpFOrdEqual:
6195 case spv::OpFOrdGreaterThan:
6196 case spv::OpFOrdGreaterThanEqual:
6197 case spv::OpFOrdLessThan:
6198 case spv::OpFOrdLessThanEqual:
6199 case spv::OpFOrdNotEqual:
6200 case spv::OpFUnordEqual:
6201 case spv::OpFUnordGreaterThan:
6202 case spv::OpFUnordGreaterThanEqual:
6203 case spv::OpFUnordLessThan:
6204 case spv::OpFUnordLessThanEqual:
6205 case spv::OpFUnordNotEqual:
6206 case spv::OpExtInst:
6207 case spv::OpIsInf:
6208 case spv::OpIsNan:
6209 case spv::OpAny:
6210 case spv::OpAll:
6211 case spv::OpUndef:
6212 case spv::OpConstantNull:
6213 case spv::OpLogicalOr:
6214 case spv::OpLogicalAnd:
6215 case spv::OpLogicalNot:
6216 case spv::OpLogicalNotEqual:
6217 case spv::OpConstantComposite:
6218 case spv::OpSpecConstantComposite:
6219 case spv::OpConstantTrue:
6220 case spv::OpConstantFalse:
6221 case spv::OpConstant:
6222 case spv::OpSpecConstant:
6223 case spv::OpVariable:
6224 case spv::OpFunctionCall:
6225 case spv::OpSampledImage:
6226 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006227 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006228 case spv::OpSelect:
6229 case spv::OpPhi:
6230 case spv::OpLoad:
6231 case spv::OpAtomicIAdd:
6232 case spv::OpAtomicISub:
6233 case spv::OpAtomicExchange:
6234 case spv::OpAtomicIIncrement:
6235 case spv::OpAtomicIDecrement:
6236 case spv::OpAtomicCompareExchange:
6237 case spv::OpAtomicUMin:
6238 case spv::OpAtomicSMin:
6239 case spv::OpAtomicUMax:
6240 case spv::OpAtomicSMax:
6241 case spv::OpAtomicAnd:
6242 case spv::OpAtomicOr:
6243 case spv::OpAtomicXor:
6244 case spv::OpDot: {
6245 WriteWordCountAndOpcode(Inst);
6246 WriteOperand(Ops[0]);
6247 WriteResultID(Inst);
6248 for (uint32_t i = 1; i < Ops.size(); i++) {
6249 WriteOperand(Ops[i]);
6250 }
6251 break;
6252 }
6253 }
6254 }
6255}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006256
alan-bakerb6b09dc2018-11-08 16:59:28 -05006257bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006258 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006259 case Type::HalfTyID:
6260 case Type::FloatTyID:
6261 case Type::DoubleTyID:
6262 case Type::IntegerTyID:
6263 case Type::VectorTyID:
6264 return true;
6265 case Type::PointerTyID: {
6266 const PointerType *pointer_type = cast<PointerType>(type);
6267 if (pointer_type->getPointerAddressSpace() !=
6268 AddressSpace::UniformConstant) {
6269 auto pointee_type = pointer_type->getPointerElementType();
6270 if (pointee_type->isStructTy() &&
6271 cast<StructType>(pointee_type)->isOpaque()) {
6272 // Images and samplers are not nullable.
6273 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006274 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006275 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006276 return true;
6277 }
6278 case Type::ArrayTyID:
6279 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6280 case Type::StructTyID: {
6281 const StructType *struct_type = cast<StructType>(type);
6282 // Images and samplers are not nullable.
6283 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006284 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006285 for (const auto element : struct_type->elements()) {
6286 if (!IsTypeNullable(element))
6287 return false;
6288 }
6289 return true;
6290 }
6291 default:
6292 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006293 }
6294}
Alan Bakerfcda9482018-10-02 17:09:59 -04006295
6296void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6297 if (auto *offsets_md =
6298 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6299 // Metdata is stored as key-value pair operands. The first element of each
6300 // operand is the type and the second is a vector of offsets.
6301 for (const auto *operand : offsets_md->operands()) {
6302 const auto *pair = cast<MDTuple>(operand);
6303 auto *type =
6304 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6305 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6306 std::vector<uint32_t> offsets;
6307 for (const Metadata *offset_md : offset_vector->operands()) {
6308 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006309 offsets.push_back(static_cast<uint32_t>(
6310 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006311 }
6312 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6313 }
6314 }
6315
6316 if (auto *sizes_md =
6317 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6318 // Metadata is stored as key-value pair operands. The first element of each
6319 // operand is the type and the second is a triple of sizes: type size in
6320 // bits, store size and alloc size.
6321 for (const auto *operand : sizes_md->operands()) {
6322 const auto *pair = cast<MDTuple>(operand);
6323 auto *type =
6324 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6325 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6326 uint64_t type_size_in_bits =
6327 cast<ConstantInt>(
6328 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6329 ->getZExtValue();
6330 uint64_t type_store_size =
6331 cast<ConstantInt>(
6332 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6333 ->getZExtValue();
6334 uint64_t type_alloc_size =
6335 cast<ConstantInt>(
6336 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6337 ->getZExtValue();
6338 RemappedUBOTypeSizes.insert(std::make_pair(
6339 type, std::make_tuple(type_size_in_bits, type_store_size,
6340 type_alloc_size)));
6341 }
6342 }
6343}
6344
6345uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6346 const DataLayout &DL) {
6347 auto iter = RemappedUBOTypeSizes.find(type);
6348 if (iter != RemappedUBOTypeSizes.end()) {
6349 return std::get<0>(iter->second);
6350 }
6351
6352 return DL.getTypeSizeInBits(type);
6353}
6354
6355uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6356 auto iter = RemappedUBOTypeSizes.find(type);
6357 if (iter != RemappedUBOTypeSizes.end()) {
6358 return std::get<1>(iter->second);
6359 }
6360
6361 return DL.getTypeStoreSize(type);
6362}
6363
6364uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6365 auto iter = RemappedUBOTypeSizes.find(type);
6366 if (iter != RemappedUBOTypeSizes.end()) {
6367 return std::get<2>(iter->second);
6368 }
6369
6370 return DL.getTypeAllocSize(type);
6371}
alan-baker5b86ed72019-02-15 08:26:50 -05006372
6373void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6374 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6375 setVariablePointersStorageBuffer(true);
6376 } else {
6377 setVariablePointers(true);
6378 }
6379}
6380
6381Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6382 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6383 return GetBasePointer(gep->getPointerOperand());
6384 }
6385
6386 // Conservatively return |v|.
6387 return v;
6388}
6389
6390bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6391 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6392 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6393 if (lhs_call->getCalledFunction()->getName().startswith(
6394 clspv::ResourceAccessorFunction()) &&
6395 rhs_call->getCalledFunction()->getName().startswith(
6396 clspv::ResourceAccessorFunction())) {
6397 // For resource accessors, match descriptor set and binding.
6398 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6399 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6400 return true;
6401 } else if (lhs_call->getCalledFunction()->getName().startswith(
6402 clspv::WorkgroupAccessorFunction()) &&
6403 rhs_call->getCalledFunction()->getName().startswith(
6404 clspv::WorkgroupAccessorFunction())) {
6405 // For workgroup resources, match spec id.
6406 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6407 return true;
6408 }
6409 }
6410 }
6411
6412 return false;
6413}
6414
6415bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6416 assert(inst->getType()->isPointerTy());
6417 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6418 spv::StorageClassStorageBuffer);
6419 const bool hack_undef = clspv::Option::HackUndef();
6420 if (auto *select = dyn_cast<SelectInst>(inst)) {
6421 auto *true_base = GetBasePointer(select->getTrueValue());
6422 auto *false_base = GetBasePointer(select->getFalseValue());
6423
6424 if (true_base == false_base)
6425 return true;
6426
6427 // If either the true or false operand is a null, then we satisfy the same
6428 // object constraint.
6429 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6430 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6431 return true;
6432 }
6433
6434 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6435 if (false_cst->isNullValue() ||
6436 (hack_undef && isa<UndefValue>(false_base)))
6437 return true;
6438 }
6439
6440 if (sameResource(true_base, false_base))
6441 return true;
6442 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6443 Value *value = nullptr;
6444 bool ok = true;
6445 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6446 auto *base = GetBasePointer(phi->getIncomingValue(i));
6447 // Null values satisfy the constraint of selecting of selecting from the
6448 // same object.
6449 if (!value) {
6450 if (auto *cst = dyn_cast<Constant>(base)) {
6451 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6452 value = base;
6453 } else {
6454 value = base;
6455 }
6456 } else if (base != value) {
6457 if (auto *base_cst = dyn_cast<Constant>(base)) {
6458 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6459 continue;
6460 }
6461
6462 if (sameResource(value, base))
6463 continue;
6464
6465 // Values don't represent the same base.
6466 ok = false;
6467 }
6468 }
6469
6470 return ok;
6471 }
6472
6473 // Conservatively return false.
6474 return false;
6475}
alan-bakere9308012019-03-15 10:25:13 -04006476
6477bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6478 if (!Arg.getType()->isPointerTy() ||
6479 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6480 // Only SSBOs need to be annotated as coherent.
6481 return false;
6482 }
6483
6484 DenseSet<Value *> visited;
6485 std::vector<Value *> stack;
6486 for (auto *U : Arg.getParent()->users()) {
6487 if (auto *call = dyn_cast<CallInst>(U)) {
6488 stack.push_back(call->getOperand(Arg.getArgNo()));
6489 }
6490 }
6491
6492 while (!stack.empty()) {
6493 Value *v = stack.back();
6494 stack.pop_back();
6495
6496 if (!visited.insert(v).second)
6497 continue;
6498
6499 auto *resource_call = dyn_cast<CallInst>(v);
6500 if (resource_call &&
6501 resource_call->getCalledFunction()->getName().startswith(
6502 clspv::ResourceAccessorFunction())) {
6503 // If this is a resource accessor function, check if the coherent operand
6504 // is set.
6505 const auto coherent =
6506 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6507 ->getZExtValue());
6508 if (coherent == 1)
6509 return true;
6510 } else if (auto *arg = dyn_cast<Argument>(v)) {
6511 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04006512 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04006513 if (auto *call = dyn_cast<CallInst>(U)) {
6514 stack.push_back(call->getOperand(arg->getArgNo()));
6515 }
6516 }
6517 } else if (auto *user = dyn_cast<User>(v)) {
6518 // If this is a user, traverse all operands that could lead to resource
6519 // variables.
6520 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6521 Value *operand = user->getOperand(i);
6522 if (operand->getType()->isPointerTy() &&
6523 operand->getType()->getPointerAddressSpace() ==
6524 clspv::AddressSpace::Global) {
6525 stack.push_back(operand);
6526 }
6527 }
6528 }
6529 }
6530
6531 // No coherent resource variables encountered.
6532 return false;
6533}