blob: 16b548cc091b36fc18b7d09819ab370c6154e482 [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.
David Neto862b7d82018-06-14 18:48:37 -04001250 if (Call && ("clspv.sampler.var.literal" ==
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.
1277 if (M.getFunction("clspv.sampler.var.literal") ||
1278 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();
1477 if (name == "clspv.sampler.var.literal") {
1478 // 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 }
David Neto22f144c2017-06-12 14:26:21 -04001487 }
1488
1489 if (isa<AllocaInst>(I)) {
1490 // Alloca instruction has constant for the number of element. Ignore it.
1491 continue;
1492 } else if (isa<ShuffleVectorInst>(I)) {
1493 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1494 // Ignore constant for mask of shuffle vector instruction.
1495 if (i == 2) {
1496 continue;
1497 }
1498
1499 if (isa<Constant>(I.getOperand(i)) &&
1500 !isa<GlobalValue>(I.getOperand(i))) {
1501 FindConstant(I.getOperand(i));
1502 }
1503 }
1504
1505 continue;
1506 } else if (isa<InsertElementInst>(I)) {
1507 // Handle InsertElement with <4 x i8> specially.
1508 Type *CompositeTy = I.getOperand(0)->getType();
1509 if (is4xi8vec(CompositeTy)) {
1510 LLVMContext &Context = CompositeTy->getContext();
1511 if (isa<Constant>(I.getOperand(0))) {
1512 FindConstant(I.getOperand(0));
1513 }
1514
1515 if (isa<Constant>(I.getOperand(1))) {
1516 FindConstant(I.getOperand(1));
1517 }
1518
1519 // Add mask constant 0xFF.
1520 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1521 FindConstant(CstFF);
1522
1523 // Add shift amount constant.
1524 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1525 uint64_t Idx = CI->getZExtValue();
1526 Constant *CstShiftAmount =
1527 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1528 FindConstant(CstShiftAmount);
1529 }
1530
1531 continue;
1532 }
1533
1534 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1535 // Ignore constant for index of InsertElement instruction.
1536 if (i == 2) {
1537 continue;
1538 }
1539
1540 if (isa<Constant>(I.getOperand(i)) &&
1541 !isa<GlobalValue>(I.getOperand(i))) {
1542 FindConstant(I.getOperand(i));
1543 }
1544 }
1545
1546 continue;
1547 } else if (isa<ExtractElementInst>(I)) {
1548 // Handle ExtractElement with <4 x i8> specially.
1549 Type *CompositeTy = I.getOperand(0)->getType();
1550 if (is4xi8vec(CompositeTy)) {
1551 LLVMContext &Context = CompositeTy->getContext();
1552 if (isa<Constant>(I.getOperand(0))) {
1553 FindConstant(I.getOperand(0));
1554 }
1555
1556 // Add mask constant 0xFF.
1557 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1558 FindConstant(CstFF);
1559
1560 // Add shift amount constant.
1561 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1562 uint64_t Idx = CI->getZExtValue();
1563 Constant *CstShiftAmount =
1564 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1565 FindConstant(CstShiftAmount);
1566 } else {
1567 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1568 FindConstant(Cst8);
1569 }
1570
1571 continue;
1572 }
1573
1574 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1575 // Ignore constant for index of ExtractElement instruction.
1576 if (i == 1) {
1577 continue;
1578 }
1579
1580 if (isa<Constant>(I.getOperand(i)) &&
1581 !isa<GlobalValue>(I.getOperand(i))) {
1582 FindConstant(I.getOperand(i));
1583 }
1584 }
1585
1586 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001587 } else if ((Instruction::Xor == I.getOpcode()) &&
1588 I.getType()->isIntegerTy(1)) {
1589 // We special case for Xor where the type is i1 and one of the arguments
1590 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1591 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001592 bool foundConstantTrue = false;
1593 for (Use &Op : I.operands()) {
1594 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1595 auto CI = cast<ConstantInt>(Op);
1596
1597 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001598 // If we already found the true constant, we might (probably only
1599 // on -O0) have an OpLogicalNot which is taking a constant
1600 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001601 FindConstant(Op);
1602 } else {
1603 foundConstantTrue = true;
1604 }
1605 }
1606 }
1607
1608 continue;
David Netod2de94a2017-08-28 17:27:47 -04001609 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001610 // Special case if i8 is not generally handled.
1611 if (!clspv::Option::Int8Support()) {
1612 // For truncation to i8 we mask against 255.
1613 Type *ToTy = I.getType();
1614 if (8u == ToTy->getPrimitiveSizeInBits()) {
1615 LLVMContext &Context = ToTy->getContext();
1616 Constant *Cst255 =
1617 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1618 FindConstant(Cst255);
1619 }
David Netod2de94a2017-08-28 17:27:47 -04001620 }
Neil Henning39672102017-09-29 14:33:13 +01001621 } else if (isa<AtomicRMWInst>(I)) {
1622 LLVMContext &Context = I.getContext();
1623
1624 FindConstant(
1625 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1626 FindConstant(ConstantInt::get(
1627 Type::getInt32Ty(Context),
1628 spv::MemorySemanticsUniformMemoryMask |
1629 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001630 }
1631
1632 for (Use &Op : I.operands()) {
1633 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1634 FindConstant(Op);
1635 }
1636 }
1637 }
1638 }
1639}
1640
1641void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001642 ValueList &CstList = getConstantList();
1643
David Netofb9a7972017-08-25 17:08:24 -04001644 // If V is already tracked, ignore it.
1645 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001646 return;
1647 }
1648
David Neto862b7d82018-06-14 18:48:37 -04001649 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1650 return;
1651 }
1652
David Neto22f144c2017-06-12 14:26:21 -04001653 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001654 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001655
1656 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001657 if (is4xi8vec(CstTy)) {
1658 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001659 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001660 }
1661 }
1662
1663 if (Cst->getNumOperands()) {
1664 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1665 ++I) {
1666 FindConstant(*I);
1667 }
1668
David Netofb9a7972017-08-25 17:08:24 -04001669 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001670 return;
1671 } else if (const ConstantDataSequential *CDS =
1672 dyn_cast<ConstantDataSequential>(Cst)) {
1673 // Add constants for each element to constant list.
1674 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1675 Constant *EleCst = CDS->getElementAsConstant(i);
1676 FindConstant(EleCst);
1677 }
1678 }
1679
1680 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001681 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001682 }
1683}
1684
1685spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1686 switch (AddrSpace) {
1687 default:
1688 llvm_unreachable("Unsupported OpenCL address space");
1689 case AddressSpace::Private:
1690 return spv::StorageClassFunction;
1691 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001692 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001693 case AddressSpace::Constant:
1694 return clspv::Option::ConstantArgsInUniformBuffer()
1695 ? spv::StorageClassUniform
1696 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001697 case AddressSpace::Input:
1698 return spv::StorageClassInput;
1699 case AddressSpace::Local:
1700 return spv::StorageClassWorkgroup;
1701 case AddressSpace::UniformConstant:
1702 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001703 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001704 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001705 case AddressSpace::ModuleScopePrivate:
1706 return spv::StorageClassPrivate;
1707 }
1708}
1709
David Neto862b7d82018-06-14 18:48:37 -04001710spv::StorageClass
1711SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1712 switch (arg_kind) {
1713 case clspv::ArgKind::Buffer:
1714 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001715 case clspv::ArgKind::BufferUBO:
1716 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001717 case clspv::ArgKind::Pod:
1718 return clspv::Option::PodArgsInUniformBuffer()
1719 ? spv::StorageClassUniform
1720 : spv::StorageClassStorageBuffer;
1721 case clspv::ArgKind::Local:
1722 return spv::StorageClassWorkgroup;
1723 case clspv::ArgKind::ReadOnlyImage:
1724 case clspv::ArgKind::WriteOnlyImage:
1725 case clspv::ArgKind::Sampler:
1726 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001727 default:
1728 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001729 }
1730}
1731
David Neto22f144c2017-06-12 14:26:21 -04001732spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1733 return StringSwitch<spv::BuiltIn>(Name)
1734 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1735 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1736 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1737 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1738 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1739 .Default(spv::BuiltInMax);
1740}
1741
1742void SPIRVProducerPass::GenerateExtInstImport() {
1743 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1744 uint32_t &ExtInstImportID = getOpExtInstImportID();
1745
1746 //
1747 // Generate OpExtInstImport.
1748 //
1749 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001750 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001751 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1752 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001753}
1754
alan-bakerb6b09dc2018-11-08 16:59:28 -05001755void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1756 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001757 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1758 ValueMapType &VMap = getValueMap();
1759 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001760 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001761
1762 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1763 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1764 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1765
1766 for (Type *Ty : getTypeList()) {
1767 // Update TypeMap with nextID for reference later.
1768 TypeMap[Ty] = nextID;
1769
1770 switch (Ty->getTypeID()) {
1771 default: {
1772 Ty->print(errs());
1773 llvm_unreachable("Unsupported type???");
1774 break;
1775 }
1776 case Type::MetadataTyID:
1777 case Type::LabelTyID: {
1778 // Ignore these types.
1779 break;
1780 }
1781 case Type::PointerTyID: {
1782 PointerType *PTy = cast<PointerType>(Ty);
1783 unsigned AddrSpace = PTy->getAddressSpace();
1784
1785 // For the purposes of our Vulkan SPIR-V type system, constant and global
1786 // are conflated.
1787 bool UseExistingOpTypePointer = false;
1788 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001789 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1790 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001791 // Check to see if we already created this type (for instance, if we
1792 // had a constant <type>* and a global <type>*, the type would be
1793 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001794 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1795 if (0 < TypeMap.count(GlobalTy)) {
1796 TypeMap[PTy] = TypeMap[GlobalTy];
1797 UseExistingOpTypePointer = true;
1798 break;
1799 }
David Neto22f144c2017-06-12 14:26:21 -04001800 }
1801 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001802 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1803 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001804
alan-bakerb6b09dc2018-11-08 16:59:28 -05001805 // Check to see if we already created this type (for instance, if we
1806 // had a constant <type>* and a global <type>*, the type would be
1807 // created by one of these types, and shared by both).
1808 auto ConstantTy =
1809 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001810 if (0 < TypeMap.count(ConstantTy)) {
1811 TypeMap[PTy] = TypeMap[ConstantTy];
1812 UseExistingOpTypePointer = true;
1813 }
David Neto22f144c2017-06-12 14:26:21 -04001814 }
1815 }
1816
David Neto862b7d82018-06-14 18:48:37 -04001817 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001818
David Neto862b7d82018-06-14 18:48:37 -04001819 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001820 //
1821 // Generate OpTypePointer.
1822 //
1823
1824 // OpTypePointer
1825 // Ops[0] = Storage Class
1826 // Ops[1] = Element Type ID
1827 SPIRVOperandList Ops;
1828
David Neto257c3892018-04-11 13:19:45 -04001829 Ops << MkNum(GetStorageClass(AddrSpace))
1830 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001831
David Neto87846742018-04-11 17:36:22 -04001832 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001833 SPIRVInstList.push_back(Inst);
1834 }
David Neto22f144c2017-06-12 14:26:21 -04001835 break;
1836 }
1837 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001838 StructType *STy = cast<StructType>(Ty);
1839
1840 // Handle sampler type.
1841 if (STy->isOpaque()) {
1842 if (STy->getName().equals("opencl.sampler_t")) {
1843 //
1844 // Generate OpTypeSampler
1845 //
1846 // Empty Ops.
1847 SPIRVOperandList Ops;
1848
David Neto87846742018-04-11 17:36:22 -04001849 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001850 SPIRVInstList.push_back(Inst);
1851 break;
1852 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1853 STy->getName().equals("opencl.image2d_wo_t") ||
1854 STy->getName().equals("opencl.image3d_ro_t") ||
1855 STy->getName().equals("opencl.image3d_wo_t")) {
1856 //
1857 // Generate OpTypeImage
1858 //
1859 // Ops[0] = Sampled Type ID
1860 // Ops[1] = Dim ID
1861 // Ops[2] = Depth (Literal Number)
1862 // Ops[3] = Arrayed (Literal Number)
1863 // Ops[4] = MS (Literal Number)
1864 // Ops[5] = Sampled (Literal Number)
1865 // Ops[6] = Image Format ID
1866 //
1867 SPIRVOperandList Ops;
1868
1869 // TODO: Changed Sampled Type according to situations.
1870 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001871 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001872
1873 spv::Dim DimID = spv::Dim2D;
1874 if (STy->getName().equals("opencl.image3d_ro_t") ||
1875 STy->getName().equals("opencl.image3d_wo_t")) {
1876 DimID = spv::Dim3D;
1877 }
David Neto257c3892018-04-11 13:19:45 -04001878 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001879
1880 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001881 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001882
1883 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001884 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001885
1886 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001887 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001888
1889 // TODO: Set up Sampled.
1890 //
1891 // From Spec
1892 //
1893 // 0 indicates this is only known at run time, not at compile time
1894 // 1 indicates will be used with sampler
1895 // 2 indicates will be used without a sampler (a storage image)
1896 uint32_t Sampled = 1;
1897 if (STy->getName().equals("opencl.image2d_wo_t") ||
1898 STy->getName().equals("opencl.image3d_wo_t")) {
1899 Sampled = 2;
1900 }
David Neto257c3892018-04-11 13:19:45 -04001901 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001902
1903 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001904 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001905
David Neto87846742018-04-11 17:36:22 -04001906 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001907 SPIRVInstList.push_back(Inst);
1908 break;
1909 }
1910 }
1911
1912 //
1913 // Generate OpTypeStruct
1914 //
1915 // Ops[0] ... Ops[n] = Member IDs
1916 SPIRVOperandList Ops;
1917
1918 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001919 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001920 }
1921
David Neto22f144c2017-06-12 14:26:21 -04001922 uint32_t STyID = nextID;
1923
alan-bakerb6b09dc2018-11-08 16:59:28 -05001924 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001925 SPIRVInstList.push_back(Inst);
1926
1927 // Generate OpMemberDecorate.
1928 auto DecoInsertPoint =
1929 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1930 [](SPIRVInstruction *Inst) -> bool {
1931 return Inst->getOpcode() != spv::OpDecorate &&
1932 Inst->getOpcode() != spv::OpMemberDecorate &&
1933 Inst->getOpcode() != spv::OpExtInstImport;
1934 });
1935
David Netoc463b372017-08-10 15:32:21 -04001936 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001937 // Search for the correct offsets if this type was remapped.
1938 std::vector<uint32_t> *offsets = nullptr;
1939 auto iter = RemappedUBOTypeOffsets.find(STy);
1940 if (iter != RemappedUBOTypeOffsets.end()) {
1941 offsets = &iter->second;
1942 }
David Netoc463b372017-08-10 15:32:21 -04001943
David Neto862b7d82018-06-14 18:48:37 -04001944 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001945 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1946 MemberIdx++) {
1947 // Ops[0] = Structure Type ID
1948 // Ops[1] = Member Index(Literal Number)
1949 // Ops[2] = Decoration (Offset)
1950 // Ops[3] = Byte Offset (Literal Number)
1951 Ops.clear();
1952
David Neto257c3892018-04-11 13:19:45 -04001953 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001954
alan-bakerb6b09dc2018-11-08 16:59:28 -05001955 auto ByteOffset =
1956 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001957 if (offsets) {
1958 ByteOffset = (*offsets)[MemberIdx];
1959 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001960 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001961 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001962 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001963
David Neto87846742018-04-11 17:36:22 -04001964 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001965 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001966 }
1967
1968 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001969 if (StructTypesNeedingBlock.idFor(STy)) {
1970 Ops.clear();
1971 // Use Block decorations with StorageBuffer storage class.
1972 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001973
David Neto862b7d82018-06-14 18:48:37 -04001974 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1975 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001976 }
1977 break;
1978 }
1979 case Type::IntegerTyID: {
1980 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1981
1982 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001983 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001984 SPIRVInstList.push_back(Inst);
1985 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001986 if (!clspv::Option::Int8Support()) {
1987 // i8 is added to TypeMap as i32.
1988 // No matter what LLVM type is requested first, always alias the
1989 // second one's SPIR-V type to be the same as the one we generated
1990 // first.
1991 unsigned aliasToWidth = 0;
1992 if (BitWidth == 8) {
1993 aliasToWidth = 32;
1994 BitWidth = 32;
1995 } else if (BitWidth == 32) {
1996 aliasToWidth = 8;
1997 }
1998 if (aliasToWidth) {
1999 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2000 auto where = TypeMap.find(otherType);
2001 if (where == TypeMap.end()) {
2002 // Go ahead and make it, but also map the other type to it.
2003 TypeMap[otherType] = nextID;
2004 } else {
2005 // Alias this SPIR-V type the existing type.
2006 TypeMap[Ty] = where->second;
2007 break;
2008 }
David Neto391aeb12017-08-26 15:51:58 -04002009 }
David Neto22f144c2017-06-12 14:26:21 -04002010 }
2011
David Neto257c3892018-04-11 13:19:45 -04002012 SPIRVOperandList Ops;
2013 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002014
2015 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002016 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002017 }
2018 break;
2019 }
2020 case Type::HalfTyID:
2021 case Type::FloatTyID:
2022 case Type::DoubleTyID: {
2023 SPIRVOperand *WidthOp = new SPIRVOperand(
2024 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2025
2026 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002027 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002028 break;
2029 }
2030 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002031 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002032 const uint64_t Length = ArrTy->getArrayNumElements();
2033 if (Length == 0) {
2034 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002035
David Neto862b7d82018-06-14 18:48:37 -04002036 // Only generate the type once.
2037 // TODO(dneto): Can it ever be generated more than once?
2038 // Doesn't LLVM type uniqueness guarantee we'll only see this
2039 // once?
2040 Type *EleTy = ArrTy->getArrayElementType();
2041 if (OpRuntimeTyMap.count(EleTy) == 0) {
2042 uint32_t OpTypeRuntimeArrayID = nextID;
2043 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002044
David Neto862b7d82018-06-14 18:48:37 -04002045 //
2046 // Generate OpTypeRuntimeArray.
2047 //
David Neto22f144c2017-06-12 14:26:21 -04002048
David Neto862b7d82018-06-14 18:48:37 -04002049 // OpTypeRuntimeArray
2050 // Ops[0] = Element Type ID
2051 SPIRVOperandList Ops;
2052 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002053
David Neto862b7d82018-06-14 18:48:37 -04002054 SPIRVInstList.push_back(
2055 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002056
David Neto862b7d82018-06-14 18:48:37 -04002057 if (Hack_generate_runtime_array_stride_early) {
2058 // Generate OpDecorate.
2059 auto DecoInsertPoint = std::find_if(
2060 SPIRVInstList.begin(), SPIRVInstList.end(),
2061 [](SPIRVInstruction *Inst) -> bool {
2062 return Inst->getOpcode() != spv::OpDecorate &&
2063 Inst->getOpcode() != spv::OpMemberDecorate &&
2064 Inst->getOpcode() != spv::OpExtInstImport;
2065 });
David Neto22f144c2017-06-12 14:26:21 -04002066
David Neto862b7d82018-06-14 18:48:37 -04002067 // Ops[0] = Target ID
2068 // Ops[1] = Decoration (ArrayStride)
2069 // Ops[2] = Stride Number(Literal Number)
2070 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002071
David Neto862b7d82018-06-14 18:48:37 -04002072 Ops << MkId(OpTypeRuntimeArrayID)
2073 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002074 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002075
David Neto862b7d82018-06-14 18:48:37 -04002076 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2077 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2078 }
2079 }
David Neto22f144c2017-06-12 14:26:21 -04002080
David Neto862b7d82018-06-14 18:48:37 -04002081 } else {
David Neto22f144c2017-06-12 14:26:21 -04002082
David Neto862b7d82018-06-14 18:48:37 -04002083 //
2084 // Generate OpConstant and OpTypeArray.
2085 //
2086
2087 //
2088 // Generate OpConstant for array length.
2089 //
2090 // Ops[0] = Result Type ID
2091 // Ops[1] .. Ops[n] = Values LiteralNumber
2092 SPIRVOperandList Ops;
2093
2094 Type *LengthTy = Type::getInt32Ty(Context);
2095 uint32_t ResTyID = lookupType(LengthTy);
2096 Ops << MkId(ResTyID);
2097
2098 assert(Length < UINT32_MAX);
2099 Ops << MkNum(static_cast<uint32_t>(Length));
2100
2101 // Add constant for length to constant list.
2102 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2103 AllocatedVMap[CstLength] = nextID;
2104 VMap[CstLength] = nextID;
2105 uint32_t LengthID = nextID;
2106
2107 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2108 SPIRVInstList.push_back(CstInst);
2109
2110 // Remember to generate ArrayStride later
2111 getTypesNeedingArrayStride().insert(Ty);
2112
2113 //
2114 // Generate OpTypeArray.
2115 //
2116 // Ops[0] = Element Type ID
2117 // Ops[1] = Array Length Constant ID
2118 Ops.clear();
2119
2120 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2121 Ops << MkId(EleTyID) << MkId(LengthID);
2122
2123 // Update TypeMap with nextID.
2124 TypeMap[Ty] = nextID;
2125
2126 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2127 SPIRVInstList.push_back(ArrayInst);
2128 }
David Neto22f144c2017-06-12 14:26:21 -04002129 break;
2130 }
2131 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002132 // <4 x i8> is changed to i32 if i8 is not generally supported.
2133 if (!clspv::Option::Int8Support() &&
2134 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002135 if (Ty->getVectorNumElements() == 4) {
2136 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2137 break;
2138 } else {
2139 Ty->print(errs());
2140 llvm_unreachable("Support above i8 vector type");
2141 }
2142 }
2143
2144 // Ops[0] = Component Type ID
2145 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002146 SPIRVOperandList Ops;
2147 Ops << MkId(lookupType(Ty->getVectorElementType()))
2148 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002149
alan-bakerb6b09dc2018-11-08 16:59:28 -05002150 SPIRVInstruction *inst =
2151 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002152 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002153 break;
2154 }
2155 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002156 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002157 SPIRVInstList.push_back(Inst);
2158 break;
2159 }
2160 case Type::FunctionTyID: {
2161 // Generate SPIRV instruction for function type.
2162 FunctionType *FTy = cast<FunctionType>(Ty);
2163
2164 // Ops[0] = Return Type ID
2165 // Ops[1] ... Ops[n] = Parameter Type IDs
2166 SPIRVOperandList Ops;
2167
2168 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002169 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002170
2171 // Find SPIRV instructions for parameter types
2172 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2173 // Find SPIRV instruction for parameter type.
2174 auto ParamTy = FTy->getParamType(k);
2175 if (ParamTy->isPointerTy()) {
2176 auto PointeeTy = ParamTy->getPointerElementType();
2177 if (PointeeTy->isStructTy() &&
2178 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2179 ParamTy = PointeeTy;
2180 }
2181 }
2182
David Netoc6f3ab22018-04-06 18:02:31 -04002183 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002184 }
2185
David Neto87846742018-04-11 17:36:22 -04002186 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002187 SPIRVInstList.push_back(Inst);
2188 break;
2189 }
2190 }
2191 }
2192
2193 // Generate OpTypeSampledImage.
2194 TypeMapType &OpImageTypeMap = getImageTypeMap();
2195 for (auto &ImageType : OpImageTypeMap) {
2196 //
2197 // Generate OpTypeSampledImage.
2198 //
2199 // Ops[0] = Image Type ID
2200 //
2201 SPIRVOperandList Ops;
2202
2203 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002204 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002205
2206 // Update OpImageTypeMap.
2207 ImageType.second = nextID;
2208
David Neto87846742018-04-11 17:36:22 -04002209 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002210 SPIRVInstList.push_back(Inst);
2211 }
David Netoc6f3ab22018-04-06 18:02:31 -04002212
2213 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002214 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2215 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002216 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002217
2218 // Generate the spec constant.
2219 SPIRVOperandList Ops;
2220 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002221 SPIRVInstList.push_back(
2222 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002223
2224 // Generate the array type.
2225 Ops.clear();
2226 // The element type must have been created.
2227 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2228 assert(elem_ty_id);
2229 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2230
2231 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002232 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002233
2234 Ops.clear();
2235 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002236 SPIRVInstList.push_back(new SPIRVInstruction(
2237 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002238 }
David Neto22f144c2017-06-12 14:26:21 -04002239}
2240
2241void SPIRVProducerPass::GenerateSPIRVConstants() {
2242 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2243 ValueMapType &VMap = getValueMap();
2244 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2245 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002246 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002247
2248 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002249 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002250 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002251
2252 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002253 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002254 continue;
2255 }
2256
David Netofb9a7972017-08-25 17:08:24 -04002257 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002258 VMap[Cst] = nextID;
2259
2260 //
2261 // Generate OpConstant.
2262 //
2263
2264 // Ops[0] = Result Type ID
2265 // Ops[1] .. Ops[n] = Values LiteralNumber
2266 SPIRVOperandList Ops;
2267
David Neto257c3892018-04-11 13:19:45 -04002268 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002269
2270 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002271 spv::Op Opcode = spv::OpNop;
2272
2273 if (isa<UndefValue>(Cst)) {
2274 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002275 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002276 if (hack_undef && IsTypeNullable(Cst->getType())) {
2277 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002278 }
David Neto22f144c2017-06-12 14:26:21 -04002279 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2280 unsigned BitWidth = CI->getBitWidth();
2281 if (BitWidth == 1) {
2282 // If the bitwidth of constant is 1, generate OpConstantTrue or
2283 // OpConstantFalse.
2284 if (CI->getZExtValue()) {
2285 // Ops[0] = Result Type ID
2286 Opcode = spv::OpConstantTrue;
2287 } else {
2288 // Ops[0] = Result Type ID
2289 Opcode = spv::OpConstantFalse;
2290 }
David Neto22f144c2017-06-12 14:26:21 -04002291 } else {
2292 auto V = CI->getZExtValue();
2293 LiteralNum.push_back(V & 0xFFFFFFFF);
2294
2295 if (BitWidth > 32) {
2296 LiteralNum.push_back(V >> 32);
2297 }
2298
2299 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002300
David Neto257c3892018-04-11 13:19:45 -04002301 Ops << MkInteger(LiteralNum);
2302
2303 if (BitWidth == 32 && V == 0) {
2304 constant_i32_zero_id_ = nextID;
2305 }
David Neto22f144c2017-06-12 14:26:21 -04002306 }
2307 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2308 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2309 Type *CFPTy = CFP->getType();
2310 if (CFPTy->isFloatTy()) {
2311 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2312 } else {
2313 CFPTy->print(errs());
2314 llvm_unreachable("Implement this ConstantFP Type");
2315 }
2316
2317 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002318
David Neto257c3892018-04-11 13:19:45 -04002319 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002320 } else if (isa<ConstantDataSequential>(Cst) &&
2321 cast<ConstantDataSequential>(Cst)->isString()) {
2322 Cst->print(errs());
2323 llvm_unreachable("Implement this Constant");
2324
2325 } else if (const ConstantDataSequential *CDS =
2326 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002327 // Let's convert <4 x i8> constant to int constant specially.
2328 // This case occurs when all the values are specified as constant
2329 // ints.
2330 Type *CstTy = Cst->getType();
2331 if (is4xi8vec(CstTy)) {
2332 LLVMContext &Context = CstTy->getContext();
2333
2334 //
2335 // Generate OpConstant with OpTypeInt 32 0.
2336 //
Neil Henning39672102017-09-29 14:33:13 +01002337 uint32_t IntValue = 0;
2338 for (unsigned k = 0; k < 4; k++) {
2339 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002340 IntValue = (IntValue << 8) | (Val & 0xffu);
2341 }
2342
2343 Type *i32 = Type::getInt32Ty(Context);
2344 Constant *CstInt = ConstantInt::get(i32, IntValue);
2345 // If this constant is already registered on VMap, use it.
2346 if (VMap.count(CstInt)) {
2347 uint32_t CstID = VMap[CstInt];
2348 VMap[Cst] = CstID;
2349 continue;
2350 }
2351
David Neto257c3892018-04-11 13:19:45 -04002352 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002353
David Neto87846742018-04-11 17:36:22 -04002354 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002355 SPIRVInstList.push_back(CstInst);
2356
2357 continue;
2358 }
2359
2360 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002361 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2362 Constant *EleCst = CDS->getElementAsConstant(k);
2363 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002364 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002365 }
2366
2367 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002368 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2369 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002370 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002371 Type *CstTy = Cst->getType();
2372 if (is4xi8vec(CstTy)) {
2373 LLVMContext &Context = CstTy->getContext();
2374
2375 //
2376 // Generate OpConstant with OpTypeInt 32 0.
2377 //
Neil Henning39672102017-09-29 14:33:13 +01002378 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002379 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2380 I != E; ++I) {
2381 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002382 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002383 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2384 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002385 }
David Neto49351ac2017-08-26 17:32:20 -04002386 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002387 }
2388
David Neto49351ac2017-08-26 17:32:20 -04002389 Type *i32 = Type::getInt32Ty(Context);
2390 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002391 // If this constant is already registered on VMap, use it.
2392 if (VMap.count(CstInt)) {
2393 uint32_t CstID = VMap[CstInt];
2394 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002395 continue;
David Neto22f144c2017-06-12 14:26:21 -04002396 }
2397
David Neto257c3892018-04-11 13:19:45 -04002398 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002399
David Neto87846742018-04-11 17:36:22 -04002400 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002401 SPIRVInstList.push_back(CstInst);
2402
David Neto19a1bad2017-08-25 15:01:41 -04002403 continue;
David Neto22f144c2017-06-12 14:26:21 -04002404 }
2405
2406 // We use a constant composite in SPIR-V for our constant aggregate in
2407 // LLVM.
2408 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002409
2410 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2411 // Look up the ID of the element of this aggregate (which we will
2412 // previously have created a constant for).
2413 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2414
2415 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002416 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002417 }
2418 } else if (Cst->isNullValue()) {
2419 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002420 } else {
2421 Cst->print(errs());
2422 llvm_unreachable("Unsupported Constant???");
2423 }
2424
alan-baker5b86ed72019-02-15 08:26:50 -05002425 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2426 // Null pointer requires variable pointers.
2427 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2428 }
2429
David Neto87846742018-04-11 17:36:22 -04002430 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002431 SPIRVInstList.push_back(CstInst);
2432 }
2433}
2434
2435void SPIRVProducerPass::GenerateSamplers(Module &M) {
2436 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002437
alan-bakerb6b09dc2018-11-08 16:59:28 -05002438 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002439 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002440 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002441 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2442 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002443
David Neto862b7d82018-06-14 18:48:37 -04002444 // We might have samplers in the sampler map that are not used
2445 // in the translation unit. We need to allocate variables
2446 // for them and bindings too.
2447 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002448
alan-bakerb6b09dc2018-11-08 16:59:28 -05002449 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2450 if (!var_fn)
2451 return;
David Neto862b7d82018-06-14 18:48:37 -04002452 for (auto user : var_fn->users()) {
2453 // Populate SamplerLiteralToDescriptorSetMap and
2454 // SamplerLiteralToBindingMap.
2455 //
2456 // Look for calls like
2457 // call %opencl.sampler_t addrspace(2)*
2458 // @clspv.sampler.var.literal(
2459 // i32 descriptor,
2460 // i32 binding,
2461 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002462 if (auto *call = dyn_cast<CallInst>(user)) {
2463 const size_t index_into_sampler_map = static_cast<size_t>(
2464 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002465 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002466 errs() << "Out of bounds index to sampler map: "
2467 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002468 llvm_unreachable("bad sampler init: out of bounds");
2469 }
2470
2471 auto sampler_value = sampler_map[index_into_sampler_map].first;
2472 const auto descriptor_set = static_cast<unsigned>(
2473 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2474 const auto binding = static_cast<unsigned>(
2475 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2476
2477 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2478 SamplerLiteralToBindingMap[sampler_value] = binding;
2479 used_bindings.insert(binding);
2480 }
2481 }
2482
2483 unsigned index = 0;
2484 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002485 // Generate OpVariable.
2486 //
2487 // GIDOps[0] : Result Type ID
2488 // GIDOps[1] : Storage Class
2489 SPIRVOperandList Ops;
2490
David Neto257c3892018-04-11 13:19:45 -04002491 Ops << MkId(lookupType(SamplerTy))
2492 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002493
David Neto862b7d82018-06-14 18:48:37 -04002494 auto sampler_var_id = nextID++;
2495 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002496 SPIRVInstList.push_back(Inst);
2497
David Neto862b7d82018-06-14 18:48:37 -04002498 SamplerMapIndexToIDMap[index] = sampler_var_id;
2499 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002500
2501 // Find Insert Point for OpDecorate.
2502 auto DecoInsertPoint =
2503 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2504 [](SPIRVInstruction *Inst) -> bool {
2505 return Inst->getOpcode() != spv::OpDecorate &&
2506 Inst->getOpcode() != spv::OpMemberDecorate &&
2507 Inst->getOpcode() != spv::OpExtInstImport;
2508 });
2509
2510 // Ops[0] = Target ID
2511 // Ops[1] = Decoration (DescriptorSet)
2512 // Ops[2] = LiteralNumber according to Decoration
2513 Ops.clear();
2514
David Neto862b7d82018-06-14 18:48:37 -04002515 unsigned descriptor_set;
2516 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002517 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2518 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002519 // This sampler is not actually used. Find the next one.
2520 for (binding = 0; used_bindings.count(binding); binding++)
2521 ;
2522 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2523 used_bindings.insert(binding);
2524 } else {
2525 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2526 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2527 }
2528
2529 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2530 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002531
alan-bakerf5e5f692018-11-27 08:33:24 -05002532 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2533 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002534
David Neto87846742018-04-11 17:36:22 -04002535 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002536 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2537
2538 // Ops[0] = Target ID
2539 // Ops[1] = Decoration (Binding)
2540 // Ops[2] = LiteralNumber according to Decoration
2541 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002542 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2543 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002544
David Neto87846742018-04-11 17:36:22 -04002545 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002546 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002547
2548 index++;
David Neto22f144c2017-06-12 14:26:21 -04002549 }
David Neto862b7d82018-06-14 18:48:37 -04002550}
David Neto22f144c2017-06-12 14:26:21 -04002551
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002552void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002553 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2554 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002555
David Neto862b7d82018-06-14 18:48:37 -04002556 // Generate variables. Make one for each of resource var info object.
2557 for (auto *info : ModuleOrderedResourceVars) {
2558 Type *type = info->var_fn->getReturnType();
2559 // Remap the address space for opaque types.
2560 switch (info->arg_kind) {
2561 case clspv::ArgKind::Sampler:
2562 case clspv::ArgKind::ReadOnlyImage:
2563 case clspv::ArgKind::WriteOnlyImage:
2564 type = PointerType::get(type->getPointerElementType(),
2565 clspv::AddressSpace::UniformConstant);
2566 break;
2567 default:
2568 break;
2569 }
David Neto22f144c2017-06-12 14:26:21 -04002570
David Neto862b7d82018-06-14 18:48:37 -04002571 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002572
David Neto862b7d82018-06-14 18:48:37 -04002573 const auto type_id = lookupType(type);
2574 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2575 SPIRVOperandList Ops;
2576 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002577
David Neto862b7d82018-06-14 18:48:37 -04002578 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2579 SPIRVInstList.push_back(Inst);
2580
2581 // Map calls to the variable-builtin-function.
2582 for (auto &U : info->var_fn->uses()) {
2583 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2584 const auto set = unsigned(
2585 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2586 const auto binding = unsigned(
2587 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2588 if (set == info->descriptor_set && binding == info->binding) {
2589 switch (info->arg_kind) {
2590 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002591 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002592 case clspv::ArgKind::Pod:
2593 // The call maps to the variable directly.
2594 VMap[call] = info->var_id;
2595 break;
2596 case clspv::ArgKind::Sampler:
2597 case clspv::ArgKind::ReadOnlyImage:
2598 case clspv::ArgKind::WriteOnlyImage:
2599 // The call maps to a load we generate later.
2600 ResourceVarDeferredLoadCalls[call] = info->var_id;
2601 break;
2602 default:
2603 llvm_unreachable("Unhandled arg kind");
2604 }
2605 }
David Neto22f144c2017-06-12 14:26:21 -04002606 }
David Neto862b7d82018-06-14 18:48:37 -04002607 }
2608 }
David Neto22f144c2017-06-12 14:26:21 -04002609
David Neto862b7d82018-06-14 18:48:37 -04002610 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002611
David Neto862b7d82018-06-14 18:48:37 -04002612 // Find Insert Point for OpDecorate.
2613 auto DecoInsertPoint =
2614 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2615 [](SPIRVInstruction *Inst) -> bool {
2616 return Inst->getOpcode() != spv::OpDecorate &&
2617 Inst->getOpcode() != spv::OpMemberDecorate &&
2618 Inst->getOpcode() != spv::OpExtInstImport;
2619 });
2620
2621 SPIRVOperandList Ops;
2622 for (auto *info : ModuleOrderedResourceVars) {
2623 // Decorate with DescriptorSet and Binding.
2624 Ops.clear();
2625 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2626 << MkNum(info->descriptor_set);
2627 SPIRVInstList.insert(DecoInsertPoint,
2628 new SPIRVInstruction(spv::OpDecorate, Ops));
2629
2630 Ops.clear();
2631 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2632 << MkNum(info->binding);
2633 SPIRVInstList.insert(DecoInsertPoint,
2634 new SPIRVInstruction(spv::OpDecorate, Ops));
2635
alan-bakere9308012019-03-15 10:25:13 -04002636 if (info->coherent) {
2637 // Decorate with Coherent if required for the variable.
2638 Ops.clear();
2639 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2640 SPIRVInstList.insert(DecoInsertPoint,
2641 new SPIRVInstruction(spv::OpDecorate, Ops));
2642 }
2643
David Neto862b7d82018-06-14 18:48:37 -04002644 // Generate NonWritable and NonReadable
2645 switch (info->arg_kind) {
2646 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002647 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002648 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2649 clspv::AddressSpace::Constant) {
2650 Ops.clear();
2651 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2652 SPIRVInstList.insert(DecoInsertPoint,
2653 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002654 }
David Neto862b7d82018-06-14 18:48:37 -04002655 break;
David Neto862b7d82018-06-14 18:48:37 -04002656 case clspv::ArgKind::WriteOnlyImage:
2657 Ops.clear();
2658 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2659 SPIRVInstList.insert(DecoInsertPoint,
2660 new SPIRVInstruction(spv::OpDecorate, Ops));
2661 break;
2662 default:
2663 break;
David Neto22f144c2017-06-12 14:26:21 -04002664 }
2665 }
2666}
2667
2668void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002669 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002670 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2671 ValueMapType &VMap = getValueMap();
2672 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002673 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002674
2675 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2676 Type *Ty = GV.getType();
2677 PointerType *PTy = cast<PointerType>(Ty);
2678
2679 uint32_t InitializerID = 0;
2680
2681 // Workgroup size is handled differently (it goes into a constant)
2682 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2683 std::vector<bool> HasMDVec;
2684 uint32_t PrevXDimCst = 0xFFFFFFFF;
2685 uint32_t PrevYDimCst = 0xFFFFFFFF;
2686 uint32_t PrevZDimCst = 0xFFFFFFFF;
2687 for (Function &Func : *GV.getParent()) {
2688 if (Func.isDeclaration()) {
2689 continue;
2690 }
2691
2692 // We only need to check kernels.
2693 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2694 continue;
2695 }
2696
2697 if (const MDNode *MD =
2698 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2699 uint32_t CurXDimCst = static_cast<uint32_t>(
2700 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2701 uint32_t CurYDimCst = static_cast<uint32_t>(
2702 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2703 uint32_t CurZDimCst = static_cast<uint32_t>(
2704 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2705
2706 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2707 PrevZDimCst == 0xFFFFFFFF) {
2708 PrevXDimCst = CurXDimCst;
2709 PrevYDimCst = CurYDimCst;
2710 PrevZDimCst = CurZDimCst;
2711 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2712 CurZDimCst != PrevZDimCst) {
2713 llvm_unreachable(
2714 "reqd_work_group_size must be the same across all kernels");
2715 } else {
2716 continue;
2717 }
2718
2719 //
2720 // Generate OpConstantComposite.
2721 //
2722 // Ops[0] : Result Type ID
2723 // Ops[1] : Constant size for x dimension.
2724 // Ops[2] : Constant size for y dimension.
2725 // Ops[3] : Constant size for z dimension.
2726 SPIRVOperandList Ops;
2727
2728 uint32_t XDimCstID =
2729 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2730 uint32_t YDimCstID =
2731 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2732 uint32_t ZDimCstID =
2733 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2734
2735 InitializerID = nextID;
2736
David Neto257c3892018-04-11 13:19:45 -04002737 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2738 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002739
David Neto87846742018-04-11 17:36:22 -04002740 auto *Inst =
2741 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002742 SPIRVInstList.push_back(Inst);
2743
2744 HasMDVec.push_back(true);
2745 } else {
2746 HasMDVec.push_back(false);
2747 }
2748 }
2749
2750 // Check all kernels have same definitions for work_group_size.
2751 bool HasMD = false;
2752 if (!HasMDVec.empty()) {
2753 HasMD = HasMDVec[0];
2754 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2755 if (HasMD != HasMDVec[i]) {
2756 llvm_unreachable(
2757 "Kernels should have consistent work group size definition");
2758 }
2759 }
2760 }
2761
2762 // If all kernels do not have metadata for reqd_work_group_size, generate
2763 // OpSpecConstants for x/y/z dimension.
2764 if (!HasMD) {
2765 //
2766 // Generate OpSpecConstants for x/y/z dimension.
2767 //
2768 // Ops[0] : Result Type ID
2769 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2770 uint32_t XDimCstID = 0;
2771 uint32_t YDimCstID = 0;
2772 uint32_t ZDimCstID = 0;
2773
David Neto22f144c2017-06-12 14:26:21 -04002774 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002775 uint32_t result_type_id =
2776 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002777
David Neto257c3892018-04-11 13:19:45 -04002778 // X Dimension
2779 Ops << MkId(result_type_id) << MkNum(1);
2780 XDimCstID = nextID++;
2781 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002782 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002783
2784 // Y Dimension
2785 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002786 Ops << MkId(result_type_id) << MkNum(1);
2787 YDimCstID = nextID++;
2788 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002789 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002790
2791 // Z Dimension
2792 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002793 Ops << MkId(result_type_id) << MkNum(1);
2794 ZDimCstID = nextID++;
2795 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002796 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002797
David Neto257c3892018-04-11 13:19:45 -04002798 BuiltinDimVec.push_back(XDimCstID);
2799 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002800 BuiltinDimVec.push_back(ZDimCstID);
2801
David Neto22f144c2017-06-12 14:26:21 -04002802 //
2803 // Generate OpSpecConstantComposite.
2804 //
2805 // Ops[0] : Result Type ID
2806 // Ops[1] : Constant size for x dimension.
2807 // Ops[2] : Constant size for y dimension.
2808 // Ops[3] : Constant size for z dimension.
2809 InitializerID = nextID;
2810
2811 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002812 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2813 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002814
David Neto87846742018-04-11 17:36:22 -04002815 auto *Inst =
2816 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002817 SPIRVInstList.push_back(Inst);
2818 }
2819 }
2820
David Neto22f144c2017-06-12 14:26:21 -04002821 VMap[&GV] = nextID;
2822
2823 //
2824 // Generate OpVariable.
2825 //
2826 // GIDOps[0] : Result Type ID
2827 // GIDOps[1] : Storage Class
2828 SPIRVOperandList Ops;
2829
David Neto85082642018-03-24 06:55:20 -07002830 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002831 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002832
David Neto85082642018-03-24 06:55:20 -07002833 if (GV.hasInitializer()) {
2834 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002835 }
2836
David Neto85082642018-03-24 06:55:20 -07002837 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002838 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002839 clspv::Option::ModuleConstantsInStorageBuffer();
2840
2841 if (0 != InitializerID) {
2842 if (!module_scope_constant_external_init) {
2843 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002844 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002845 }
2846 }
2847 const uint32_t var_id = nextID++;
2848
David Neto87846742018-04-11 17:36:22 -04002849 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002850 SPIRVInstList.push_back(Inst);
2851
2852 // If we have a builtin.
2853 if (spv::BuiltInMax != BuiltinType) {
2854 // Find Insert Point for OpDecorate.
2855 auto DecoInsertPoint =
2856 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2857 [](SPIRVInstruction *Inst) -> bool {
2858 return Inst->getOpcode() != spv::OpDecorate &&
2859 Inst->getOpcode() != spv::OpMemberDecorate &&
2860 Inst->getOpcode() != spv::OpExtInstImport;
2861 });
2862 //
2863 // Generate OpDecorate.
2864 //
2865 // DOps[0] = Target ID
2866 // DOps[1] = Decoration (Builtin)
2867 // DOps[2] = BuiltIn ID
2868 uint32_t ResultID;
2869
2870 // WorkgroupSize is different, we decorate the constant composite that has
2871 // its value, rather than the variable that we use to access the value.
2872 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2873 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002874 // Save both the value and variable IDs for later.
2875 WorkgroupSizeValueID = InitializerID;
2876 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002877 } else {
2878 ResultID = VMap[&GV];
2879 }
2880
2881 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002882 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2883 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002884
David Neto87846742018-04-11 17:36:22 -04002885 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002886 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002887 } else if (module_scope_constant_external_init) {
2888 // This module scope constant is initialized from a storage buffer with data
2889 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002890 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002891
David Neto862b7d82018-06-14 18:48:37 -04002892 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002893 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2894 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002895 std::string hexbytes;
2896 llvm::raw_string_ostream str(hexbytes);
2897 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2898 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2899 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002900
2901 // Find Insert Point for OpDecorate.
2902 auto DecoInsertPoint =
2903 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2904 [](SPIRVInstruction *Inst) -> bool {
2905 return Inst->getOpcode() != spv::OpDecorate &&
2906 Inst->getOpcode() != spv::OpMemberDecorate &&
2907 Inst->getOpcode() != spv::OpExtInstImport;
2908 });
2909
David Neto257c3892018-04-11 13:19:45 -04002910 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002911 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002912 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2913 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002914 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002915
2916 // OpDecorate %var DescriptorSet <descriptor_set>
2917 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002918 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2919 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002920 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002921 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002922 }
2923}
2924
David Netoc6f3ab22018-04-06 18:02:31 -04002925void SPIRVProducerPass::GenerateWorkgroupVars() {
2926 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002927 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2928 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002929 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002930
2931 // Generate OpVariable.
2932 //
2933 // GIDOps[0] : Result Type ID
2934 // GIDOps[1] : Storage Class
2935 SPIRVOperandList Ops;
2936 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2937
2938 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002939 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002940 }
2941}
2942
David Neto862b7d82018-06-14 18:48:37 -04002943void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2944 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002945 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2946 return;
2947 }
David Neto862b7d82018-06-14 18:48:37 -04002948 // Gather the list of resources that are used by this function's arguments.
2949 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2950
alan-bakerf5e5f692018-11-27 08:33:24 -05002951 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2952 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002953 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002954 std::string kind =
2955 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2956 ? "pod_ubo"
2957 : argKind;
2958 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002959 };
2960
2961 auto *fty = F.getType()->getPointerElementType();
2962 auto *func_ty = dyn_cast<FunctionType>(fty);
2963
2964 // If we've clustereed POD arguments, then argument details are in metadata.
2965 // If an argument maps to a resource variable, then get descriptor set and
2966 // binding from the resoure variable. Other info comes from the metadata.
2967 const auto *arg_map = F.getMetadata("kernel_arg_map");
2968 if (arg_map) {
2969 for (const auto &arg : arg_map->operands()) {
2970 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002971 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002972 const auto name =
2973 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2974 const auto old_index =
2975 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2976 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002977 const size_t new_index = static_cast<size_t>(
2978 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002979 const auto offset =
2980 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002981 const auto arg_size =
2982 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002983 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002984 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002985 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002986 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05002987
2988 uint32_t descriptor_set = 0;
2989 uint32_t binding = 0;
2990 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2991 F.getName(),
2992 name,
2993 static_cast<uint32_t>(old_index),
2994 argKind,
2995 static_cast<uint32_t>(spec_id),
2996 // This will be set below for pointer-to-local args.
2997 0,
2998 static_cast<uint32_t>(offset),
2999 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003000 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003001 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3002 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3003 DL));
David Neto862b7d82018-06-14 18:48:37 -04003004 } else {
3005 auto *info = resource_var_at_index[new_index];
3006 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003007 descriptor_set = info->descriptor_set;
3008 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003009 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003010 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003011 }
3012 } else {
3013 // There is no argument map.
3014 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003015 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003016
3017 SmallVector<Argument *, 4> arguments;
3018 for (auto &arg : F.args()) {
3019 arguments.push_back(&arg);
3020 }
3021
3022 unsigned arg_index = 0;
3023 for (auto *info : resource_var_at_index) {
3024 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003025 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003026 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003027 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003028 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003029 }
3030
alan-bakerf5e5f692018-11-27 08:33:24 -05003031 // Local pointer arguments are unused in this case. Offset is always zero.
3032 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3033 F.getName(), arg->getName(),
3034 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3035 0, 0,
3036 0, arg_size};
3037 descriptorMapEntries->emplace_back(std::move(kernel_data),
3038 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003039 }
3040 arg_index++;
3041 }
3042 // Generate mappings for pointer-to-local arguments.
3043 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3044 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003045 auto where = LocalArgSpecIds.find(arg);
3046 if (where != LocalArgSpecIds.end()) {
3047 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003048 // Pod arguments members are unused in this case.
3049 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3050 F.getName(),
3051 arg->getName(),
3052 arg_index,
3053 ArgKind::Local,
3054 static_cast<uint32_t>(local_arg_info.spec_id),
3055 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3056 0,
3057 0};
3058 // Pointer-to-local arguments do not utilize descriptor set and binding.
3059 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003060 }
3061 }
3062 }
3063}
3064
David Neto22f144c2017-06-12 14:26:21 -04003065void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3066 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3067 ValueMapType &VMap = getValueMap();
3068 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003069 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3070 auto &GlobalConstArgSet = getGlobalConstArgSet();
3071
3072 FunctionType *FTy = F.getFunctionType();
3073
3074 //
David Neto22f144c2017-06-12 14:26:21 -04003075 // Generate OPFunction.
3076 //
3077
3078 // FOps[0] : Result Type ID
3079 // FOps[1] : Function Control
3080 // FOps[2] : Function Type ID
3081 SPIRVOperandList FOps;
3082
3083 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003084 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003085
3086 // Check function attributes for SPIRV Function Control.
3087 uint32_t FuncControl = spv::FunctionControlMaskNone;
3088 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3089 FuncControl |= spv::FunctionControlInlineMask;
3090 }
3091 if (F.hasFnAttribute(Attribute::NoInline)) {
3092 FuncControl |= spv::FunctionControlDontInlineMask;
3093 }
3094 // TODO: Check llvm attribute for Function Control Pure.
3095 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3096 FuncControl |= spv::FunctionControlPureMask;
3097 }
3098 // TODO: Check llvm attribute for Function Control Const.
3099 if (F.hasFnAttribute(Attribute::ReadNone)) {
3100 FuncControl |= spv::FunctionControlConstMask;
3101 }
3102
David Neto257c3892018-04-11 13:19:45 -04003103 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003104
3105 uint32_t FTyID;
3106 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3107 SmallVector<Type *, 4> NewFuncParamTys;
3108 FunctionType *NewFTy =
3109 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3110 FTyID = lookupType(NewFTy);
3111 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003112 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003113 if (GlobalConstFuncTyMap.count(FTy)) {
3114 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3115 } else {
3116 FTyID = lookupType(FTy);
3117 }
3118 }
3119
David Neto257c3892018-04-11 13:19:45 -04003120 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003121
3122 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3123 EntryPoints.push_back(std::make_pair(&F, nextID));
3124 }
3125
3126 VMap[&F] = nextID;
3127
David Neto482550a2018-03-24 05:21:07 -07003128 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003129 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3130 }
David Neto22f144c2017-06-12 14:26:21 -04003131 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003132 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003133 SPIRVInstList.push_back(FuncInst);
3134
3135 //
3136 // Generate OpFunctionParameter for Normal function.
3137 //
3138
3139 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003140
3141 // Find Insert Point for OpDecorate.
3142 auto DecoInsertPoint =
3143 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3144 [](SPIRVInstruction *Inst) -> bool {
3145 return Inst->getOpcode() != spv::OpDecorate &&
3146 Inst->getOpcode() != spv::OpMemberDecorate &&
3147 Inst->getOpcode() != spv::OpExtInstImport;
3148 });
3149
David Neto22f144c2017-06-12 14:26:21 -04003150 // Iterate Argument for name instead of param type from function type.
3151 unsigned ArgIdx = 0;
3152 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003153 uint32_t param_id = nextID++;
3154 VMap[&Arg] = param_id;
3155
3156 if (CalledWithCoherentResource(Arg)) {
3157 // If the arg is passed a coherent resource ever, then decorate this
3158 // parameter with Coherent too.
3159 SPIRVOperandList decoration_ops;
3160 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
3161 SPIRVInstList.insert(DecoInsertPoint,
3162 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
3163 }
David Neto22f144c2017-06-12 14:26:21 -04003164
3165 // ParamOps[0] : Result Type ID
3166 SPIRVOperandList ParamOps;
3167
3168 // Find SPIRV instruction for parameter type.
3169 uint32_t ParamTyID = lookupType(Arg.getType());
3170 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3171 if (GlobalConstFuncTyMap.count(FTy)) {
3172 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3173 Type *EleTy = PTy->getPointerElementType();
3174 Type *ArgTy =
3175 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3176 ParamTyID = lookupType(ArgTy);
3177 GlobalConstArgSet.insert(&Arg);
3178 }
3179 }
3180 }
David Neto257c3892018-04-11 13:19:45 -04003181 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003182
3183 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003184 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003185 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003186 SPIRVInstList.push_back(ParamInst);
3187
3188 ArgIdx++;
3189 }
3190 }
3191}
3192
alan-bakerb6b09dc2018-11-08 16:59:28 -05003193void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003194 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3195 EntryPointVecType &EntryPoints = getEntryPointVec();
3196 ValueMapType &VMap = getValueMap();
3197 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3198 uint32_t &ExtInstImportID = getOpExtInstImportID();
3199 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3200
3201 // Set up insert point.
3202 auto InsertPoint = SPIRVInstList.begin();
3203
3204 //
3205 // Generate OpCapability
3206 //
3207 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3208
3209 // Ops[0] = Capability
3210 SPIRVOperandList Ops;
3211
David Neto87846742018-04-11 17:36:22 -04003212 auto *CapInst =
3213 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003214 SPIRVInstList.insert(InsertPoint, CapInst);
3215
3216 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003217 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3218 // Generate OpCapability for i8 type.
3219 SPIRVInstList.insert(InsertPoint,
3220 new SPIRVInstruction(spv::OpCapability,
3221 {MkNum(spv::CapabilityInt8)}));
3222 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003223 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003224 SPIRVInstList.insert(InsertPoint,
3225 new SPIRVInstruction(spv::OpCapability,
3226 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003227 } else if (Ty->isIntegerTy(64)) {
3228 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003229 SPIRVInstList.insert(InsertPoint,
3230 new SPIRVInstruction(spv::OpCapability,
3231 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003232 } else if (Ty->isHalfTy()) {
3233 // Generate OpCapability for half type.
3234 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003235 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3236 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003237 } else if (Ty->isDoubleTy()) {
3238 // Generate OpCapability for double type.
3239 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003240 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3241 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003242 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3243 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003244 if (STy->getName().equals("opencl.image2d_wo_t") ||
3245 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003246 // Generate OpCapability for write only image type.
3247 SPIRVInstList.insert(
3248 InsertPoint,
3249 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003250 spv::OpCapability,
3251 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003252 }
3253 }
3254 }
3255 }
3256
David Neto5c22a252018-03-15 16:07:41 -04003257 { // OpCapability ImageQuery
3258 bool hasImageQuery = false;
3259 for (const char *imageQuery : {
3260 "_Z15get_image_width14ocl_image2d_ro",
3261 "_Z15get_image_width14ocl_image2d_wo",
3262 "_Z16get_image_height14ocl_image2d_ro",
3263 "_Z16get_image_height14ocl_image2d_wo",
3264 }) {
3265 if (module.getFunction(imageQuery)) {
3266 hasImageQuery = true;
3267 break;
3268 }
3269 }
3270 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003271 auto *ImageQueryCapInst = new SPIRVInstruction(
3272 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003273 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3274 }
3275 }
3276
David Neto22f144c2017-06-12 14:26:21 -04003277 if (hasVariablePointers()) {
3278 //
David Neto22f144c2017-06-12 14:26:21 -04003279 // Generate OpCapability.
3280 //
3281 // Ops[0] = Capability
3282 //
3283 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003284 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003285
David Neto87846742018-04-11 17:36:22 -04003286 SPIRVInstList.insert(InsertPoint,
3287 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003288 } else if (hasVariablePointersStorageBuffer()) {
3289 //
3290 // Generate OpCapability.
3291 //
3292 // Ops[0] = Capability
3293 //
3294 Ops.clear();
3295 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003296
alan-baker5b86ed72019-02-15 08:26:50 -05003297 SPIRVInstList.insert(InsertPoint,
3298 new SPIRVInstruction(spv::OpCapability, Ops));
3299 }
3300
3301 // Always add the storage buffer extension
3302 {
David Neto22f144c2017-06-12 14:26:21 -04003303 //
3304 // Generate OpExtension.
3305 //
3306 // Ops[0] = Name (Literal String)
3307 //
alan-baker5b86ed72019-02-15 08:26:50 -05003308 auto *ExtensionInst = new SPIRVInstruction(
3309 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3310 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3311 }
David Neto22f144c2017-06-12 14:26:21 -04003312
alan-baker5b86ed72019-02-15 08:26:50 -05003313 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3314 //
3315 // Generate OpExtension.
3316 //
3317 // Ops[0] = Name (Literal String)
3318 //
3319 auto *ExtensionInst = new SPIRVInstruction(
3320 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3321 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003322 }
3323
3324 if (ExtInstImportID) {
3325 ++InsertPoint;
3326 }
3327
3328 //
3329 // Generate OpMemoryModel
3330 //
3331 // Memory model for Vulkan will always be GLSL450.
3332
3333 // Ops[0] = Addressing Model
3334 // Ops[1] = Memory Model
3335 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003336 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003337
David Neto87846742018-04-11 17:36:22 -04003338 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003339 SPIRVInstList.insert(InsertPoint, MemModelInst);
3340
3341 //
3342 // Generate OpEntryPoint
3343 //
3344 for (auto EntryPoint : EntryPoints) {
3345 // Ops[0] = Execution Model
3346 // Ops[1] = EntryPoint ID
3347 // Ops[2] = Name (Literal String)
3348 // ...
3349 //
3350 // TODO: Do we need to consider Interface ID for forward references???
3351 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003352 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003353 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3354 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003355
David Neto22f144c2017-06-12 14:26:21 -04003356 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003357 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003358 }
3359
David Neto87846742018-04-11 17:36:22 -04003360 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003361 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3362 }
3363
3364 for (auto EntryPoint : EntryPoints) {
3365 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3366 ->getMetadata("reqd_work_group_size")) {
3367
3368 if (!BuiltinDimVec.empty()) {
3369 llvm_unreachable(
3370 "Kernels should have consistent work group size definition");
3371 }
3372
3373 //
3374 // Generate OpExecutionMode
3375 //
3376
3377 // Ops[0] = Entry Point ID
3378 // Ops[1] = Execution Mode
3379 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3380 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003381 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003382
3383 uint32_t XDim = static_cast<uint32_t>(
3384 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3385 uint32_t YDim = static_cast<uint32_t>(
3386 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3387 uint32_t ZDim = static_cast<uint32_t>(
3388 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3389
David Neto257c3892018-04-11 13:19:45 -04003390 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003391
David Neto87846742018-04-11 17:36:22 -04003392 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003393 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3394 }
3395 }
3396
3397 //
3398 // Generate OpSource.
3399 //
3400 // Ops[0] = SourceLanguage ID
3401 // Ops[1] = Version (LiteralNum)
3402 //
3403 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003404 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003405
David Neto87846742018-04-11 17:36:22 -04003406 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003407 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3408
3409 if (!BuiltinDimVec.empty()) {
3410 //
3411 // Generate OpDecorates for x/y/z dimension.
3412 //
3413 // Ops[0] = Target ID
3414 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003415 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003416
3417 // X Dimension
3418 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003419 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003420 SPIRVInstList.insert(InsertPoint,
3421 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003422
3423 // Y Dimension
3424 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003425 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003426 SPIRVInstList.insert(InsertPoint,
3427 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003428
3429 // Z Dimension
3430 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003431 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003432 SPIRVInstList.insert(InsertPoint,
3433 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003434 }
3435}
3436
David Netob6e2e062018-04-25 10:32:06 -04003437void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3438 // Work around a driver bug. Initializers on Private variables might not
3439 // work. So the start of the kernel should store the initializer value to the
3440 // variables. Yes, *every* entry point pays this cost if *any* entry point
3441 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3442 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003443 // TODO(dneto): Remove this at some point once fixed drivers are widely
3444 // available.
David Netob6e2e062018-04-25 10:32:06 -04003445 if (WorkgroupSizeVarID) {
3446 assert(WorkgroupSizeValueID);
3447
3448 SPIRVOperandList Ops;
3449 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3450
3451 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3452 getSPIRVInstList().push_back(Inst);
3453 }
3454}
3455
David Neto22f144c2017-06-12 14:26:21 -04003456void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3457 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3458 ValueMapType &VMap = getValueMap();
3459
David Netob6e2e062018-04-25 10:32:06 -04003460 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003461
3462 for (BasicBlock &BB : F) {
3463 // Register BasicBlock to ValueMap.
3464 VMap[&BB] = nextID;
3465
3466 //
3467 // Generate OpLabel for Basic Block.
3468 //
3469 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003470 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003471 SPIRVInstList.push_back(Inst);
3472
David Neto6dcd4712017-06-23 11:06:47 -04003473 // OpVariable instructions must come first.
3474 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003475 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3476 // Allocating a pointer requires variable pointers.
3477 if (alloca->getAllocatedType()->isPointerTy()) {
3478 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3479 }
David Neto6dcd4712017-06-23 11:06:47 -04003480 GenerateInstruction(I);
3481 }
3482 }
3483
David Neto22f144c2017-06-12 14:26:21 -04003484 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003485 if (clspv::Option::HackInitializers()) {
3486 GenerateEntryPointInitialStores();
3487 }
David Neto22f144c2017-06-12 14:26:21 -04003488 }
3489
3490 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003491 if (!isa<AllocaInst>(I)) {
3492 GenerateInstruction(I);
3493 }
David Neto22f144c2017-06-12 14:26:21 -04003494 }
3495 }
3496}
3497
3498spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3499 const std::map<CmpInst::Predicate, spv::Op> Map = {
3500 {CmpInst::ICMP_EQ, spv::OpIEqual},
3501 {CmpInst::ICMP_NE, spv::OpINotEqual},
3502 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3503 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3504 {CmpInst::ICMP_ULT, spv::OpULessThan},
3505 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3506 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3507 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3508 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3509 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3510 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3511 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3512 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3513 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3514 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3515 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3516 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3517 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3518 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3519 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3520 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3521 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3522
3523 assert(0 != Map.count(I->getPredicate()));
3524
3525 return Map.at(I->getPredicate());
3526}
3527
3528spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3529 const std::map<unsigned, spv::Op> Map{
3530 {Instruction::Trunc, spv::OpUConvert},
3531 {Instruction::ZExt, spv::OpUConvert},
3532 {Instruction::SExt, spv::OpSConvert},
3533 {Instruction::FPToUI, spv::OpConvertFToU},
3534 {Instruction::FPToSI, spv::OpConvertFToS},
3535 {Instruction::UIToFP, spv::OpConvertUToF},
3536 {Instruction::SIToFP, spv::OpConvertSToF},
3537 {Instruction::FPTrunc, spv::OpFConvert},
3538 {Instruction::FPExt, spv::OpFConvert},
3539 {Instruction::BitCast, spv::OpBitcast}};
3540
3541 assert(0 != Map.count(I.getOpcode()));
3542
3543 return Map.at(I.getOpcode());
3544}
3545
3546spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003547 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003548 switch (I.getOpcode()) {
3549 default:
3550 break;
3551 case Instruction::Or:
3552 return spv::OpLogicalOr;
3553 case Instruction::And:
3554 return spv::OpLogicalAnd;
3555 case Instruction::Xor:
3556 return spv::OpLogicalNotEqual;
3557 }
3558 }
3559
alan-bakerb6b09dc2018-11-08 16:59:28 -05003560 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003561 {Instruction::Add, spv::OpIAdd},
3562 {Instruction::FAdd, spv::OpFAdd},
3563 {Instruction::Sub, spv::OpISub},
3564 {Instruction::FSub, spv::OpFSub},
3565 {Instruction::Mul, spv::OpIMul},
3566 {Instruction::FMul, spv::OpFMul},
3567 {Instruction::UDiv, spv::OpUDiv},
3568 {Instruction::SDiv, spv::OpSDiv},
3569 {Instruction::FDiv, spv::OpFDiv},
3570 {Instruction::URem, spv::OpUMod},
3571 {Instruction::SRem, spv::OpSRem},
3572 {Instruction::FRem, spv::OpFRem},
3573 {Instruction::Or, spv::OpBitwiseOr},
3574 {Instruction::Xor, spv::OpBitwiseXor},
3575 {Instruction::And, spv::OpBitwiseAnd},
3576 {Instruction::Shl, spv::OpShiftLeftLogical},
3577 {Instruction::LShr, spv::OpShiftRightLogical},
3578 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3579
3580 assert(0 != Map.count(I.getOpcode()));
3581
3582 return Map.at(I.getOpcode());
3583}
3584
3585void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3586 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3587 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003588 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3589 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3590
3591 // Register Instruction to ValueMap.
3592 if (0 == VMap[&I]) {
3593 VMap[&I] = nextID;
3594 }
3595
3596 switch (I.getOpcode()) {
3597 default: {
3598 if (Instruction::isCast(I.getOpcode())) {
3599 //
3600 // Generate SPIRV instructions for cast operators.
3601 //
3602
David Netod2de94a2017-08-28 17:27:47 -04003603 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003604 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003605 auto toI8 = Ty == Type::getInt8Ty(Context);
3606 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003607 // Handle zext, sext and uitofp with i1 type specially.
3608 if ((I.getOpcode() == Instruction::ZExt ||
3609 I.getOpcode() == Instruction::SExt ||
3610 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003611 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003612 //
3613 // Generate OpSelect.
3614 //
3615
3616 // Ops[0] = Result Type ID
3617 // Ops[1] = Condition ID
3618 // Ops[2] = True Constant ID
3619 // Ops[3] = False Constant ID
3620 SPIRVOperandList Ops;
3621
David Neto257c3892018-04-11 13:19:45 -04003622 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003623
David Neto22f144c2017-06-12 14:26:21 -04003624 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003625 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003626
3627 uint32_t TrueID = 0;
3628 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003629 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003630 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003631 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003632 } else {
3633 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3634 }
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003636
3637 uint32_t FalseID = 0;
3638 if (I.getOpcode() == Instruction::ZExt) {
3639 FalseID = VMap[Constant::getNullValue(I.getType())];
3640 } else if (I.getOpcode() == Instruction::SExt) {
3641 FalseID = VMap[Constant::getNullValue(I.getType())];
3642 } else {
3643 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3644 }
David Neto257c3892018-04-11 13:19:45 -04003645 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003646
David Neto87846742018-04-11 17:36:22 -04003647 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003648 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003649 } else if (!clspv::Option::Int8Support() &&
3650 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003651 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3652 // 8 bits.
3653 // Before:
3654 // %result = trunc i32 %a to i8
3655 // After
3656 // %result = OpBitwiseAnd %uint %a %uint_255
3657
3658 SPIRVOperandList Ops;
3659
David Neto257c3892018-04-11 13:19:45 -04003660 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003661
3662 Type *UintTy = Type::getInt32Ty(Context);
3663 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003664 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003665
David Neto87846742018-04-11 17:36:22 -04003666 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003667 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003668 } else {
3669 // Ops[0] = Result Type ID
3670 // Ops[1] = Source Value ID
3671 SPIRVOperandList Ops;
3672
David Neto257c3892018-04-11 13:19:45 -04003673 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003674
David Neto87846742018-04-11 17:36:22 -04003675 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003676 SPIRVInstList.push_back(Inst);
3677 }
3678 } else if (isa<BinaryOperator>(I)) {
3679 //
3680 // Generate SPIRV instructions for binary operators.
3681 //
3682
3683 // Handle xor with i1 type specially.
3684 if (I.getOpcode() == Instruction::Xor &&
3685 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003686 ((isa<ConstantInt>(I.getOperand(0)) &&
3687 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3688 (isa<ConstantInt>(I.getOperand(1)) &&
3689 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003690 //
3691 // Generate OpLogicalNot.
3692 //
3693 // Ops[0] = Result Type ID
3694 // Ops[1] = Operand
3695 SPIRVOperandList Ops;
3696
David Neto257c3892018-04-11 13:19:45 -04003697 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003698
3699 Value *CondV = I.getOperand(0);
3700 if (isa<Constant>(I.getOperand(0))) {
3701 CondV = I.getOperand(1);
3702 }
David Neto257c3892018-04-11 13:19:45 -04003703 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003704
David Neto87846742018-04-11 17:36:22 -04003705 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003706 SPIRVInstList.push_back(Inst);
3707 } else {
3708 // Ops[0] = Result Type ID
3709 // Ops[1] = Operand 0
3710 // Ops[2] = Operand 1
3711 SPIRVOperandList Ops;
3712
David Neto257c3892018-04-11 13:19:45 -04003713 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3714 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003715
David Neto87846742018-04-11 17:36:22 -04003716 auto *Inst =
3717 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003718 SPIRVInstList.push_back(Inst);
3719 }
3720 } else {
3721 I.print(errs());
3722 llvm_unreachable("Unsupported instruction???");
3723 }
3724 break;
3725 }
3726 case Instruction::GetElementPtr: {
3727 auto &GlobalConstArgSet = getGlobalConstArgSet();
3728
3729 //
3730 // Generate OpAccessChain.
3731 //
3732 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3733
3734 //
3735 // Generate OpAccessChain.
3736 //
3737
3738 // Ops[0] = Result Type ID
3739 // Ops[1] = Base ID
3740 // Ops[2] ... Ops[n] = Indexes ID
3741 SPIRVOperandList Ops;
3742
alan-bakerb6b09dc2018-11-08 16:59:28 -05003743 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003744 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3745 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3746 // Use pointer type with private address space for global constant.
3747 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003748 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003749 }
David Neto257c3892018-04-11 13:19:45 -04003750
3751 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003752
David Neto862b7d82018-06-14 18:48:37 -04003753 // Generate the base pointer.
3754 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003755
David Neto862b7d82018-06-14 18:48:37 -04003756 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003757
3758 //
3759 // Follows below rules for gep.
3760 //
David Neto862b7d82018-06-14 18:48:37 -04003761 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3762 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003763 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3764 // first index.
3765 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3766 // use gep's first index.
3767 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3768 // gep's first index.
3769 //
3770 spv::Op Opcode = spv::OpAccessChain;
3771 unsigned offset = 0;
3772 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003773 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003774 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003775 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003776 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003777 }
David Neto862b7d82018-06-14 18:48:37 -04003778 } else {
David Neto22f144c2017-06-12 14:26:21 -04003779 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003780 }
3781
3782 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003783 // Do we need to generate ArrayStride? Check against the GEP result type
3784 // rather than the pointer type of the base because when indexing into
3785 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3786 // for something else in the SPIR-V.
3787 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003788 auto address_space = ResultType->getAddressSpace();
3789 setVariablePointersCapabilities(address_space);
3790 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003791 case spv::StorageClassStorageBuffer:
3792 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003793 // Save the need to generate an ArrayStride decoration. But defer
3794 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003795 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003796 break;
3797 default:
3798 break;
David Neto1a1a0582017-07-07 12:01:44 -04003799 }
David Neto22f144c2017-06-12 14:26:21 -04003800 }
3801
3802 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003803 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003804 }
3805
David Neto87846742018-04-11 17:36:22 -04003806 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003807 SPIRVInstList.push_back(Inst);
3808 break;
3809 }
3810 case Instruction::ExtractValue: {
3811 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3812 // Ops[0] = Result Type ID
3813 // Ops[1] = Composite ID
3814 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3815 SPIRVOperandList Ops;
3816
David Neto257c3892018-04-11 13:19:45 -04003817 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003818
3819 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003820 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003821
3822 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003823 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003824 }
3825
David Neto87846742018-04-11 17:36:22 -04003826 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003827 SPIRVInstList.push_back(Inst);
3828 break;
3829 }
3830 case Instruction::InsertValue: {
3831 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3832 // Ops[0] = Result Type ID
3833 // Ops[1] = Object ID
3834 // Ops[2] = Composite ID
3835 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3836 SPIRVOperandList Ops;
3837
3838 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003839 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003840
3841 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003842 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003843
3844 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003846
3847 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003848 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003849 }
3850
David Neto87846742018-04-11 17:36:22 -04003851 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003852 SPIRVInstList.push_back(Inst);
3853 break;
3854 }
3855 case Instruction::Select: {
3856 //
3857 // Generate OpSelect.
3858 //
3859
3860 // Ops[0] = Result Type ID
3861 // Ops[1] = Condition ID
3862 // Ops[2] = True Constant ID
3863 // Ops[3] = False Constant ID
3864 SPIRVOperandList Ops;
3865
3866 // Find SPIRV instruction for parameter type.
3867 auto Ty = I.getType();
3868 if (Ty->isPointerTy()) {
3869 auto PointeeTy = Ty->getPointerElementType();
3870 if (PointeeTy->isStructTy() &&
3871 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3872 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003873 } else {
3874 // Selecting between pointers requires variable pointers.
3875 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3876 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3877 setVariablePointers(true);
3878 }
David Neto22f144c2017-06-12 14:26:21 -04003879 }
3880 }
3881
David Neto257c3892018-04-11 13:19:45 -04003882 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3883 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003884
David Neto87846742018-04-11 17:36:22 -04003885 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003886 SPIRVInstList.push_back(Inst);
3887 break;
3888 }
3889 case Instruction::ExtractElement: {
3890 // Handle <4 x i8> type manually.
3891 Type *CompositeTy = I.getOperand(0)->getType();
3892 if (is4xi8vec(CompositeTy)) {
3893 //
3894 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3895 // <4 x i8>.
3896 //
3897
3898 //
3899 // Generate OpShiftRightLogical
3900 //
3901 // Ops[0] = Result Type ID
3902 // Ops[1] = Operand 0
3903 // Ops[2] = Operand 1
3904 //
3905 SPIRVOperandList Ops;
3906
David Neto257c3892018-04-11 13:19:45 -04003907 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003908
3909 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003910 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003911
3912 uint32_t Op1ID = 0;
3913 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3914 // Handle constant index.
3915 uint64_t Idx = CI->getZExtValue();
3916 Value *ShiftAmount =
3917 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3918 Op1ID = VMap[ShiftAmount];
3919 } else {
3920 // Handle variable index.
3921 SPIRVOperandList TmpOps;
3922
David Neto257c3892018-04-11 13:19:45 -04003923 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3924 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003925
3926 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003927 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003928
3929 Op1ID = nextID;
3930
David Neto87846742018-04-11 17:36:22 -04003931 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003932 SPIRVInstList.push_back(TmpInst);
3933 }
David Neto257c3892018-04-11 13:19:45 -04003934 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 uint32_t ShiftID = nextID;
3937
David Neto87846742018-04-11 17:36:22 -04003938 auto *Inst =
3939 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003940 SPIRVInstList.push_back(Inst);
3941
3942 //
3943 // Generate OpBitwiseAnd
3944 //
3945 // Ops[0] = Result Type ID
3946 // Ops[1] = Operand 0
3947 // Ops[2] = Operand 1
3948 //
3949 Ops.clear();
3950
David Neto257c3892018-04-11 13:19:45 -04003951 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003952
3953 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003954 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003955
David Neto9b2d6252017-09-06 15:47:37 -04003956 // Reset mapping for this value to the result of the bitwise and.
3957 VMap[&I] = nextID;
3958
David Neto87846742018-04-11 17:36:22 -04003959 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003960 SPIRVInstList.push_back(Inst);
3961 break;
3962 }
3963
3964 // Ops[0] = Result Type ID
3965 // Ops[1] = Composite ID
3966 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3967 SPIRVOperandList Ops;
3968
David Neto257c3892018-04-11 13:19:45 -04003969 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003970
3971 spv::Op Opcode = spv::OpCompositeExtract;
3972 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003973 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003974 } else {
David Neto257c3892018-04-11 13:19:45 -04003975 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003976 Opcode = spv::OpVectorExtractDynamic;
3977 }
3978
David Neto87846742018-04-11 17:36:22 -04003979 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003980 SPIRVInstList.push_back(Inst);
3981 break;
3982 }
3983 case Instruction::InsertElement: {
3984 // Handle <4 x i8> type manually.
3985 Type *CompositeTy = I.getOperand(0)->getType();
3986 if (is4xi8vec(CompositeTy)) {
3987 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3988 uint32_t CstFFID = VMap[CstFF];
3989
3990 uint32_t ShiftAmountID = 0;
3991 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3992 // Handle constant index.
3993 uint64_t Idx = CI->getZExtValue();
3994 Value *ShiftAmount =
3995 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3996 ShiftAmountID = VMap[ShiftAmount];
3997 } else {
3998 // Handle variable index.
3999 SPIRVOperandList TmpOps;
4000
David Neto257c3892018-04-11 13:19:45 -04004001 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4002 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004003
4004 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004005 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004006
4007 ShiftAmountID = nextID;
4008
David Neto87846742018-04-11 17:36:22 -04004009 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004010 SPIRVInstList.push_back(TmpInst);
4011 }
4012
4013 //
4014 // Generate mask operations.
4015 //
4016
4017 // ShiftLeft mask according to index of insertelement.
4018 SPIRVOperandList Ops;
4019
David Neto257c3892018-04-11 13:19:45 -04004020 const uint32_t ResTyID = lookupType(CompositeTy);
4021 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004022
4023 uint32_t MaskID = nextID;
4024
David Neto87846742018-04-11 17:36:22 -04004025 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004026 SPIRVInstList.push_back(Inst);
4027
4028 // Inverse mask.
4029 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004030 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004031
4032 uint32_t InvMaskID = nextID;
4033
David Neto87846742018-04-11 17:36:22 -04004034 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004035 SPIRVInstList.push_back(Inst);
4036
4037 // Apply mask.
4038 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004039 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004040
4041 uint32_t OrgValID = nextID;
4042
David Neto87846742018-04-11 17:36:22 -04004043 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004044 SPIRVInstList.push_back(Inst);
4045
4046 // Create correct value according to index of insertelement.
4047 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004048 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4049 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004050
4051 uint32_t InsertValID = nextID;
4052
David Neto87846742018-04-11 17:36:22 -04004053 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004054 SPIRVInstList.push_back(Inst);
4055
4056 // Insert value to original value.
4057 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004058 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004059
David Netoa394f392017-08-26 20:45:29 -04004060 VMap[&I] = nextID;
4061
David Neto87846742018-04-11 17:36:22 -04004062 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004063 SPIRVInstList.push_back(Inst);
4064
4065 break;
4066 }
4067
David Neto22f144c2017-06-12 14:26:21 -04004068 SPIRVOperandList Ops;
4069
James Priced26efea2018-06-09 23:28:32 +01004070 // Ops[0] = Result Type ID
4071 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004072
4073 spv::Op Opcode = spv::OpCompositeInsert;
4074 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004075 const auto value = CI->getZExtValue();
4076 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004077 // Ops[1] = Object ID
4078 // Ops[2] = Composite ID
4079 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004080 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004081 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004082 } else {
James Priced26efea2018-06-09 23:28:32 +01004083 // Ops[1] = Composite ID
4084 // Ops[2] = Object ID
4085 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004086 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004087 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004088 Opcode = spv::OpVectorInsertDynamic;
4089 }
4090
David Neto87846742018-04-11 17:36:22 -04004091 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004092 SPIRVInstList.push_back(Inst);
4093 break;
4094 }
4095 case Instruction::ShuffleVector: {
4096 // Ops[0] = Result Type ID
4097 // Ops[1] = Vector 1 ID
4098 // Ops[2] = Vector 2 ID
4099 // Ops[3] ... Ops[n] = Components (Literal Number)
4100 SPIRVOperandList Ops;
4101
David Neto257c3892018-04-11 13:19:45 -04004102 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4103 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004104
4105 uint64_t NumElements = 0;
4106 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4107 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4108
4109 if (Cst->isNullValue()) {
4110 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004111 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004112 }
4113 } else if (const ConstantDataSequential *CDS =
4114 dyn_cast<ConstantDataSequential>(Cst)) {
4115 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4116 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004117 const auto value = CDS->getElementAsInteger(i);
4118 assert(value <= UINT32_MAX);
4119 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004120 }
4121 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4122 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4123 auto Op = CV->getOperand(i);
4124
4125 uint32_t literal = 0;
4126
4127 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4128 literal = static_cast<uint32_t>(CI->getZExtValue());
4129 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4130 literal = 0xFFFFFFFFu;
4131 } else {
4132 Op->print(errs());
4133 llvm_unreachable("Unsupported element in ConstantVector!");
4134 }
4135
David Neto257c3892018-04-11 13:19:45 -04004136 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004137 }
4138 } else {
4139 Cst->print(errs());
4140 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4141 }
4142 }
4143
David Neto87846742018-04-11 17:36:22 -04004144 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004145 SPIRVInstList.push_back(Inst);
4146 break;
4147 }
4148 case Instruction::ICmp:
4149 case Instruction::FCmp: {
4150 CmpInst *CmpI = cast<CmpInst>(&I);
4151
David Netod4ca2e62017-07-06 18:47:35 -04004152 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004153 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004154 if (isa<PointerType>(ArgTy)) {
4155 CmpI->print(errs());
4156 std::string name = I.getParent()->getParent()->getName();
4157 errs()
4158 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4159 << "in function " << name << "\n";
4160 llvm_unreachable("Pointer equality check is invalid");
4161 break;
4162 }
4163
David Neto257c3892018-04-11 13:19:45 -04004164 // Ops[0] = Result Type ID
4165 // Ops[1] = Operand 1 ID
4166 // Ops[2] = Operand 2 ID
4167 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004168
David Neto257c3892018-04-11 13:19:45 -04004169 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4170 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004171
4172 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004173 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004174 SPIRVInstList.push_back(Inst);
4175 break;
4176 }
4177 case Instruction::Br: {
4178 // Branch instrucion is deferred because it needs label's ID. Record slot's
4179 // location on SPIRVInstructionList.
4180 DeferredInsts.push_back(
4181 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4182 break;
4183 }
4184 case Instruction::Switch: {
4185 I.print(errs());
4186 llvm_unreachable("Unsupported instruction???");
4187 break;
4188 }
4189 case Instruction::IndirectBr: {
4190 I.print(errs());
4191 llvm_unreachable("Unsupported instruction???");
4192 break;
4193 }
4194 case Instruction::PHI: {
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(), nextID++));
4199 break;
4200 }
4201 case Instruction::Alloca: {
4202 //
4203 // Generate OpVariable.
4204 //
4205 // Ops[0] : Result Type ID
4206 // Ops[1] : Storage Class
4207 SPIRVOperandList Ops;
4208
David Neto257c3892018-04-11 13:19:45 -04004209 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004210
David Neto87846742018-04-11 17:36:22 -04004211 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004212 SPIRVInstList.push_back(Inst);
4213 break;
4214 }
4215 case Instruction::Load: {
4216 LoadInst *LD = cast<LoadInst>(&I);
4217 //
4218 // Generate OpLoad.
4219 //
alan-baker5b86ed72019-02-15 08:26:50 -05004220
4221 if (LD->getType()->isPointerTy()) {
4222 // Loading a pointer requires variable pointers.
4223 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4224 }
David Neto22f144c2017-06-12 14:26:21 -04004225
David Neto0a2f98d2017-09-15 19:38:40 -04004226 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004227 uint32_t PointerID = VMap[LD->getPointerOperand()];
4228
4229 // This is a hack to work around what looks like a driver bug.
4230 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004231 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4232 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004233 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004234 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004235 // Generate a bitwise-and of the original value with itself.
4236 // We should have been able to get away with just an OpCopyObject,
4237 // but we need something more complex to get past certain driver bugs.
4238 // This is ridiculous, but necessary.
4239 // TODO(dneto): Revisit this once drivers fix their bugs.
4240
4241 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004242 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4243 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004244
David Neto87846742018-04-11 17:36:22 -04004245 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004246 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004247 break;
4248 }
4249
4250 // This is the normal path. Generate a load.
4251
David Neto22f144c2017-06-12 14:26:21 -04004252 // Ops[0] = Result Type ID
4253 // Ops[1] = Pointer ID
4254 // Ops[2] ... Ops[n] = Optional Memory Access
4255 //
4256 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004257
David Neto22f144c2017-06-12 14:26:21 -04004258 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004259 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004260
David Neto87846742018-04-11 17:36:22 -04004261 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004262 SPIRVInstList.push_back(Inst);
4263 break;
4264 }
4265 case Instruction::Store: {
4266 StoreInst *ST = cast<StoreInst>(&I);
4267 //
4268 // Generate OpStore.
4269 //
4270
alan-baker5b86ed72019-02-15 08:26:50 -05004271 if (ST->getValueOperand()->getType()->isPointerTy()) {
4272 // Storing a pointer requires variable pointers.
4273 setVariablePointersCapabilities(
4274 ST->getValueOperand()->getType()->getPointerAddressSpace());
4275 }
4276
David Neto22f144c2017-06-12 14:26:21 -04004277 // Ops[0] = Pointer ID
4278 // Ops[1] = Object ID
4279 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4280 //
4281 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004282 SPIRVOperandList Ops;
4283 Ops << MkId(VMap[ST->getPointerOperand()])
4284 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004285
David Neto87846742018-04-11 17:36:22 -04004286 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004287 SPIRVInstList.push_back(Inst);
4288 break;
4289 }
4290 case Instruction::AtomicCmpXchg: {
4291 I.print(errs());
4292 llvm_unreachable("Unsupported instruction???");
4293 break;
4294 }
4295 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004296 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4297
4298 spv::Op opcode;
4299
4300 switch (AtomicRMW->getOperation()) {
4301 default:
4302 I.print(errs());
4303 llvm_unreachable("Unsupported instruction???");
4304 case llvm::AtomicRMWInst::Add:
4305 opcode = spv::OpAtomicIAdd;
4306 break;
4307 case llvm::AtomicRMWInst::Sub:
4308 opcode = spv::OpAtomicISub;
4309 break;
4310 case llvm::AtomicRMWInst::Xchg:
4311 opcode = spv::OpAtomicExchange;
4312 break;
4313 case llvm::AtomicRMWInst::Min:
4314 opcode = spv::OpAtomicSMin;
4315 break;
4316 case llvm::AtomicRMWInst::Max:
4317 opcode = spv::OpAtomicSMax;
4318 break;
4319 case llvm::AtomicRMWInst::UMin:
4320 opcode = spv::OpAtomicUMin;
4321 break;
4322 case llvm::AtomicRMWInst::UMax:
4323 opcode = spv::OpAtomicUMax;
4324 break;
4325 case llvm::AtomicRMWInst::And:
4326 opcode = spv::OpAtomicAnd;
4327 break;
4328 case llvm::AtomicRMWInst::Or:
4329 opcode = spv::OpAtomicOr;
4330 break;
4331 case llvm::AtomicRMWInst::Xor:
4332 opcode = spv::OpAtomicXor;
4333 break;
4334 }
4335
4336 //
4337 // Generate OpAtomic*.
4338 //
4339 SPIRVOperandList Ops;
4340
David Neto257c3892018-04-11 13:19:45 -04004341 Ops << MkId(lookupType(I.getType()))
4342 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004343
4344 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004345 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004346 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004347
4348 const auto ConstantMemorySemantics = ConstantInt::get(
4349 IntTy, spv::MemorySemanticsUniformMemoryMask |
4350 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004351 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004352
David Neto257c3892018-04-11 13:19:45 -04004353 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004354
4355 VMap[&I] = nextID;
4356
David Neto87846742018-04-11 17:36:22 -04004357 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004358 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004359 break;
4360 }
4361 case Instruction::Fence: {
4362 I.print(errs());
4363 llvm_unreachable("Unsupported instruction???");
4364 break;
4365 }
4366 case Instruction::Call: {
4367 CallInst *Call = dyn_cast<CallInst>(&I);
4368 Function *Callee = Call->getCalledFunction();
4369
Alan Baker202c8c72018-08-13 13:47:44 -04004370 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004371 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4372 // Generate an OpLoad
4373 SPIRVOperandList Ops;
4374 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004375
David Neto862b7d82018-06-14 18:48:37 -04004376 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4377 << MkId(ResourceVarDeferredLoadCalls[Call]);
4378
4379 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4380 SPIRVInstList.push_back(Inst);
4381 VMap[Call] = load_id;
4382 break;
4383
4384 } else {
4385 // This maps to an OpVariable we've already generated.
4386 // No code is generated for the call.
4387 }
4388 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004389 } else if (Callee->getName().startswith(
4390 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004391 // Don't codegen an instruction here, but instead map this call directly
4392 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004393 int spec_id = static_cast<int>(
4394 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004395 const auto &info = LocalSpecIdInfoMap[spec_id];
4396 VMap[Call] = info.variable_id;
4397 break;
David Neto862b7d82018-06-14 18:48:37 -04004398 }
4399
4400 // Sampler initializers become a load of the corresponding sampler.
4401
4402 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4403 // Map this to a load from the variable.
4404 const auto index_into_sampler_map =
4405 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4406
4407 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004408 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004409 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004410
David Neto257c3892018-04-11 13:19:45 -04004411 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004412 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4413 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004414
David Neto862b7d82018-06-14 18:48:37 -04004415 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004416 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004417 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004418 break;
4419 }
4420
Kévin Petit349c9502019-03-28 17:24:14 +00004421 // Handle SPIR-V intrinsics
4422 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4423 .Case("spirv.smul_extended", spv::OpSMulExtended)
4424 .Case("spirv.umul_extended", spv::OpUMulExtended)
4425 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4426 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4427 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4428 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4429 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4430 .Case("spirv.atomic_compare_exchange", spv::OpAtomicCompareExchange)
4431 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4432 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4433 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4434 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4435 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4436 .Case("spirv.atomic_or", spv::OpAtomicOr)
4437 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4438 .Case("__spirv_control_barrier", spv::OpControlBarrier)
4439 .Case("__spirv_memory_barrier", spv::OpMemoryBarrier)
Kévin Petitfd6c24f2019-04-03 15:30:59 +01004440 .StartsWith("spirv.store_null", spv::OpStore)
Kévin Petit349c9502019-03-28 17:24:14 +00004441 .StartsWith("__spirv_isinf", spv::OpIsInf)
4442 .StartsWith("__spirv_isnan", spv::OpIsNan)
4443 .StartsWith("__spirv_allDv", spv::OpAll)
4444 .StartsWith("__spirv_anyDv", spv::OpAny)
4445 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004446
Kévin Petit349c9502019-03-28 17:24:14 +00004447 if (opcode != spv::OpNop) {
4448
David Neto22f144c2017-06-12 14:26:21 -04004449 SPIRVOperandList Ops;
4450
Kévin Petit349c9502019-03-28 17:24:14 +00004451 if (!I.getType()->isVoidTy()) {
4452 Ops << MkId(lookupType(I.getType()));
4453 }
David Neto22f144c2017-06-12 14:26:21 -04004454
4455 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004456 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004457 }
4458
Kévin Petit349c9502019-03-28 17:24:14 +00004459 if (!I.getType()->isVoidTy()) {
4460 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004461 }
4462
Kévin Petit349c9502019-03-28 17:24:14 +00004463 SPIRVInstruction *Inst;
4464 if (!I.getType()->isVoidTy()) {
4465 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4466 } else {
4467 Inst = new SPIRVInstruction(opcode, Ops);
4468 }
Kévin Petit8a560882019-03-21 15:24:34 +00004469 SPIRVInstList.push_back(Inst);
4470 break;
4471 }
4472
David Neto22f144c2017-06-12 14:26:21 -04004473 if (Callee->getName().startswith("_Z3dot")) {
4474 // If the argument is a vector type, generate OpDot
4475 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4476 //
4477 // Generate OpDot.
4478 //
4479 SPIRVOperandList Ops;
4480
David Neto257c3892018-04-11 13:19:45 -04004481 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004482
4483 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004484 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004485 }
4486
4487 VMap[&I] = nextID;
4488
David Neto87846742018-04-11 17:36:22 -04004489 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004490 SPIRVInstList.push_back(Inst);
4491 } else {
4492 //
4493 // Generate OpFMul.
4494 //
4495 SPIRVOperandList Ops;
4496
David Neto257c3892018-04-11 13:19:45 -04004497 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004498
4499 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004500 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004501 }
4502
4503 VMap[&I] = nextID;
4504
David Neto87846742018-04-11 17:36:22 -04004505 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004506 SPIRVInstList.push_back(Inst);
4507 }
4508 break;
4509 }
4510
David Neto8505ebf2017-10-13 18:50:50 -04004511 if (Callee->getName().startswith("_Z4fmod")) {
4512 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4513 // The sign for a non-zero result is taken from x.
4514 // (Try an example.)
4515 // So translate to OpFRem
4516
4517 SPIRVOperandList Ops;
4518
David Neto257c3892018-04-11 13:19:45 -04004519 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004520
4521 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004522 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004523 }
4524
4525 VMap[&I] = nextID;
4526
David Neto87846742018-04-11 17:36:22 -04004527 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004528 SPIRVInstList.push_back(Inst);
4529 break;
4530 }
4531
David Neto22f144c2017-06-12 14:26:21 -04004532 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4533 if (Callee->getName().startswith("spirv.copy_memory")) {
4534 //
4535 // Generate OpCopyMemory.
4536 //
4537
4538 // Ops[0] = Dst ID
4539 // Ops[1] = Src ID
4540 // Ops[2] = Memory Access
4541 // Ops[3] = Alignment
4542
4543 auto IsVolatile =
4544 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4545
4546 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4547 : spv::MemoryAccessMaskNone;
4548
4549 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4550
4551 auto Alignment =
4552 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4553
David Neto257c3892018-04-11 13:19:45 -04004554 SPIRVOperandList Ops;
4555 Ops << MkId(VMap[Call->getArgOperand(0)])
4556 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4557 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004558
David Neto87846742018-04-11 17:36:22 -04004559 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004560
4561 SPIRVInstList.push_back(Inst);
4562
4563 break;
4564 }
4565
David Neto22f144c2017-06-12 14:26:21 -04004566 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4567 // Additionally, OpTypeSampledImage is generated.
4568 if (Callee->getName().equals(
4569 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4570 Callee->getName().equals(
4571 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4572 //
4573 // Generate OpSampledImage.
4574 //
4575 // Ops[0] = Result Type ID
4576 // Ops[1] = Image ID
4577 // Ops[2] = Sampler ID
4578 //
4579 SPIRVOperandList Ops;
4580
4581 Value *Image = Call->getArgOperand(0);
4582 Value *Sampler = Call->getArgOperand(1);
4583 Value *Coordinate = Call->getArgOperand(2);
4584
4585 TypeMapType &OpImageTypeMap = getImageTypeMap();
4586 Type *ImageTy = Image->getType()->getPointerElementType();
4587 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004588 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004589 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004590
4591 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004592
4593 uint32_t SampledImageID = nextID;
4594
David Neto87846742018-04-11 17:36:22 -04004595 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004596 SPIRVInstList.push_back(Inst);
4597
4598 //
4599 // Generate OpImageSampleExplicitLod.
4600 //
4601 // Ops[0] = Result Type ID
4602 // Ops[1] = Sampled Image ID
4603 // Ops[2] = Coordinate ID
4604 // Ops[3] = Image Operands Type ID
4605 // Ops[4] ... Ops[n] = Operands ID
4606 //
4607 Ops.clear();
4608
David Neto257c3892018-04-11 13:19:45 -04004609 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4610 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004611
4612 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004613 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004614
4615 VMap[&I] = nextID;
4616
David Neto87846742018-04-11 17:36:22 -04004617 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004618 SPIRVInstList.push_back(Inst);
4619 break;
4620 }
4621
4622 // write_imagef is mapped to OpImageWrite.
4623 if (Callee->getName().equals(
4624 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4625 Callee->getName().equals(
4626 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4627 //
4628 // Generate OpImageWrite.
4629 //
4630 // Ops[0] = Image ID
4631 // Ops[1] = Coordinate ID
4632 // Ops[2] = Texel ID
4633 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4634 // Ops[4] ... Ops[n] = (Optional) Operands ID
4635 //
4636 SPIRVOperandList Ops;
4637
4638 Value *Image = Call->getArgOperand(0);
4639 Value *Coordinate = Call->getArgOperand(1);
4640 Value *Texel = Call->getArgOperand(2);
4641
4642 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004643 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004644 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004645 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004646
David Neto87846742018-04-11 17:36:22 -04004647 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004648 SPIRVInstList.push_back(Inst);
4649 break;
4650 }
4651
David Neto5c22a252018-03-15 16:07:41 -04004652 // get_image_width is mapped to OpImageQuerySize
4653 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4654 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4655 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4656 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4657 //
4658 // Generate OpImageQuerySize, then pull out the right component.
4659 // Assume 2D image for now.
4660 //
4661 // Ops[0] = Image ID
4662 //
4663 // %sizes = OpImageQuerySizes %uint2 %im
4664 // %result = OpCompositeExtract %uint %sizes 0-or-1
4665 SPIRVOperandList Ops;
4666
4667 // Implement:
4668 // %sizes = OpImageQuerySizes %uint2 %im
4669 uint32_t SizesTypeID =
4670 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004671 Value *Image = Call->getArgOperand(0);
4672 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004673 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004674
4675 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004676 auto *QueryInst =
4677 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004678 SPIRVInstList.push_back(QueryInst);
4679
4680 // Reset value map entry since we generated an intermediate instruction.
4681 VMap[&I] = nextID;
4682
4683 // Implement:
4684 // %result = OpCompositeExtract %uint %sizes 0-or-1
4685 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004686 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004687
4688 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004689 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004690
David Neto87846742018-04-11 17:36:22 -04004691 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004692 SPIRVInstList.push_back(Inst);
4693 break;
4694 }
4695
David Neto22f144c2017-06-12 14:26:21 -04004696 // Call instrucion is deferred because it needs function's ID. Record
4697 // slot's location on SPIRVInstructionList.
4698 DeferredInsts.push_back(
4699 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4700
David Neto3fbb4072017-10-16 11:28:14 -04004701 // Check whether the implementation of this call uses an extended
4702 // instruction plus one more value-producing instruction. If so, then
4703 // reserve the id for the extra value-producing slot.
4704 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4705 if (EInst != kGlslExtInstBad) {
4706 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004707 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004708 VMap[&I] = nextID;
4709 nextID++;
4710 }
4711 break;
4712 }
4713 case Instruction::Ret: {
4714 unsigned NumOps = I.getNumOperands();
4715 if (NumOps == 0) {
4716 //
4717 // Generate OpReturn.
4718 //
David Neto87846742018-04-11 17:36:22 -04004719 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004720 } else {
4721 //
4722 // Generate OpReturnValue.
4723 //
4724
4725 // Ops[0] = Return Value ID
4726 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004727
4728 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004729
David Neto87846742018-04-11 17:36:22 -04004730 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004731 SPIRVInstList.push_back(Inst);
4732 break;
4733 }
4734 break;
4735 }
4736 }
4737}
4738
4739void SPIRVProducerPass::GenerateFuncEpilogue() {
4740 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4741
4742 //
4743 // Generate OpFunctionEnd
4744 //
4745
David Neto87846742018-04-11 17:36:22 -04004746 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004747 SPIRVInstList.push_back(Inst);
4748}
4749
4750bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004751 // Don't specialize <4 x i8> if i8 is generally supported.
4752 if (clspv::Option::Int8Support())
4753 return false;
4754
David Neto22f144c2017-06-12 14:26:21 -04004755 LLVMContext &Context = Ty->getContext();
4756 if (Ty->isVectorTy()) {
4757 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4758 Ty->getVectorNumElements() == 4) {
4759 return true;
4760 }
4761 }
4762
4763 return false;
4764}
4765
David Neto257c3892018-04-11 13:19:45 -04004766uint32_t SPIRVProducerPass::GetI32Zero() {
4767 if (0 == constant_i32_zero_id_) {
4768 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4769 "defined in the SPIR-V module");
4770 }
4771 return constant_i32_zero_id_;
4772}
4773
David Neto22f144c2017-06-12 14:26:21 -04004774void SPIRVProducerPass::HandleDeferredInstruction() {
4775 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4776 ValueMapType &VMap = getValueMap();
4777 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4778
4779 for (auto DeferredInst = DeferredInsts.rbegin();
4780 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4781 Value *Inst = std::get<0>(*DeferredInst);
4782 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4783 if (InsertPoint != SPIRVInstList.end()) {
4784 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4785 ++InsertPoint;
4786 }
4787 }
4788
4789 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4790 // Check whether basic block, which has this branch instruction, is loop
4791 // header or not. If it is loop header, generate OpLoopMerge and
4792 // OpBranchConditional.
4793 Function *Func = Br->getParent()->getParent();
4794 DominatorTree &DT =
4795 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4796 const LoopInfo &LI =
4797 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4798
4799 BasicBlock *BrBB = Br->getParent();
4800 if (LI.isLoopHeader(BrBB)) {
4801 Value *ContinueBB = nullptr;
4802 Value *MergeBB = nullptr;
4803
4804 Loop *L = LI.getLoopFor(BrBB);
4805 MergeBB = L->getExitBlock();
4806 if (!MergeBB) {
4807 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4808 // has regions with single entry/exit. As a result, loop should not
4809 // have multiple exits.
4810 llvm_unreachable("Loop has multiple exits???");
4811 }
4812
4813 if (L->isLoopLatch(BrBB)) {
4814 ContinueBB = BrBB;
4815 } else {
4816 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4817 // block.
4818 BasicBlock *Header = L->getHeader();
4819 BasicBlock *Latch = L->getLoopLatch();
4820 for (BasicBlock *BB : L->blocks()) {
4821 if (BB == Header) {
4822 continue;
4823 }
4824
4825 // Check whether block dominates block with back-edge.
4826 if (DT.dominates(BB, Latch)) {
4827 ContinueBB = BB;
4828 }
4829 }
4830
4831 if (!ContinueBB) {
4832 llvm_unreachable("Wrong continue block from loop");
4833 }
4834 }
4835
4836 //
4837 // Generate OpLoopMerge.
4838 //
4839 // Ops[0] = Merge Block ID
4840 // Ops[1] = Continue Target ID
4841 // Ops[2] = Selection Control
4842 SPIRVOperandList Ops;
4843
4844 // StructurizeCFG pass already manipulated CFG. Just use false block of
4845 // branch instruction as merge block.
4846 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004847 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004848 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4849 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004850
David Neto87846742018-04-11 17:36:22 -04004851 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004852 SPIRVInstList.insert(InsertPoint, MergeInst);
4853
4854 } else if (Br->isConditional()) {
4855 bool HasBackEdge = false;
4856
4857 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4858 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4859 HasBackEdge = true;
4860 }
4861 }
4862 if (!HasBackEdge) {
4863 //
4864 // Generate OpSelectionMerge.
4865 //
4866 // Ops[0] = Merge Block ID
4867 // Ops[1] = Selection Control
4868 SPIRVOperandList Ops;
4869
4870 // StructurizeCFG pass already manipulated CFG. Just use false block
4871 // of branch instruction as merge block.
4872 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004873 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004874
David Neto87846742018-04-11 17:36:22 -04004875 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004876 SPIRVInstList.insert(InsertPoint, MergeInst);
4877 }
4878 }
4879
4880 if (Br->isConditional()) {
4881 //
4882 // Generate OpBranchConditional.
4883 //
4884 // Ops[0] = Condition ID
4885 // Ops[1] = True Label ID
4886 // Ops[2] = False Label ID
4887 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4888 SPIRVOperandList Ops;
4889
4890 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004891 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004892 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004893
4894 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004895
David Neto87846742018-04-11 17:36:22 -04004896 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004897 SPIRVInstList.insert(InsertPoint, BrInst);
4898 } else {
4899 //
4900 // Generate OpBranch.
4901 //
4902 // Ops[0] = Target Label ID
4903 SPIRVOperandList Ops;
4904
4905 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004906 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004907
David Neto87846742018-04-11 17:36:22 -04004908 SPIRVInstList.insert(InsertPoint,
4909 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004910 }
4911 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004912 if (PHI->getType()->isPointerTy()) {
4913 // OpPhi on pointers requires variable pointers.
4914 setVariablePointersCapabilities(
4915 PHI->getType()->getPointerAddressSpace());
4916 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4917 setVariablePointers(true);
4918 }
4919 }
4920
David Neto22f144c2017-06-12 14:26:21 -04004921 //
4922 // Generate OpPhi.
4923 //
4924 // Ops[0] = Result Type ID
4925 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4926 SPIRVOperandList Ops;
4927
David Neto257c3892018-04-11 13:19:45 -04004928 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004929
David Neto22f144c2017-06-12 14:26:21 -04004930 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4931 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004932 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004933 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004934 }
4935
4936 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004937 InsertPoint,
4938 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004939 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4940 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004941 auto callee_name = Callee->getName();
4942 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004943
4944 if (EInst) {
4945 uint32_t &ExtInstImportID = getOpExtInstImportID();
4946
4947 //
4948 // Generate OpExtInst.
4949 //
4950
4951 // Ops[0] = Result Type ID
4952 // Ops[1] = Set ID (OpExtInstImport ID)
4953 // Ops[2] = Instruction Number (Literal Number)
4954 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4955 SPIRVOperandList Ops;
4956
David Neto862b7d82018-06-14 18:48:37 -04004957 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4958 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004959
David Neto22f144c2017-06-12 14:26:21 -04004960 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4961 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004962 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004963 }
4964
David Neto87846742018-04-11 17:36:22 -04004965 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4966 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004967 SPIRVInstList.insert(InsertPoint, ExtInst);
4968
David Neto3fbb4072017-10-16 11:28:14 -04004969 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4970 if (IndirectExtInst != kGlslExtInstBad) {
4971 // Generate one more instruction that uses the result of the extended
4972 // instruction. Its result id is one more than the id of the
4973 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004974 LLVMContext &Context =
4975 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004976
David Neto3fbb4072017-10-16 11:28:14 -04004977 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4978 &VMap, &SPIRVInstList, &InsertPoint](
4979 spv::Op opcode, Constant *constant) {
4980 //
4981 // Generate instruction like:
4982 // result = opcode constant <extinst-result>
4983 //
4984 // Ops[0] = Result Type ID
4985 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4986 // Ops[2] = Operand 1 ;; the result of the extended instruction
4987 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004988
David Neto3fbb4072017-10-16 11:28:14 -04004989 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004990 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004991
4992 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4993 constant = ConstantVector::getSplat(
4994 static_cast<unsigned>(vectorTy->getNumElements()), constant);
4995 }
David Neto257c3892018-04-11 13:19:45 -04004996 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04004997
4998 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004999 InsertPoint, new SPIRVInstruction(
5000 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005001 };
5002
5003 switch (IndirectExtInst) {
5004 case glsl::ExtInstFindUMsb: // Implementing clz
5005 generate_extra_inst(
5006 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5007 break;
5008 case glsl::ExtInstAcos: // Implementing acospi
5009 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005010 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005011 case glsl::ExtInstAtan2: // Implementing atan2pi
5012 generate_extra_inst(
5013 spv::OpFMul,
5014 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5015 break;
5016
5017 default:
5018 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005019 }
David Neto22f144c2017-06-12 14:26:21 -04005020 }
David Neto3fbb4072017-10-16 11:28:14 -04005021
alan-bakerb39c8262019-03-08 14:03:37 -05005022 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04005023 //
5024 // Generate OpBitCount
5025 //
5026 // Ops[0] = Result Type ID
5027 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005028 SPIRVOperandList Ops;
5029 Ops << MkId(lookupType(Call->getType()))
5030 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005031
5032 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005033 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005034 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005035
David Neto862b7d82018-06-14 18:48:37 -04005036 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005037
5038 // Generate an OpCompositeConstruct
5039 SPIRVOperandList Ops;
5040
5041 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005042 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005043
5044 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005045 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005046 }
5047
5048 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005049 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5050 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005051
Alan Baker202c8c72018-08-13 13:47:44 -04005052 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5053
5054 // We have already mapped the call's result value to an ID.
5055 // Don't generate any code now.
5056
5057 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005058
5059 // We have already mapped the call's result value to an ID.
5060 // Don't generate any code now.
5061
David Neto22f144c2017-06-12 14:26:21 -04005062 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005063 if (Call->getType()->isPointerTy()) {
5064 // Functions returning pointers require variable pointers.
5065 setVariablePointersCapabilities(
5066 Call->getType()->getPointerAddressSpace());
5067 }
5068
David Neto22f144c2017-06-12 14:26:21 -04005069 //
5070 // Generate OpFunctionCall.
5071 //
5072
5073 // Ops[0] = Result Type ID
5074 // Ops[1] = Callee Function ID
5075 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5076 SPIRVOperandList Ops;
5077
David Neto862b7d82018-06-14 18:48:37 -04005078 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005079
5080 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005081 if (CalleeID == 0) {
5082 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005083 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005084 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5085 // causes an infinite loop. Instead, go ahead and generate
5086 // the bad function call. A validator will catch the 0-Id.
5087 // llvm_unreachable("Can't translate function call");
5088 }
David Neto22f144c2017-06-12 14:26:21 -04005089
David Neto257c3892018-04-11 13:19:45 -04005090 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005091
David Neto22f144c2017-06-12 14:26:21 -04005092 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5093 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005094 auto *operand = Call->getOperand(i);
5095 if (operand->getType()->isPointerTy()) {
5096 auto sc =
5097 GetStorageClass(operand->getType()->getPointerAddressSpace());
5098 if (sc == spv::StorageClassStorageBuffer) {
5099 // Passing SSBO by reference requires variable pointers storage
5100 // buffer.
5101 setVariablePointersStorageBuffer(true);
5102 } else if (sc == spv::StorageClassWorkgroup) {
5103 // Workgroup references require variable pointers if they are not
5104 // memory object declarations.
5105 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5106 // Workgroup accessor represents a variable reference.
5107 if (!operand_call->getCalledFunction()->getName().startswith(
5108 clspv::WorkgroupAccessorFunction()))
5109 setVariablePointers(true);
5110 } else {
5111 // Arguments are function parameters.
5112 if (!isa<Argument>(operand))
5113 setVariablePointers(true);
5114 }
5115 }
5116 }
5117 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005118 }
5119
David Neto87846742018-04-11 17:36:22 -04005120 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5121 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005122 SPIRVInstList.insert(InsertPoint, CallInst);
5123 }
5124 }
5125 }
5126}
5127
David Neto1a1a0582017-07-07 12:01:44 -04005128void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005129 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005130 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005131 }
David Neto1a1a0582017-07-07 12:01:44 -04005132
5133 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005134
5135 // Find an iterator pointing just past the last decoration.
5136 bool seen_decorations = false;
5137 auto DecoInsertPoint =
5138 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5139 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5140 const bool is_decoration =
5141 Inst->getOpcode() == spv::OpDecorate ||
5142 Inst->getOpcode() == spv::OpMemberDecorate;
5143 if (is_decoration) {
5144 seen_decorations = true;
5145 return false;
5146 } else {
5147 return seen_decorations;
5148 }
5149 });
5150
David Netoc6f3ab22018-04-06 18:02:31 -04005151 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5152 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005153 for (auto *type : getTypesNeedingArrayStride()) {
5154 Type *elemTy = nullptr;
5155 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5156 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005157 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005158 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005159 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005160 elemTy = seqTy->getSequentialElementType();
5161 } else {
5162 errs() << "Unhandled strided type " << *type << "\n";
5163 llvm_unreachable("Unhandled strided type");
5164 }
David Neto1a1a0582017-07-07 12:01:44 -04005165
5166 // Ops[0] = Target ID
5167 // Ops[1] = Decoration (ArrayStride)
5168 // Ops[2] = Stride number (Literal Number)
5169 SPIRVOperandList Ops;
5170
David Neto85082642018-03-24 06:55:20 -07005171 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005172 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005173
5174 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5175 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005176
David Neto87846742018-04-11 17:36:22 -04005177 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005178 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5179 }
David Netoc6f3ab22018-04-06 18:02:31 -04005180
5181 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005182 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5183 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005184 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005185 SPIRVOperandList Ops;
5186 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5187 << MkNum(arg_info.spec_id);
5188 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005189 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005190 }
David Neto1a1a0582017-07-07 12:01:44 -04005191}
5192
David Neto22f144c2017-06-12 14:26:21 -04005193glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5194 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005195 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5196 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5197 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5198 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005199 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5200 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5201 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5202 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005203 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5204 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5205 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5206 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005207 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5208 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5209 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5210 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005211 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5212 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5213 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5214 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5215 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5216 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5217 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5218 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005219 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5220 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5221 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5222 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5223 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5224 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5225 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5226 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005227 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5228 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5229 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5230 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5231 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5232 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5233 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5234 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005235 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5236 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5237 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5238 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5239 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5240 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5241 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5242 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005243 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5244 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5245 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5246 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005247 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5248 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5249 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5250 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5251 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5252 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5253 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5254 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005255 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5256 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5257 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5258 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5259 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5260 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5261 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5262 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005263 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5264 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5265 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5266 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5267 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5268 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5269 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5270 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005271 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5272 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5273 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5274 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5275 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5276 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5277 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5278 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005279 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5280 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5281 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5282 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5283 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005284 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5285 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5286 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5287 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5288 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5289 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5290 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5291 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005292 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5293 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5294 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5295 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5296 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5297 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5298 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5299 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005300 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5301 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5302 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5303 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5304 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5305 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5306 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5307 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005308 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5309 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5310 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5311 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5312 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5313 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5314 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5315 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005316 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5317 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5318 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5319 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5320 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5321 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5322 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5323 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5324 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5325 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5326 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5327 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5328 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5329 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5330 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5331 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5332 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5333 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5334 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5335 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5336 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5337 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5338 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5339 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5340 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5341 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5342 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5343 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5344 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5345 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5346 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5347 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5348 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5349 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5350 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5351 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5352 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5353 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5354 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5355 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5356 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005357 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005358 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5359 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5360 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5361 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5362 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5363 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5364 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5365 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5366 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5367 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5368 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5369 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5370 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5371 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5372 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5373 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5374 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005375 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005376 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005377 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005378 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005379 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005380 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5381 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005382 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005383 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5384 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5385 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005386 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5387 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5388 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5389 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005390 .Default(kGlslExtInstBad);
5391}
5392
5393glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5394 // Check indirect cases.
5395 return StringSwitch<glsl::ExtInst>(Name)
5396 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5397 // Use exact match on float arg because these need a multiply
5398 // of a constant of the right floating point type.
5399 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5400 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5401 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5402 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5403 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5404 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5405 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5406 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005407 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5408 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5409 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5410 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005411 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5412 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5413 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5414 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5415 .Default(kGlslExtInstBad);
5416}
5417
alan-bakerb6b09dc2018-11-08 16:59:28 -05005418glsl::ExtInst
5419SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005420 auto direct = getExtInstEnum(Name);
5421 if (direct != kGlslExtInstBad)
5422 return direct;
5423 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005424}
5425
5426void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5427 out << "%" << Inst->getResultID();
5428}
5429
5430void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5431 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5432 out << "\t" << spv::getOpName(Opcode);
5433}
5434
5435void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5436 SPIRVOperandType OpTy = Op->getType();
5437 switch (OpTy) {
5438 default: {
5439 llvm_unreachable("Unsupported SPIRV Operand Type???");
5440 break;
5441 }
5442 case SPIRVOperandType::NUMBERID: {
5443 out << "%" << Op->getNumID();
5444 break;
5445 }
5446 case SPIRVOperandType::LITERAL_STRING: {
5447 out << "\"" << Op->getLiteralStr() << "\"";
5448 break;
5449 }
5450 case SPIRVOperandType::LITERAL_INTEGER: {
5451 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005452 auto Words = Op->getLiteralNum();
5453 auto NumWords = Words.size();
5454
5455 if (NumWords == 1) {
5456 out << Words[0];
5457 } else if (NumWords == 2) {
5458 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5459 out << Val;
5460 } else {
5461 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005462 }
5463 break;
5464 }
5465 case SPIRVOperandType::LITERAL_FLOAT: {
5466 // TODO: Handle LiteralNum carefully.
5467 for (auto Word : Op->getLiteralNum()) {
5468 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5469 SmallString<8> Str;
5470 APF.toString(Str, 6, 2);
5471 out << Str;
5472 }
5473 break;
5474 }
5475 }
5476}
5477
5478void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5479 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5480 out << spv::getCapabilityName(Cap);
5481}
5482
5483void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5484 auto LiteralNum = Op->getLiteralNum();
5485 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5486 out << glsl::getExtInstName(Ext);
5487}
5488
5489void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5490 spv::AddressingModel AddrModel =
5491 static_cast<spv::AddressingModel>(Op->getNumID());
5492 out << spv::getAddressingModelName(AddrModel);
5493}
5494
5495void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5496 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5497 out << spv::getMemoryModelName(MemModel);
5498}
5499
5500void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5501 spv::ExecutionModel ExecModel =
5502 static_cast<spv::ExecutionModel>(Op->getNumID());
5503 out << spv::getExecutionModelName(ExecModel);
5504}
5505
5506void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5507 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5508 out << spv::getExecutionModeName(ExecMode);
5509}
5510
5511void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005512 spv::SourceLanguage SourceLang =
5513 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005514 out << spv::getSourceLanguageName(SourceLang);
5515}
5516
5517void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5518 spv::FunctionControlMask FuncCtrl =
5519 static_cast<spv::FunctionControlMask>(Op->getNumID());
5520 out << spv::getFunctionControlName(FuncCtrl);
5521}
5522
5523void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5524 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5525 out << getStorageClassName(StClass);
5526}
5527
5528void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5529 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5530 out << getDecorationName(Deco);
5531}
5532
5533void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5534 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5535 out << getBuiltInName(BIn);
5536}
5537
5538void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5539 spv::SelectionControlMask BIn =
5540 static_cast<spv::SelectionControlMask>(Op->getNumID());
5541 out << getSelectionControlName(BIn);
5542}
5543
5544void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5545 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5546 out << getLoopControlName(BIn);
5547}
5548
5549void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5550 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5551 out << getDimName(DIM);
5552}
5553
5554void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5555 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5556 out << getImageFormatName(Format);
5557}
5558
5559void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5560 out << spv::getMemoryAccessName(
5561 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5562}
5563
5564void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5565 auto LiteralNum = Op->getLiteralNum();
5566 spv::ImageOperandsMask Type =
5567 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5568 out << getImageOperandsName(Type);
5569}
5570
5571void SPIRVProducerPass::WriteSPIRVAssembly() {
5572 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5573
5574 for (auto Inst : SPIRVInstList) {
5575 SPIRVOperandList Ops = Inst->getOperands();
5576 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5577
5578 switch (Opcode) {
5579 default: {
5580 llvm_unreachable("Unsupported SPIRV instruction");
5581 break;
5582 }
5583 case spv::OpCapability: {
5584 // Ops[0] = Capability
5585 PrintOpcode(Inst);
5586 out << " ";
5587 PrintCapability(Ops[0]);
5588 out << "\n";
5589 break;
5590 }
5591 case spv::OpMemoryModel: {
5592 // Ops[0] = Addressing Model
5593 // Ops[1] = Memory Model
5594 PrintOpcode(Inst);
5595 out << " ";
5596 PrintAddrModel(Ops[0]);
5597 out << " ";
5598 PrintMemModel(Ops[1]);
5599 out << "\n";
5600 break;
5601 }
5602 case spv::OpEntryPoint: {
5603 // Ops[0] = Execution Model
5604 // Ops[1] = EntryPoint ID
5605 // Ops[2] = Name (Literal String)
5606 // Ops[3] ... Ops[n] = Interface ID
5607 PrintOpcode(Inst);
5608 out << " ";
5609 PrintExecModel(Ops[0]);
5610 for (uint32_t i = 1; i < Ops.size(); i++) {
5611 out << " ";
5612 PrintOperand(Ops[i]);
5613 }
5614 out << "\n";
5615 break;
5616 }
5617 case spv::OpExecutionMode: {
5618 // Ops[0] = Entry Point ID
5619 // Ops[1] = Execution Mode
5620 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5621 PrintOpcode(Inst);
5622 out << " ";
5623 PrintOperand(Ops[0]);
5624 out << " ";
5625 PrintExecMode(Ops[1]);
5626 for (uint32_t i = 2; i < Ops.size(); i++) {
5627 out << " ";
5628 PrintOperand(Ops[i]);
5629 }
5630 out << "\n";
5631 break;
5632 }
5633 case spv::OpSource: {
5634 // Ops[0] = SourceLanguage ID
5635 // Ops[1] = Version (LiteralNum)
5636 PrintOpcode(Inst);
5637 out << " ";
5638 PrintSourceLanguage(Ops[0]);
5639 out << " ";
5640 PrintOperand(Ops[1]);
5641 out << "\n";
5642 break;
5643 }
5644 case spv::OpDecorate: {
5645 // Ops[0] = Target ID
5646 // Ops[1] = Decoration (Block or BufferBlock)
5647 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5648 PrintOpcode(Inst);
5649 out << " ";
5650 PrintOperand(Ops[0]);
5651 out << " ";
5652 PrintDecoration(Ops[1]);
5653 // Handle BuiltIn OpDecorate specially.
5654 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5655 out << " ";
5656 PrintBuiltIn(Ops[2]);
5657 } else {
5658 for (uint32_t i = 2; i < Ops.size(); i++) {
5659 out << " ";
5660 PrintOperand(Ops[i]);
5661 }
5662 }
5663 out << "\n";
5664 break;
5665 }
5666 case spv::OpMemberDecorate: {
5667 // Ops[0] = Structure Type ID
5668 // Ops[1] = Member Index(Literal Number)
5669 // Ops[2] = Decoration
5670 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5671 PrintOpcode(Inst);
5672 out << " ";
5673 PrintOperand(Ops[0]);
5674 out << " ";
5675 PrintOperand(Ops[1]);
5676 out << " ";
5677 PrintDecoration(Ops[2]);
5678 for (uint32_t i = 3; i < Ops.size(); i++) {
5679 out << " ";
5680 PrintOperand(Ops[i]);
5681 }
5682 out << "\n";
5683 break;
5684 }
5685 case spv::OpTypePointer: {
5686 // Ops[0] = Storage Class
5687 // Ops[1] = Element Type ID
5688 PrintResID(Inst);
5689 out << " = ";
5690 PrintOpcode(Inst);
5691 out << " ";
5692 PrintStorageClass(Ops[0]);
5693 out << " ";
5694 PrintOperand(Ops[1]);
5695 out << "\n";
5696 break;
5697 }
5698 case spv::OpTypeImage: {
5699 // Ops[0] = Sampled Type ID
5700 // Ops[1] = Dim ID
5701 // Ops[2] = Depth (Literal Number)
5702 // Ops[3] = Arrayed (Literal Number)
5703 // Ops[4] = MS (Literal Number)
5704 // Ops[5] = Sampled (Literal Number)
5705 // Ops[6] = Image Format ID
5706 PrintResID(Inst);
5707 out << " = ";
5708 PrintOpcode(Inst);
5709 out << " ";
5710 PrintOperand(Ops[0]);
5711 out << " ";
5712 PrintDimensionality(Ops[1]);
5713 out << " ";
5714 PrintOperand(Ops[2]);
5715 out << " ";
5716 PrintOperand(Ops[3]);
5717 out << " ";
5718 PrintOperand(Ops[4]);
5719 out << " ";
5720 PrintOperand(Ops[5]);
5721 out << " ";
5722 PrintImageFormat(Ops[6]);
5723 out << "\n";
5724 break;
5725 }
5726 case spv::OpFunction: {
5727 // Ops[0] : Result Type ID
5728 // Ops[1] : Function Control
5729 // Ops[2] : Function Type ID
5730 PrintResID(Inst);
5731 out << " = ";
5732 PrintOpcode(Inst);
5733 out << " ";
5734 PrintOperand(Ops[0]);
5735 out << " ";
5736 PrintFuncCtrl(Ops[1]);
5737 out << " ";
5738 PrintOperand(Ops[2]);
5739 out << "\n";
5740 break;
5741 }
5742 case spv::OpSelectionMerge: {
5743 // Ops[0] = Merge Block ID
5744 // Ops[1] = Selection Control
5745 PrintOpcode(Inst);
5746 out << " ";
5747 PrintOperand(Ops[0]);
5748 out << " ";
5749 PrintSelectionControl(Ops[1]);
5750 out << "\n";
5751 break;
5752 }
5753 case spv::OpLoopMerge: {
5754 // Ops[0] = Merge Block ID
5755 // Ops[1] = Continue Target ID
5756 // Ops[2] = Selection Control
5757 PrintOpcode(Inst);
5758 out << " ";
5759 PrintOperand(Ops[0]);
5760 out << " ";
5761 PrintOperand(Ops[1]);
5762 out << " ";
5763 PrintLoopControl(Ops[2]);
5764 out << "\n";
5765 break;
5766 }
5767 case spv::OpImageSampleExplicitLod: {
5768 // Ops[0] = Result Type ID
5769 // Ops[1] = Sampled Image ID
5770 // Ops[2] = Coordinate ID
5771 // Ops[3] = Image Operands Type ID
5772 // Ops[4] ... Ops[n] = Operands ID
5773 PrintResID(Inst);
5774 out << " = ";
5775 PrintOpcode(Inst);
5776 for (uint32_t i = 0; i < 3; i++) {
5777 out << " ";
5778 PrintOperand(Ops[i]);
5779 }
5780 out << " ";
5781 PrintImageOperandsType(Ops[3]);
5782 for (uint32_t i = 4; i < Ops.size(); i++) {
5783 out << " ";
5784 PrintOperand(Ops[i]);
5785 }
5786 out << "\n";
5787 break;
5788 }
5789 case spv::OpVariable: {
5790 // Ops[0] : Result Type ID
5791 // Ops[1] : Storage Class
5792 // Ops[2] ... Ops[n] = Initializer IDs
5793 PrintResID(Inst);
5794 out << " = ";
5795 PrintOpcode(Inst);
5796 out << " ";
5797 PrintOperand(Ops[0]);
5798 out << " ";
5799 PrintStorageClass(Ops[1]);
5800 for (uint32_t i = 2; i < Ops.size(); i++) {
5801 out << " ";
5802 PrintOperand(Ops[i]);
5803 }
5804 out << "\n";
5805 break;
5806 }
5807 case spv::OpExtInst: {
5808 // Ops[0] = Result Type ID
5809 // Ops[1] = Set ID (OpExtInstImport ID)
5810 // Ops[2] = Instruction Number (Literal Number)
5811 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5812 PrintResID(Inst);
5813 out << " = ";
5814 PrintOpcode(Inst);
5815 out << " ";
5816 PrintOperand(Ops[0]);
5817 out << " ";
5818 PrintOperand(Ops[1]);
5819 out << " ";
5820 PrintExtInst(Ops[2]);
5821 for (uint32_t i = 3; i < Ops.size(); i++) {
5822 out << " ";
5823 PrintOperand(Ops[i]);
5824 }
5825 out << "\n";
5826 break;
5827 }
5828 case spv::OpCopyMemory: {
5829 // Ops[0] = Addressing Model
5830 // Ops[1] = Memory Model
5831 PrintOpcode(Inst);
5832 out << " ";
5833 PrintOperand(Ops[0]);
5834 out << " ";
5835 PrintOperand(Ops[1]);
5836 out << " ";
5837 PrintMemoryAccess(Ops[2]);
5838 out << " ";
5839 PrintOperand(Ops[3]);
5840 out << "\n";
5841 break;
5842 }
5843 case spv::OpExtension:
5844 case spv::OpControlBarrier:
5845 case spv::OpMemoryBarrier:
5846 case spv::OpBranch:
5847 case spv::OpBranchConditional:
5848 case spv::OpStore:
5849 case spv::OpImageWrite:
5850 case spv::OpReturnValue:
5851 case spv::OpReturn:
5852 case spv::OpFunctionEnd: {
5853 PrintOpcode(Inst);
5854 for (uint32_t i = 0; i < Ops.size(); i++) {
5855 out << " ";
5856 PrintOperand(Ops[i]);
5857 }
5858 out << "\n";
5859 break;
5860 }
5861 case spv::OpExtInstImport:
5862 case spv::OpTypeRuntimeArray:
5863 case spv::OpTypeStruct:
5864 case spv::OpTypeSampler:
5865 case spv::OpTypeSampledImage:
5866 case spv::OpTypeInt:
5867 case spv::OpTypeFloat:
5868 case spv::OpTypeArray:
5869 case spv::OpTypeVector:
5870 case spv::OpTypeBool:
5871 case spv::OpTypeVoid:
5872 case spv::OpTypeFunction:
5873 case spv::OpFunctionParameter:
5874 case spv::OpLabel:
5875 case spv::OpPhi:
5876 case spv::OpLoad:
5877 case spv::OpSelect:
5878 case spv::OpAccessChain:
5879 case spv::OpPtrAccessChain:
5880 case spv::OpInBoundsAccessChain:
5881 case spv::OpUConvert:
5882 case spv::OpSConvert:
5883 case spv::OpConvertFToU:
5884 case spv::OpConvertFToS:
5885 case spv::OpConvertUToF:
5886 case spv::OpConvertSToF:
5887 case spv::OpFConvert:
5888 case spv::OpConvertPtrToU:
5889 case spv::OpConvertUToPtr:
5890 case spv::OpBitcast:
5891 case spv::OpIAdd:
5892 case spv::OpFAdd:
5893 case spv::OpISub:
5894 case spv::OpFSub:
5895 case spv::OpIMul:
5896 case spv::OpFMul:
5897 case spv::OpUDiv:
5898 case spv::OpSDiv:
5899 case spv::OpFDiv:
5900 case spv::OpUMod:
5901 case spv::OpSRem:
5902 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005903 case spv::OpUMulExtended:
5904 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005905 case spv::OpBitwiseOr:
5906 case spv::OpBitwiseXor:
5907 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005908 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005909 case spv::OpShiftLeftLogical:
5910 case spv::OpShiftRightLogical:
5911 case spv::OpShiftRightArithmetic:
5912 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005913 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005914 case spv::OpCompositeExtract:
5915 case spv::OpVectorExtractDynamic:
5916 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005917 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005918 case spv::OpVectorInsertDynamic:
5919 case spv::OpVectorShuffle:
5920 case spv::OpIEqual:
5921 case spv::OpINotEqual:
5922 case spv::OpUGreaterThan:
5923 case spv::OpUGreaterThanEqual:
5924 case spv::OpULessThan:
5925 case spv::OpULessThanEqual:
5926 case spv::OpSGreaterThan:
5927 case spv::OpSGreaterThanEqual:
5928 case spv::OpSLessThan:
5929 case spv::OpSLessThanEqual:
5930 case spv::OpFOrdEqual:
5931 case spv::OpFOrdGreaterThan:
5932 case spv::OpFOrdGreaterThanEqual:
5933 case spv::OpFOrdLessThan:
5934 case spv::OpFOrdLessThanEqual:
5935 case spv::OpFOrdNotEqual:
5936 case spv::OpFUnordEqual:
5937 case spv::OpFUnordGreaterThan:
5938 case spv::OpFUnordGreaterThanEqual:
5939 case spv::OpFUnordLessThan:
5940 case spv::OpFUnordLessThanEqual:
5941 case spv::OpFUnordNotEqual:
5942 case spv::OpSampledImage:
5943 case spv::OpFunctionCall:
5944 case spv::OpConstantTrue:
5945 case spv::OpConstantFalse:
5946 case spv::OpConstant:
5947 case spv::OpSpecConstant:
5948 case spv::OpConstantComposite:
5949 case spv::OpSpecConstantComposite:
5950 case spv::OpConstantNull:
5951 case spv::OpLogicalOr:
5952 case spv::OpLogicalAnd:
5953 case spv::OpLogicalNot:
5954 case spv::OpLogicalNotEqual:
5955 case spv::OpUndef:
5956 case spv::OpIsInf:
5957 case spv::OpIsNan:
5958 case spv::OpAny:
5959 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005960 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005961 case spv::OpAtomicIAdd:
5962 case spv::OpAtomicISub:
5963 case spv::OpAtomicExchange:
5964 case spv::OpAtomicIIncrement:
5965 case spv::OpAtomicIDecrement:
5966 case spv::OpAtomicCompareExchange:
5967 case spv::OpAtomicUMin:
5968 case spv::OpAtomicSMin:
5969 case spv::OpAtomicUMax:
5970 case spv::OpAtomicSMax:
5971 case spv::OpAtomicAnd:
5972 case spv::OpAtomicOr:
5973 case spv::OpAtomicXor:
5974 case spv::OpDot: {
5975 PrintResID(Inst);
5976 out << " = ";
5977 PrintOpcode(Inst);
5978 for (uint32_t i = 0; i < Ops.size(); i++) {
5979 out << " ";
5980 PrintOperand(Ops[i]);
5981 }
5982 out << "\n";
5983 break;
5984 }
5985 }
5986 }
5987}
5988
5989void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005990 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005991}
5992
5993void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5994 WriteOneWord(Inst->getResultID());
5995}
5996
5997void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5998 // High 16 bit : Word Count
5999 // Low 16 bit : Opcode
6000 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006001 const uint32_t count = Inst->getWordCount();
6002 if (count > 65535) {
6003 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6004 llvm_unreachable("Word count too high");
6005 }
David Neto22f144c2017-06-12 14:26:21 -04006006 Word |= Inst->getWordCount() << 16;
6007 WriteOneWord(Word);
6008}
6009
6010void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6011 SPIRVOperandType OpTy = Op->getType();
6012 switch (OpTy) {
6013 default: {
6014 llvm_unreachable("Unsupported SPIRV Operand Type???");
6015 break;
6016 }
6017 case SPIRVOperandType::NUMBERID: {
6018 WriteOneWord(Op->getNumID());
6019 break;
6020 }
6021 case SPIRVOperandType::LITERAL_STRING: {
6022 std::string Str = Op->getLiteralStr();
6023 const char *Data = Str.c_str();
6024 size_t WordSize = Str.size() / 4;
6025 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6026 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6027 }
6028
6029 uint32_t Remainder = Str.size() % 4;
6030 uint32_t LastWord = 0;
6031 if (Remainder) {
6032 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6033 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6034 }
6035 }
6036
6037 WriteOneWord(LastWord);
6038 break;
6039 }
6040 case SPIRVOperandType::LITERAL_INTEGER:
6041 case SPIRVOperandType::LITERAL_FLOAT: {
6042 auto LiteralNum = Op->getLiteralNum();
6043 // TODO: Handle LiteranNum carefully.
6044 for (auto Word : LiteralNum) {
6045 WriteOneWord(Word);
6046 }
6047 break;
6048 }
6049 }
6050}
6051
6052void SPIRVProducerPass::WriteSPIRVBinary() {
6053 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6054
6055 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006056 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006057 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6058
6059 switch (Opcode) {
6060 default: {
David Neto5c22a252018-03-15 16:07:41 -04006061 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006062 llvm_unreachable("Unsupported SPIRV instruction");
6063 break;
6064 }
6065 case spv::OpCapability:
6066 case spv::OpExtension:
6067 case spv::OpMemoryModel:
6068 case spv::OpEntryPoint:
6069 case spv::OpExecutionMode:
6070 case spv::OpSource:
6071 case spv::OpDecorate:
6072 case spv::OpMemberDecorate:
6073 case spv::OpBranch:
6074 case spv::OpBranchConditional:
6075 case spv::OpSelectionMerge:
6076 case spv::OpLoopMerge:
6077 case spv::OpStore:
6078 case spv::OpImageWrite:
6079 case spv::OpReturnValue:
6080 case spv::OpControlBarrier:
6081 case spv::OpMemoryBarrier:
6082 case spv::OpReturn:
6083 case spv::OpFunctionEnd:
6084 case spv::OpCopyMemory: {
6085 WriteWordCountAndOpcode(Inst);
6086 for (uint32_t i = 0; i < Ops.size(); i++) {
6087 WriteOperand(Ops[i]);
6088 }
6089 break;
6090 }
6091 case spv::OpTypeBool:
6092 case spv::OpTypeVoid:
6093 case spv::OpTypeSampler:
6094 case spv::OpLabel:
6095 case spv::OpExtInstImport:
6096 case spv::OpTypePointer:
6097 case spv::OpTypeRuntimeArray:
6098 case spv::OpTypeStruct:
6099 case spv::OpTypeImage:
6100 case spv::OpTypeSampledImage:
6101 case spv::OpTypeInt:
6102 case spv::OpTypeFloat:
6103 case spv::OpTypeArray:
6104 case spv::OpTypeVector:
6105 case spv::OpTypeFunction: {
6106 WriteWordCountAndOpcode(Inst);
6107 WriteResultID(Inst);
6108 for (uint32_t i = 0; i < Ops.size(); i++) {
6109 WriteOperand(Ops[i]);
6110 }
6111 break;
6112 }
6113 case spv::OpFunction:
6114 case spv::OpFunctionParameter:
6115 case spv::OpAccessChain:
6116 case spv::OpPtrAccessChain:
6117 case spv::OpInBoundsAccessChain:
6118 case spv::OpUConvert:
6119 case spv::OpSConvert:
6120 case spv::OpConvertFToU:
6121 case spv::OpConvertFToS:
6122 case spv::OpConvertUToF:
6123 case spv::OpConvertSToF:
6124 case spv::OpFConvert:
6125 case spv::OpConvertPtrToU:
6126 case spv::OpConvertUToPtr:
6127 case spv::OpBitcast:
6128 case spv::OpIAdd:
6129 case spv::OpFAdd:
6130 case spv::OpISub:
6131 case spv::OpFSub:
6132 case spv::OpIMul:
6133 case spv::OpFMul:
6134 case spv::OpUDiv:
6135 case spv::OpSDiv:
6136 case spv::OpFDiv:
6137 case spv::OpUMod:
6138 case spv::OpSRem:
6139 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00006140 case spv::OpUMulExtended:
6141 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04006142 case spv::OpBitwiseOr:
6143 case spv::OpBitwiseXor:
6144 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006145 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006146 case spv::OpShiftLeftLogical:
6147 case spv::OpShiftRightLogical:
6148 case spv::OpShiftRightArithmetic:
6149 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006150 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006151 case spv::OpCompositeExtract:
6152 case spv::OpVectorExtractDynamic:
6153 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006154 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006155 case spv::OpVectorInsertDynamic:
6156 case spv::OpVectorShuffle:
6157 case spv::OpIEqual:
6158 case spv::OpINotEqual:
6159 case spv::OpUGreaterThan:
6160 case spv::OpUGreaterThanEqual:
6161 case spv::OpULessThan:
6162 case spv::OpULessThanEqual:
6163 case spv::OpSGreaterThan:
6164 case spv::OpSGreaterThanEqual:
6165 case spv::OpSLessThan:
6166 case spv::OpSLessThanEqual:
6167 case spv::OpFOrdEqual:
6168 case spv::OpFOrdGreaterThan:
6169 case spv::OpFOrdGreaterThanEqual:
6170 case spv::OpFOrdLessThan:
6171 case spv::OpFOrdLessThanEqual:
6172 case spv::OpFOrdNotEqual:
6173 case spv::OpFUnordEqual:
6174 case spv::OpFUnordGreaterThan:
6175 case spv::OpFUnordGreaterThanEqual:
6176 case spv::OpFUnordLessThan:
6177 case spv::OpFUnordLessThanEqual:
6178 case spv::OpFUnordNotEqual:
6179 case spv::OpExtInst:
6180 case spv::OpIsInf:
6181 case spv::OpIsNan:
6182 case spv::OpAny:
6183 case spv::OpAll:
6184 case spv::OpUndef:
6185 case spv::OpConstantNull:
6186 case spv::OpLogicalOr:
6187 case spv::OpLogicalAnd:
6188 case spv::OpLogicalNot:
6189 case spv::OpLogicalNotEqual:
6190 case spv::OpConstantComposite:
6191 case spv::OpSpecConstantComposite:
6192 case spv::OpConstantTrue:
6193 case spv::OpConstantFalse:
6194 case spv::OpConstant:
6195 case spv::OpSpecConstant:
6196 case spv::OpVariable:
6197 case spv::OpFunctionCall:
6198 case spv::OpSampledImage:
6199 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006200 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006201 case spv::OpSelect:
6202 case spv::OpPhi:
6203 case spv::OpLoad:
6204 case spv::OpAtomicIAdd:
6205 case spv::OpAtomicISub:
6206 case spv::OpAtomicExchange:
6207 case spv::OpAtomicIIncrement:
6208 case spv::OpAtomicIDecrement:
6209 case spv::OpAtomicCompareExchange:
6210 case spv::OpAtomicUMin:
6211 case spv::OpAtomicSMin:
6212 case spv::OpAtomicUMax:
6213 case spv::OpAtomicSMax:
6214 case spv::OpAtomicAnd:
6215 case spv::OpAtomicOr:
6216 case spv::OpAtomicXor:
6217 case spv::OpDot: {
6218 WriteWordCountAndOpcode(Inst);
6219 WriteOperand(Ops[0]);
6220 WriteResultID(Inst);
6221 for (uint32_t i = 1; i < Ops.size(); i++) {
6222 WriteOperand(Ops[i]);
6223 }
6224 break;
6225 }
6226 }
6227 }
6228}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006229
alan-bakerb6b09dc2018-11-08 16:59:28 -05006230bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006231 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006232 case Type::HalfTyID:
6233 case Type::FloatTyID:
6234 case Type::DoubleTyID:
6235 case Type::IntegerTyID:
6236 case Type::VectorTyID:
6237 return true;
6238 case Type::PointerTyID: {
6239 const PointerType *pointer_type = cast<PointerType>(type);
6240 if (pointer_type->getPointerAddressSpace() !=
6241 AddressSpace::UniformConstant) {
6242 auto pointee_type = pointer_type->getPointerElementType();
6243 if (pointee_type->isStructTy() &&
6244 cast<StructType>(pointee_type)->isOpaque()) {
6245 // Images and samplers are not nullable.
6246 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006247 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006248 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006249 return true;
6250 }
6251 case Type::ArrayTyID:
6252 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6253 case Type::StructTyID: {
6254 const StructType *struct_type = cast<StructType>(type);
6255 // Images and samplers are not nullable.
6256 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006257 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006258 for (const auto element : struct_type->elements()) {
6259 if (!IsTypeNullable(element))
6260 return false;
6261 }
6262 return true;
6263 }
6264 default:
6265 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006266 }
6267}
Alan Bakerfcda9482018-10-02 17:09:59 -04006268
6269void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6270 if (auto *offsets_md =
6271 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6272 // Metdata is stored as key-value pair operands. The first element of each
6273 // operand is the type and the second is a vector of offsets.
6274 for (const auto *operand : offsets_md->operands()) {
6275 const auto *pair = cast<MDTuple>(operand);
6276 auto *type =
6277 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6278 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6279 std::vector<uint32_t> offsets;
6280 for (const Metadata *offset_md : offset_vector->operands()) {
6281 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006282 offsets.push_back(static_cast<uint32_t>(
6283 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006284 }
6285 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6286 }
6287 }
6288
6289 if (auto *sizes_md =
6290 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6291 // Metadata is stored as key-value pair operands. The first element of each
6292 // operand is the type and the second is a triple of sizes: type size in
6293 // bits, store size and alloc size.
6294 for (const auto *operand : sizes_md->operands()) {
6295 const auto *pair = cast<MDTuple>(operand);
6296 auto *type =
6297 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6298 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6299 uint64_t type_size_in_bits =
6300 cast<ConstantInt>(
6301 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6302 ->getZExtValue();
6303 uint64_t type_store_size =
6304 cast<ConstantInt>(
6305 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6306 ->getZExtValue();
6307 uint64_t type_alloc_size =
6308 cast<ConstantInt>(
6309 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6310 ->getZExtValue();
6311 RemappedUBOTypeSizes.insert(std::make_pair(
6312 type, std::make_tuple(type_size_in_bits, type_store_size,
6313 type_alloc_size)));
6314 }
6315 }
6316}
6317
6318uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6319 const DataLayout &DL) {
6320 auto iter = RemappedUBOTypeSizes.find(type);
6321 if (iter != RemappedUBOTypeSizes.end()) {
6322 return std::get<0>(iter->second);
6323 }
6324
6325 return DL.getTypeSizeInBits(type);
6326}
6327
6328uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6329 auto iter = RemappedUBOTypeSizes.find(type);
6330 if (iter != RemappedUBOTypeSizes.end()) {
6331 return std::get<1>(iter->second);
6332 }
6333
6334 return DL.getTypeStoreSize(type);
6335}
6336
6337uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6338 auto iter = RemappedUBOTypeSizes.find(type);
6339 if (iter != RemappedUBOTypeSizes.end()) {
6340 return std::get<2>(iter->second);
6341 }
6342
6343 return DL.getTypeAllocSize(type);
6344}
alan-baker5b86ed72019-02-15 08:26:50 -05006345
6346void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6347 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6348 setVariablePointersStorageBuffer(true);
6349 } else {
6350 setVariablePointers(true);
6351 }
6352}
6353
6354Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6355 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6356 return GetBasePointer(gep->getPointerOperand());
6357 }
6358
6359 // Conservatively return |v|.
6360 return v;
6361}
6362
6363bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6364 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6365 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6366 if (lhs_call->getCalledFunction()->getName().startswith(
6367 clspv::ResourceAccessorFunction()) &&
6368 rhs_call->getCalledFunction()->getName().startswith(
6369 clspv::ResourceAccessorFunction())) {
6370 // For resource accessors, match descriptor set and binding.
6371 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6372 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6373 return true;
6374 } else if (lhs_call->getCalledFunction()->getName().startswith(
6375 clspv::WorkgroupAccessorFunction()) &&
6376 rhs_call->getCalledFunction()->getName().startswith(
6377 clspv::WorkgroupAccessorFunction())) {
6378 // For workgroup resources, match spec id.
6379 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6380 return true;
6381 }
6382 }
6383 }
6384
6385 return false;
6386}
6387
6388bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6389 assert(inst->getType()->isPointerTy());
6390 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6391 spv::StorageClassStorageBuffer);
6392 const bool hack_undef = clspv::Option::HackUndef();
6393 if (auto *select = dyn_cast<SelectInst>(inst)) {
6394 auto *true_base = GetBasePointer(select->getTrueValue());
6395 auto *false_base = GetBasePointer(select->getFalseValue());
6396
6397 if (true_base == false_base)
6398 return true;
6399
6400 // If either the true or false operand is a null, then we satisfy the same
6401 // object constraint.
6402 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6403 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6404 return true;
6405 }
6406
6407 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6408 if (false_cst->isNullValue() ||
6409 (hack_undef && isa<UndefValue>(false_base)))
6410 return true;
6411 }
6412
6413 if (sameResource(true_base, false_base))
6414 return true;
6415 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6416 Value *value = nullptr;
6417 bool ok = true;
6418 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6419 auto *base = GetBasePointer(phi->getIncomingValue(i));
6420 // Null values satisfy the constraint of selecting of selecting from the
6421 // same object.
6422 if (!value) {
6423 if (auto *cst = dyn_cast<Constant>(base)) {
6424 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6425 value = base;
6426 } else {
6427 value = base;
6428 }
6429 } else if (base != value) {
6430 if (auto *base_cst = dyn_cast<Constant>(base)) {
6431 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6432 continue;
6433 }
6434
6435 if (sameResource(value, base))
6436 continue;
6437
6438 // Values don't represent the same base.
6439 ok = false;
6440 }
6441 }
6442
6443 return ok;
6444 }
6445
6446 // Conservatively return false.
6447 return false;
6448}
alan-bakere9308012019-03-15 10:25:13 -04006449
6450bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
6451 if (!Arg.getType()->isPointerTy() ||
6452 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
6453 // Only SSBOs need to be annotated as coherent.
6454 return false;
6455 }
6456
6457 DenseSet<Value *> visited;
6458 std::vector<Value *> stack;
6459 for (auto *U : Arg.getParent()->users()) {
6460 if (auto *call = dyn_cast<CallInst>(U)) {
6461 stack.push_back(call->getOperand(Arg.getArgNo()));
6462 }
6463 }
6464
6465 while (!stack.empty()) {
6466 Value *v = stack.back();
6467 stack.pop_back();
6468
6469 if (!visited.insert(v).second)
6470 continue;
6471
6472 auto *resource_call = dyn_cast<CallInst>(v);
6473 if (resource_call &&
6474 resource_call->getCalledFunction()->getName().startswith(
6475 clspv::ResourceAccessorFunction())) {
6476 // If this is a resource accessor function, check if the coherent operand
6477 // is set.
6478 const auto coherent =
6479 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
6480 ->getZExtValue());
6481 if (coherent == 1)
6482 return true;
6483 } else if (auto *arg = dyn_cast<Argument>(v)) {
6484 // If this is a function argument, trace through its callers.
6485 for (auto U : arg->users()) {
6486 if (auto *call = dyn_cast<CallInst>(U)) {
6487 stack.push_back(call->getOperand(arg->getArgNo()));
6488 }
6489 }
6490 } else if (auto *user = dyn_cast<User>(v)) {
6491 // If this is a user, traverse all operands that could lead to resource
6492 // variables.
6493 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
6494 Value *operand = user->getOperand(i);
6495 if (operand->getType()->isPointerTy() &&
6496 operand->getType()->getPointerAddressSpace() ==
6497 clspv::AddressSpace::Global) {
6498 stack.push_back(operand);
6499 }
6500 }
6501 }
6502 }
6503
6504 // No coherent resource variables encountered.
6505 return false;
6506}