blob: 047cd65179ac48c1bffefb8ab28722fd933cb9c6 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
alan-bakerb6b09dc2018-11-08 16:59:28 -050080const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040081
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500127 SPIRVOperandList(const SPIRVOperandList &other) = delete;
128 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500136 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500145 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
alan-bakerb6b09dc2018-11-08 16:59:28 -0500153SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500156SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500159SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500162SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
163SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400164 return new SPIRVOperand(LITERAL_STRING, str);
165}
David Netoc6f3ab22018-04-06 18:02:31 -0400166
David Neto22f144c2017-06-12 14:26:21 -0400167struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400168 // Create an instruction with an opcode and no result ID, and with the given
169 // operands. This computes its own word count.
170 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
171 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
172 Operands(Ops.begin(), Ops.end()) {
173 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400174 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400175 }
176 }
177 // Create an instruction with an opcode and a no-zero result ID, and
178 // with the given operands. This computes its own word count.
179 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400180 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400181 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
182 Operands(Ops.begin(), Ops.end()) {
183 if (ResID == 0) {
184 llvm_unreachable("Result ID of 0 was provided");
185 }
186 for (auto *operand : Ops) {
187 WordCount += operand->GetNumWords();
188 }
189 }
David Neto22f144c2017-06-12 14:26:21 -0400190
David Netoee2660d2018-06-28 16:31:29 -0400191 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400192 uint16_t getOpcode() const { return Opcode; }
193 uint32_t getResultID() const { return ResultID; }
194 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
195
196private:
David Netoee2660d2018-06-28 16:31:29 -0400197 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400198 uint16_t Opcode;
199 uint32_t ResultID;
200 SmallVector<SPIRVOperand *, 4> Operands;
201};
202
203struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400204 typedef DenseMap<Type *, uint32_t> TypeMapType;
205 typedef UniqueVector<Type *> TypeList;
206 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400207 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400208 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
209 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400210 // A vector of tuples, each of which is:
211 // - the LLVM instruction that we will later generate SPIR-V code for
212 // - where the SPIR-V instruction should be inserted
213 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400214 typedef std::vector<
215 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
216 DeferredInstVecType;
217 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
218 GlobalConstFuncMapType;
219
David Neto44795152017-07-13 15:45:28 -0400220 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500221 raw_pwrite_stream &out,
222 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
David Neto44795152017-07-13 15:45:28 -0400223 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
224 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400225 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400226 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 descriptorMapEntries(descriptor_map_entries), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400228 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500229 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
230 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
231 WorkgroupSizeVarID(0), max_local_spec_id_(0), constant_i32_zero_id_(0) {
232 }
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
alan-baker5b86ed72019-02-15 08:26:50 -0500280 bool hasVariablePointersStorageBuffer() {
281 return HasVariablePointersStorageBuffer;
282 }
283 void setVariablePointersStorageBuffer(bool Val) {
284 HasVariablePointersStorageBuffer = Val;
285 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500286 bool hasVariablePointers() {
alan-baker5b86ed72019-02-15 08:26:50 -0500287 return HasVariablePointers;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 };
David Neto22f144c2017-06-12 14:26:21 -0400289 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500290 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
291 return samplerMap;
292 }
David Neto22f144c2017-06-12 14:26:21 -0400293 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
294 return GlobalConstFuncTypeMap;
295 }
296 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
297 return GlobalConstArgumentSet;
298 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500299 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400300
David Netoc6f3ab22018-04-06 18:02:31 -0400301 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500302 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
303 // *not* be converted to a storage buffer, replace each such global variable
304 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindGlobalConstVars(Module &M, const DataLayout &DL);
306 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
307 // ModuleOrderedResourceVars.
308 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400309 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400310 bool FindExtInst(Module &M);
311 void FindTypePerGlobalVar(GlobalVariable &GV);
312 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400313 void FindTypesForSamplerMap(Module &M);
314 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500315 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
316 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400317 void FindType(Type *Ty);
318 void FindConstantPerGlobalVar(GlobalVariable &GV);
319 void FindConstantPerFunc(Function &F);
320 void FindConstant(Value *V);
321 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400322 // Generates instructions for SPIR-V types corresponding to the LLVM types
323 // saved in the |Types| member. A type follows its subtypes. IDs are
324 // allocated sequentially starting with the current value of nextID, and
325 // with a type following its subtypes. Also updates nextID to just beyond
326 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500327 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400329 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400331 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400332 // Generate descriptor map entries for resource variables associated with
333 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500334 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400335 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400336 // Generate OpVariables for %clspv.resource.var.* calls.
337 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400338 void GenerateFuncPrologue(Function &F);
339 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400340 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400341 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
342 spv::Op GetSPIRVCastOpcode(Instruction &I);
343 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
344 void GenerateInstruction(Instruction &I);
345 void GenerateFuncEpilogue();
346 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500347 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400348 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400349 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
350 // have been created.
351 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400352 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400353 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400354 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400355 // Returns the GLSL extended instruction enum that the given function
356 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400357 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400358 // Returns the GLSL extended instruction enum indirectly used by the given
359 // function. That is, to implement the given function, we use an extended
360 // instruction plus one more instruction. If none, then returns the 0 value,
361 // i.e. GLSLstd4580Bad.
362 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
363 // Returns the single GLSL extended instruction used directly or
364 // indirectly by the given function call.
365 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400366 void PrintResID(SPIRVInstruction *Inst);
367 void PrintOpcode(SPIRVInstruction *Inst);
368 void PrintOperand(SPIRVOperand *Op);
369 void PrintCapability(SPIRVOperand *Op);
370 void PrintExtInst(SPIRVOperand *Op);
371 void PrintAddrModel(SPIRVOperand *Op);
372 void PrintMemModel(SPIRVOperand *Op);
373 void PrintExecModel(SPIRVOperand *Op);
374 void PrintExecMode(SPIRVOperand *Op);
375 void PrintSourceLanguage(SPIRVOperand *Op);
376 void PrintFuncCtrl(SPIRVOperand *Op);
377 void PrintStorageClass(SPIRVOperand *Op);
378 void PrintDecoration(SPIRVOperand *Op);
379 void PrintBuiltIn(SPIRVOperand *Op);
380 void PrintSelectionControl(SPIRVOperand *Op);
381 void PrintLoopControl(SPIRVOperand *Op);
382 void PrintDimensionality(SPIRVOperand *Op);
383 void PrintImageFormat(SPIRVOperand *Op);
384 void PrintMemoryAccess(SPIRVOperand *Op);
385 void PrintImageOperandsType(SPIRVOperand *Op);
386 void WriteSPIRVAssembly();
387 void WriteOneWord(uint32_t Word);
388 void WriteResultID(SPIRVInstruction *Inst);
389 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
390 void WriteOperand(SPIRVOperand *Op);
391 void WriteSPIRVBinary();
392
Alan Baker9bf93fb2018-08-28 16:59:26 -0400393 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500394 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400395
Alan Bakerfcda9482018-10-02 17:09:59 -0400396 // Populate UBO remapped type maps.
397 void PopulateUBOTypeMaps(Module &module);
398
399 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
400 // uses the internal map, otherwise it falls back on the data layout.
401 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
402 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
403 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
404
alan-baker5b86ed72019-02-15 08:26:50 -0500405 // Returns the base pointer of |v|.
406 Value *GetBasePointer(Value *v);
407
408 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
409 // |address_space|.
410 void setVariablePointersCapabilities(unsigned address_space);
411
412 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
413 // variable.
414 bool sameResource(Value *lhs, Value *rhs) const;
415
416 // Returns true if |inst| is phi or select that selects from the same
417 // structure (or null).
418 bool selectFromSameObject(Instruction *inst);
419
David Neto22f144c2017-06-12 14:26:21 -0400420private:
421 static char ID;
David Neto44795152017-07-13 15:45:28 -0400422 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400423 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400424
425 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
426 // convert to other formats on demand?
427
428 // When emitting a C initialization list, the WriteSPIRVBinary method
429 // will actually write its words to this vector via binaryTempOut.
430 SmallVector<char, 100> binaryTempUnderlyingVector;
431 raw_svector_ostream binaryTempOut;
432
433 // Binary output writes to this stream, which might be |out| or
434 // |binaryTempOut|. It's the latter when we really want to write a C
435 // initializer list.
alan-bakerf5e5f692018-11-27 08:33:24 -0500436 raw_pwrite_stream* binaryOut;
437 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto22f144c2017-06-12 14:26:21 -0400438 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400439 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400440 uint64_t patchBoundOffset;
441 uint32_t nextID;
442
David Neto19a1bad2017-08-25 15:01:41 -0400443 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400444 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400445 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400446 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400447 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400448 TypeList Types;
449 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400450 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400451 ValueMapType ValueMap;
452 ValueMapType AllocatedValueMap;
453 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400454
David Neto22f144c2017-06-12 14:26:21 -0400455 EntryPointVecType EntryPointVec;
456 DeferredInstVecType DeferredInstVec;
457 ValueList EntryPointInterfacesVec;
458 uint32_t OpExtInstImportID;
459 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500460 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400461 bool HasVariablePointers;
462 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500463 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700464
465 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700466 // will map F's type to (G, index of the parameter), where in a first phase
467 // G is F's type. During FindTypePerFunc, G will be changed to F's type
468 // but replacing the pointer-to-constant parameter with
469 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700470 // TODO(dneto): This doesn't seem general enough? A function might have
471 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400472 GlobalConstFuncMapType GlobalConstFuncTypeMap;
473 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400474 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700475 // or array types, and which point into transparent memory (StorageBuffer
476 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400477 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700478 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400479
480 // This is truly ugly, but works around what look like driver bugs.
481 // For get_local_size, an earlier part of the flow has created a module-scope
482 // variable in Private address space to hold the value for the workgroup
483 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
484 // When this is present, save the IDs of the initializer value and variable
485 // in these two variables. We only ever do a vector load from it, and
486 // when we see one of those, substitute just the value of the intializer.
487 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700488 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400489 uint32_t WorkgroupSizeValueID;
490 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400491
David Neto862b7d82018-06-14 18:48:37 -0400492 // Bookkeeping for mapping kernel arguments to resource variables.
493 struct ResourceVarInfo {
494 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
495 Function *fn, clspv::ArgKind arg_kind_arg)
496 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
497 var_fn(fn), arg_kind(arg_kind_arg),
498 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
499 const int index; // Index into ResourceVarInfoList
500 const unsigned descriptor_set;
501 const unsigned binding;
502 Function *const var_fn; // The @clspv.resource.var.* function.
503 const clspv::ArgKind arg_kind;
504 const unsigned addr_space; // The LLVM address space
505 // The SPIR-V ID of the OpVariable. Not populated at construction time.
506 uint32_t var_id = 0;
507 };
508 // A list of resource var info. Each one correponds to a module-scope
509 // resource variable we will have to create. Resource var indices are
510 // indices into this vector.
511 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
512 // This is a vector of pointers of all the resource vars, but ordered by
513 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500514 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400515 // Map a function to the ordered list of resource variables it uses, one for
516 // each argument. If an argument does not use a resource variable, it
517 // will have a null pointer entry.
518 using FunctionToResourceVarsMapType =
519 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
520 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
521
522 // What LLVM types map to SPIR-V types needing layout? These are the
523 // arrays and structures supporting storage buffers and uniform buffers.
524 TypeList TypesNeedingLayout;
525 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
526 UniqueVector<StructType *> StructTypesNeedingBlock;
527 // For a call that represents a load from an opaque type (samplers, images),
528 // map it to the variable id it should load from.
529 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700530
Alan Baker202c8c72018-08-13 13:47:44 -0400531 // One larger than the maximum used SpecId for pointer-to-local arguments.
532 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400533 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500534 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400535 LocalArgList LocalArgs;
536 // Information about a pointer-to-local argument.
537 struct LocalArgInfo {
538 // The SPIR-V ID of the array variable.
539 uint32_t variable_id;
540 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500541 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400542 // The ID of the array type.
543 uint32_t array_size_id;
544 // The ID of the array type.
545 uint32_t array_type_id;
546 // The ID of the pointer to the array type.
547 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400548 // The specialization constant ID of the array size.
549 int spec_id;
550 };
Alan Baker202c8c72018-08-13 13:47:44 -0400551 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500552 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400553 // A mapping from SpecId to its LocalArgInfo.
554 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400555 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500556 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500558 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
559 RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400560
561 // The ID of 32-bit integer zero constant. This is only valid after
562 // GenerateSPIRVConstants has run.
563 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400564};
565
566char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400567
alan-bakerb6b09dc2018-11-08 16:59:28 -0500568} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400569
570namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500571ModulePass *createSPIRVProducerPass(
572 raw_pwrite_stream &out,
573 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
574 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
575 bool outputCInitList) {
576 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
577 outputAsm, outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400578}
David Netoc2c368d2017-06-30 16:50:17 -0400579} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400580
581bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400582 binaryOut = outputCInitList ? &binaryTempOut : &out;
583
David Neto257c3892018-04-11 13:19:45 -0400584 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
585
Alan Bakerfcda9482018-10-02 17:09:59 -0400586 PopulateUBOTypeMaps(module);
587
David Neto22f144c2017-06-12 14:26:21 -0400588 // SPIR-V always begins with its header information
589 outputHeader();
590
David Netoc6f3ab22018-04-06 18:02:31 -0400591 const DataLayout &DL = module.getDataLayout();
592
David Neto22f144c2017-06-12 14:26:21 -0400593 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400594 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400595
David Neto22f144c2017-06-12 14:26:21 -0400596 // Collect information on global variables too.
597 for (GlobalVariable &GV : module.globals()) {
598 // If the GV is one of our special __spirv_* variables, remove the
599 // initializer as it was only placed there to force LLVM to not throw the
600 // value away.
601 if (GV.getName().startswith("__spirv_")) {
602 GV.setInitializer(nullptr);
603 }
604
605 // Collect types' information from global variable.
606 FindTypePerGlobalVar(GV);
607
608 // Collect constant information from global variable.
609 FindConstantPerGlobalVar(GV);
610
611 // If the variable is an input, entry points need to know about it.
612 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400613 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400614 }
615 }
616
617 // If there are extended instructions, generate OpExtInstImport.
618 if (FindExtInst(module)) {
619 GenerateExtInstImport();
620 }
621
622 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400623 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400624
625 // Generate SPIRV constants.
626 GenerateSPIRVConstants();
627
628 // If we have a sampler map, we might have literal samplers to generate.
629 if (0 < getSamplerMap().size()) {
630 GenerateSamplers(module);
631 }
632
633 // Generate SPIRV variables.
634 for (GlobalVariable &GV : module.globals()) {
635 GenerateGlobalVar(GV);
636 }
David Neto862b7d82018-06-14 18:48:37 -0400637 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400638 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400639
640 // Generate SPIRV instructions for each function.
641 for (Function &F : module) {
642 if (F.isDeclaration()) {
643 continue;
644 }
645
David Neto862b7d82018-06-14 18:48:37 -0400646 GenerateDescriptorMapInfo(DL, F);
647
David Neto22f144c2017-06-12 14:26:21 -0400648 // Generate Function Prologue.
649 GenerateFuncPrologue(F);
650
651 // Generate SPIRV instructions for function body.
652 GenerateFuncBody(F);
653
654 // Generate Function Epilogue.
655 GenerateFuncEpilogue();
656 }
657
658 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400659 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400660
661 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400662 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400663
664 if (outputAsm) {
665 WriteSPIRVAssembly();
666 } else {
667 WriteSPIRVBinary();
668 }
669
670 // We need to patch the SPIR-V header to set bound correctly.
671 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400672
673 if (outputCInitList) {
674 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400675 std::ostringstream os;
676
David Neto57fb0b92017-08-04 15:35:09 -0400677 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400678 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400679 os << ",\n";
680 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400681 first = false;
682 };
683
684 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400685 const std::string str(binaryTempOut.str());
686 for (unsigned i = 0; i < str.size(); i += 4) {
687 const uint32_t a = static_cast<unsigned char>(str[i]);
688 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
689 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
690 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
691 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400692 }
693 os << "}\n";
694 out << os.str();
695 }
696
David Neto22f144c2017-06-12 14:26:21 -0400697 return false;
698}
699
700void SPIRVProducerPass::outputHeader() {
701 if (outputAsm) {
702 // for ASM output the header goes into 5 comments at the beginning of the
703 // file
704 out << "; SPIR-V\n";
705
706 // the major version number is in the 2nd highest byte
707 const uint32_t major = (spv::Version >> 16) & 0xFF;
708
709 // the minor version number is in the 2nd lowest byte
710 const uint32_t minor = (spv::Version >> 8) & 0xFF;
711 out << "; Version: " << major << "." << minor << "\n";
712
713 // use Codeplay's vendor ID
714 out << "; Generator: Codeplay; 0\n";
715
716 out << "; Bound: ";
717
718 // we record where we need to come back to and patch in the bound value
719 patchBoundOffset = out.tell();
720
721 // output one space per digit for the max size of a 32 bit unsigned integer
722 // (which is the maximum ID we could possibly be using)
723 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
724 out << " ";
725 }
726
727 out << "\n";
728
729 out << "; Schema: 0\n";
730 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400731 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500732 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400733 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
alan-bakerb6b09dc2018-11-08 16:59:28 -0500734 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400735
736 // use Codeplay's vendor ID
737 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400738 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400739
740 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400741 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400742
743 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400744 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400745
746 // output the schema (reserved for use and must be 0)
747 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400748 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400749 }
750}
751
752void SPIRVProducerPass::patchHeader() {
753 if (outputAsm) {
754 // get the string representation of the max bound used (nextID will be the
755 // max ID used)
756 auto asString = std::to_string(nextID);
757 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
758 } else {
759 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400760 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
761 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400762 }
763}
764
David Netoc6f3ab22018-04-06 18:02:31 -0400765void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400766 // This function generates LLVM IR for function such as global variable for
767 // argument, constant and pointer type for argument access. These information
768 // is artificial one because we need Vulkan SPIR-V output. This function is
769 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400770 LLVMContext &Context = M.getContext();
771
David Neto862b7d82018-06-14 18:48:37 -0400772 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400773
David Neto862b7d82018-06-14 18:48:37 -0400774 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400775
776 bool HasWorkGroupBuiltin = false;
777 for (GlobalVariable &GV : M.globals()) {
778 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
779 if (spv::BuiltInWorkgroupSize == BuiltinType) {
780 HasWorkGroupBuiltin = true;
781 }
782 }
783
David Neto862b7d82018-06-14 18:48:37 -0400784 FindTypesForSamplerMap(M);
785 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400786 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400787
David Neto862b7d82018-06-14 18:48:37 -0400788 // These function calls need a <2 x i32> as an intermediate result but not
789 // the final result.
790 std::unordered_set<std::string> NeedsIVec2{
791 "_Z15get_image_width14ocl_image2d_ro",
792 "_Z15get_image_width14ocl_image2d_wo",
793 "_Z16get_image_height14ocl_image2d_ro",
794 "_Z16get_image_height14ocl_image2d_wo",
795 };
796
David Neto22f144c2017-06-12 14:26:21 -0400797 for (Function &F : M) {
798 // Handle kernel function first.
799 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
800 continue;
801 }
802
803 for (BasicBlock &BB : F) {
804 for (Instruction &I : BB) {
805 if (I.getOpcode() == Instruction::ZExt ||
806 I.getOpcode() == Instruction::SExt ||
807 I.getOpcode() == Instruction::UIToFP) {
808 // If there is zext with i1 type, it will be changed to OpSelect. The
809 // OpSelect needs constant 0 and 1 so the constants are added here.
810
811 auto OpTy = I.getOperand(0)->getType();
812
Kévin Petit24272b62018-10-18 19:16:12 +0000813 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400814 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400815 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000816 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400817 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400818 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000819 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400820 } else {
821 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
822 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
823 }
824 }
825 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400826 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400827
828 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400829 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400830 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400831 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400832 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
833 TypeMapType &OpImageTypeMap = getImageTypeMap();
834 Type *ImageTy =
835 Call->getArgOperand(0)->getType()->getPointerElementType();
836 OpImageTypeMap[ImageTy] = 0;
837
838 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
839 }
David Neto5c22a252018-03-15 16:07:41 -0400840
David Neto862b7d82018-06-14 18:48:37 -0400841 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400842 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
843 }
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845 }
846 }
847
David Neto22f144c2017-06-12 14:26:21 -0400848 if (const MDNode *MD =
849 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
850 // We generate constants if the WorkgroupSize builtin is being used.
851 if (HasWorkGroupBuiltin) {
852 // Collect constant information for work group size.
853 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
854 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
855 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
856 }
857 }
858
David Neto22f144c2017-06-12 14:26:21 -0400859 // Collect types' information from function.
860 FindTypePerFunc(F);
861
862 // Collect constant information from function.
863 FindConstantPerFunc(F);
864 }
865
866 for (Function &F : M) {
867 // Handle non-kernel functions.
868 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
869 continue;
870 }
871
872 for (BasicBlock &BB : F) {
873 for (Instruction &I : BB) {
874 if (I.getOpcode() == Instruction::ZExt ||
875 I.getOpcode() == Instruction::SExt ||
876 I.getOpcode() == Instruction::UIToFP) {
877 // If there is zext with i1 type, it will be changed to OpSelect. The
878 // OpSelect needs constant 0 and 1 so the constants are added here.
879
880 auto OpTy = I.getOperand(0)->getType();
881
Kévin Petit24272b62018-10-18 19:16:12 +0000882 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400883 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400884 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000885 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400886 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400887 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000888 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400889 } else {
890 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
891 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
892 }
893 }
894 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
895 Function *Callee = Call->getCalledFunction();
896
897 // Handle image type specially.
898 if (Callee->getName().equals(
899 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
900 Callee->getName().equals(
901 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
902 TypeMapType &OpImageTypeMap = getImageTypeMap();
903 Type *ImageTy =
904 Call->getArgOperand(0)->getType()->getPointerElementType();
905 OpImageTypeMap[ImageTy] = 0;
906
907 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
908 }
909 }
910 }
911 }
912
913 if (M.getTypeByName("opencl.image2d_ro_t") ||
914 M.getTypeByName("opencl.image2d_wo_t") ||
915 M.getTypeByName("opencl.image3d_ro_t") ||
916 M.getTypeByName("opencl.image3d_wo_t")) {
917 // Assume Image type's sampled type is float type.
918 FindType(Type::getFloatTy(Context));
919 }
920
921 // Collect types' information from function.
922 FindTypePerFunc(F);
923
924 // Collect constant information from function.
925 FindConstantPerFunc(F);
926 }
927}
928
David Neto862b7d82018-06-14 18:48:37 -0400929void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
930 SmallVector<GlobalVariable *, 8> GVList;
931 SmallVector<GlobalVariable *, 8> DeadGVList;
932 for (GlobalVariable &GV : M.globals()) {
933 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
934 if (GV.use_empty()) {
935 DeadGVList.push_back(&GV);
936 } else {
937 GVList.push_back(&GV);
938 }
939 }
940 }
941
942 // Remove dead global __constant variables.
943 for (auto GV : DeadGVList) {
944 GV->eraseFromParent();
945 }
946 DeadGVList.clear();
947
948 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
949 // For now, we only support a single storage buffer.
950 if (GVList.size() > 0) {
951 assert(GVList.size() == 1);
952 const auto *GV = GVList[0];
953 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400954 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400955 const size_t kConstantMaxSize = 65536;
956 if (constants_byte_size > kConstantMaxSize) {
957 outs() << "Max __constant capacity of " << kConstantMaxSize
958 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
959 llvm_unreachable("Max __constant capacity exceeded");
960 }
961 }
962 } else {
963 // Change global constant variable's address space to ModuleScopePrivate.
964 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
965 for (auto GV : GVList) {
966 // Create new gv with ModuleScopePrivate address space.
967 Type *NewGVTy = GV->getType()->getPointerElementType();
968 GlobalVariable *NewGV = new GlobalVariable(
969 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
970 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
971 NewGV->takeName(GV);
972
973 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
974 SmallVector<User *, 8> CandidateUsers;
975
976 auto record_called_function_type_as_user =
977 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
978 // Find argument index.
979 unsigned index = 0;
980 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
981 if (gv == call->getOperand(i)) {
982 // TODO(dneto): Should we break here?
983 index = i;
984 }
985 }
986
987 // Record function type with global constant.
988 GlobalConstFuncTyMap[call->getFunctionType()] =
989 std::make_pair(call->getFunctionType(), index);
990 };
991
992 for (User *GVU : GVUsers) {
993 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
994 record_called_function_type_as_user(GV, Call);
995 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
996 // Check GEP users.
997 for (User *GEPU : GEP->users()) {
998 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
999 record_called_function_type_as_user(GEP, GEPCall);
1000 }
1001 }
1002 }
1003
1004 CandidateUsers.push_back(GVU);
1005 }
1006
1007 for (User *U : CandidateUsers) {
1008 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -05001009 if (!isa<Constant>(U)) {
1010 // #254: Can't change operands of a constant, but this shouldn't be
1011 // something that sticks around in the module.
1012 U->replaceUsesOfWith(GV, NewGV);
1013 }
David Neto862b7d82018-06-14 18:48:37 -04001014 }
1015
1016 // Delete original gv.
1017 GV->eraseFromParent();
1018 }
1019 }
1020}
1021
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001022void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -04001023 ResourceVarInfoList.clear();
1024 FunctionToResourceVarsMap.clear();
1025 ModuleOrderedResourceVars.reset();
1026 // Normally, there is one resource variable per clspv.resource.var.*
1027 // function, since that is unique'd by arg type and index. By design,
1028 // we can share these resource variables across kernels because all
1029 // kernels use the same descriptor set.
1030 //
1031 // But if the user requested distinct descriptor sets per kernel, then
1032 // the descriptor allocator has made different (set,binding) pairs for
1033 // the same (type,arg_index) pair. Since we can decorate a resource
1034 // variable with only exactly one DescriptorSet and Binding, we are
1035 // forced in this case to make distinct resource variables whenever
1036 // the same clspv.reource.var.X function is seen with disintct
1037 // (set,binding) values.
1038 const bool always_distinct_sets =
1039 clspv::Option::DistinctKernelDescriptorSets();
1040 for (Function &F : M) {
1041 // Rely on the fact the resource var functions have a stable ordering
1042 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001043 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001044 // Find all calls to this function with distinct set and binding pairs.
1045 // Save them in ResourceVarInfoList.
1046
1047 // Determine uniqueness of the (set,binding) pairs only withing this
1048 // one resource-var builtin function.
1049 using SetAndBinding = std::pair<unsigned, unsigned>;
1050 // Maps set and binding to the resource var info.
1051 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1052 bool first_use = true;
1053 for (auto &U : F.uses()) {
1054 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1055 const auto set = unsigned(
1056 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1057 const auto binding = unsigned(
1058 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1059 const auto arg_kind = clspv::ArgKind(
1060 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1061 const auto arg_index = unsigned(
1062 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1063
1064 // Find or make the resource var info for this combination.
1065 ResourceVarInfo *rv = nullptr;
1066 if (always_distinct_sets) {
1067 // Make a new resource var any time we see a different
1068 // (set,binding) pair.
1069 SetAndBinding key{set, binding};
1070 auto where = set_and_binding_map.find(key);
1071 if (where == set_and_binding_map.end()) {
1072 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1073 binding, &F, arg_kind);
1074 ResourceVarInfoList.emplace_back(rv);
1075 set_and_binding_map[key] = rv;
1076 } else {
1077 rv = where->second;
1078 }
1079 } else {
1080 // The default is to make exactly one resource for each
1081 // clspv.resource.var.* function.
1082 if (first_use) {
1083 first_use = false;
1084 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1085 binding, &F, arg_kind);
1086 ResourceVarInfoList.emplace_back(rv);
1087 } else {
1088 rv = ResourceVarInfoList.back().get();
1089 }
1090 }
1091
1092 // Now populate FunctionToResourceVarsMap.
1093 auto &mapping =
1094 FunctionToResourceVarsMap[call->getParent()->getParent()];
1095 while (mapping.size() <= arg_index) {
1096 mapping.push_back(nullptr);
1097 }
1098 mapping[arg_index] = rv;
1099 }
1100 }
1101 }
1102 }
1103
1104 // Populate ModuleOrderedResourceVars.
1105 for (Function &F : M) {
1106 auto where = FunctionToResourceVarsMap.find(&F);
1107 if (where != FunctionToResourceVarsMap.end()) {
1108 for (auto &rv : where->second) {
1109 if (rv != nullptr) {
1110 ModuleOrderedResourceVars.insert(rv);
1111 }
1112 }
1113 }
1114 }
1115 if (ShowResourceVars) {
1116 for (auto *info : ModuleOrderedResourceVars) {
1117 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1118 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1119 << "\n";
1120 }
1121 }
1122}
1123
David Neto22f144c2017-06-12 14:26:21 -04001124bool SPIRVProducerPass::FindExtInst(Module &M) {
1125 LLVMContext &Context = M.getContext();
1126 bool HasExtInst = false;
1127
1128 for (Function &F : M) {
1129 for (BasicBlock &BB : F) {
1130 for (Instruction &I : BB) {
1131 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1132 Function *Callee = Call->getCalledFunction();
1133 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001134 auto callee_name = Callee->getName();
1135 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1136 const glsl::ExtInst IndirectEInst =
1137 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001138
David Neto3fbb4072017-10-16 11:28:14 -04001139 HasExtInst |=
1140 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1141
1142 if (IndirectEInst) {
1143 // Register extra constants if needed.
1144
1145 // Registers a type and constant for computing the result of the
1146 // given instruction. If the result of the instruction is a vector,
1147 // then make a splat vector constant with the same number of
1148 // elements.
1149 auto register_constant = [this, &I](Constant *constant) {
1150 FindType(constant->getType());
1151 FindConstant(constant);
1152 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1153 // Register the splat vector of the value with the same
1154 // width as the result of the instruction.
1155 auto *vec_constant = ConstantVector::getSplat(
1156 static_cast<unsigned>(vectorTy->getNumElements()),
1157 constant);
1158 FindConstant(vec_constant);
1159 FindType(vec_constant->getType());
1160 }
1161 };
1162 switch (IndirectEInst) {
1163 case glsl::ExtInstFindUMsb:
1164 // clz needs OpExtInst and OpISub with constant 31, or splat
1165 // vector of 31. Add it to the constant list here.
1166 register_constant(
1167 ConstantInt::get(Type::getInt32Ty(Context), 31));
1168 break;
1169 case glsl::ExtInstAcos:
1170 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001171 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001172 case glsl::ExtInstAtan2:
1173 // We need 1/pi for acospi, asinpi, atan2pi.
1174 register_constant(
1175 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1176 break;
1177 default:
1178 assert(false && "internally inconsistent");
1179 }
David Neto22f144c2017-06-12 14:26:21 -04001180 }
1181 }
1182 }
1183 }
1184 }
1185
1186 return HasExtInst;
1187}
1188
1189void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1190 // Investigate global variable's type.
1191 FindType(GV.getType());
1192}
1193
1194void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1195 // Investigate function's type.
1196 FunctionType *FTy = F.getFunctionType();
1197
1198 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1199 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001200 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001201 if (GlobalConstFuncTyMap.count(FTy)) {
1202 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1203 SmallVector<Type *, 4> NewFuncParamTys;
1204 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1205 Type *ParamTy = FTy->getParamType(i);
1206 if (i == GVCstArgIdx) {
1207 Type *EleTy = ParamTy->getPointerElementType();
1208 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1209 }
1210
1211 NewFuncParamTys.push_back(ParamTy);
1212 }
1213
1214 FunctionType *NewFTy =
1215 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1216 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1217 FTy = NewFTy;
1218 }
1219
1220 FindType(FTy);
1221 } else {
1222 // As kernel functions do not have parameters, create new function type and
1223 // add it to type map.
1224 SmallVector<Type *, 4> NewFuncParamTys;
1225 FunctionType *NewFTy =
1226 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1227 FindType(NewFTy);
1228 }
1229
1230 // Investigate instructions' type in function body.
1231 for (BasicBlock &BB : F) {
1232 for (Instruction &I : BB) {
1233 if (isa<ShuffleVectorInst>(I)) {
1234 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1235 // Ignore type for mask of shuffle vector instruction.
1236 if (i == 2) {
1237 continue;
1238 }
1239
1240 Value *Op = I.getOperand(i);
1241 if (!isa<MetadataAsValue>(Op)) {
1242 FindType(Op->getType());
1243 }
1244 }
1245
1246 FindType(I.getType());
1247 continue;
1248 }
1249
David Neto862b7d82018-06-14 18:48:37 -04001250 CallInst *Call = dyn_cast<CallInst>(&I);
1251
1252 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001253 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001254 // This is a fake call representing access to a resource variable.
1255 // We handle that elsewhere.
1256 continue;
1257 }
1258
Alan Baker202c8c72018-08-13 13:47:44 -04001259 if (Call && Call->getCalledFunction()->getName().startswith(
1260 clspv::WorkgroupAccessorFunction())) {
1261 // This is a fake call representing access to a workgroup variable.
1262 // We handle that elsewhere.
1263 continue;
1264 }
1265
David Neto22f144c2017-06-12 14:26:21 -04001266 // Work through the operands of the instruction.
1267 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1268 Value *const Op = I.getOperand(i);
1269 // If any of the operands is a constant, find the type!
1270 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1271 FindType(Op->getType());
1272 }
1273 }
1274
1275 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001276 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001277 // Avoid to check call instruction's type.
1278 break;
1279 }
Alan Baker202c8c72018-08-13 13:47:44 -04001280 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1281 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1282 clspv::WorkgroupAccessorFunction())) {
1283 // This is a fake call representing access to a workgroup variable.
1284 // We handle that elsewhere.
1285 continue;
1286 }
1287 }
David Neto22f144c2017-06-12 14:26:21 -04001288 if (!isa<MetadataAsValue>(&Op)) {
1289 FindType(Op->getType());
1290 continue;
1291 }
1292 }
1293
David Neto22f144c2017-06-12 14:26:21 -04001294 // We don't want to track the type of this call as we are going to replace
1295 // it.
David Neto862b7d82018-06-14 18:48:37 -04001296 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001297 Call->getCalledFunction()->getName())) {
1298 continue;
1299 }
1300
1301 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1302 // If gep's base operand has ModuleScopePrivate address space, make gep
1303 // return ModuleScopePrivate address space.
1304 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1305 // Add pointer type with private address space for global constant to
1306 // type list.
1307 Type *EleTy = I.getType()->getPointerElementType();
1308 Type *NewPTy =
1309 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1310
1311 FindType(NewPTy);
1312 continue;
1313 }
1314 }
1315
1316 FindType(I.getType());
1317 }
1318 }
1319}
1320
David Neto862b7d82018-06-14 18:48:37 -04001321void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1322 // If we are using a sampler map, find the type of the sampler.
1323 if (M.getFunction("clspv.sampler.var.literal") ||
1324 0 < getSamplerMap().size()) {
1325 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1326 if (!SamplerStructTy) {
1327 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1328 }
1329
1330 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1331
1332 FindType(SamplerTy);
1333 }
1334}
1335
1336void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1337 // Record types so they are generated.
1338 TypesNeedingLayout.reset();
1339 StructTypesNeedingBlock.reset();
1340
1341 // To match older clspv codegen, generate the float type first if required
1342 // for images.
1343 for (const auto *info : ModuleOrderedResourceVars) {
1344 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1345 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1346 // We need "float" for the sampled component type.
1347 FindType(Type::getFloatTy(M.getContext()));
1348 // We only need to find it once.
1349 break;
1350 }
1351 }
1352
1353 for (const auto *info : ModuleOrderedResourceVars) {
1354 Type *type = info->var_fn->getReturnType();
1355
1356 switch (info->arg_kind) {
1357 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001358 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001359 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1360 StructTypesNeedingBlock.insert(sty);
1361 } else {
1362 errs() << *type << "\n";
1363 llvm_unreachable("Buffer arguments must map to structures!");
1364 }
1365 break;
1366 case clspv::ArgKind::Pod:
1367 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1368 StructTypesNeedingBlock.insert(sty);
1369 } else {
1370 errs() << *type << "\n";
1371 llvm_unreachable("POD arguments must map to structures!");
1372 }
1373 break;
1374 case clspv::ArgKind::ReadOnlyImage:
1375 case clspv::ArgKind::WriteOnlyImage:
1376 case clspv::ArgKind::Sampler:
1377 // Sampler and image types map to the pointee type but
1378 // in the uniform constant address space.
1379 type = PointerType::get(type->getPointerElementType(),
1380 clspv::AddressSpace::UniformConstant);
1381 break;
1382 default:
1383 break;
1384 }
1385
1386 // The converted type is the type of the OpVariable we will generate.
1387 // If the pointee type is an array of size zero, FindType will convert it
1388 // to a runtime array.
1389 FindType(type);
1390 }
1391
1392 // Traverse the arrays and structures underneath each Block, and
1393 // mark them as needing layout.
1394 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1395 StructTypesNeedingBlock.end());
1396 while (!work_list.empty()) {
1397 Type *type = work_list.back();
1398 work_list.pop_back();
1399 TypesNeedingLayout.insert(type);
1400 switch (type->getTypeID()) {
1401 case Type::ArrayTyID:
1402 work_list.push_back(type->getArrayElementType());
1403 if (!Hack_generate_runtime_array_stride_early) {
1404 // Remember this array type for deferred decoration.
1405 TypesNeedingArrayStride.insert(type);
1406 }
1407 break;
1408 case Type::StructTyID:
1409 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1410 work_list.push_back(elem_ty);
1411 }
1412 default:
1413 // This type and its contained types don't get layout.
1414 break;
1415 }
1416 }
1417}
1418
Alan Baker202c8c72018-08-13 13:47:44 -04001419void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1420 // The SpecId assignment for pointer-to-local arguments is recorded in
1421 // module-level metadata. Translate that information into local argument
1422 // information.
1423 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001424 if (!nmd)
1425 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001426 for (auto operand : nmd->operands()) {
1427 MDTuple *tuple = cast<MDTuple>(operand);
1428 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1429 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001430 ConstantAsMetadata *arg_index_md =
1431 cast<ConstantAsMetadata>(tuple->getOperand(1));
1432 int arg_index = static_cast<int>(
1433 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1434 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001435
1436 ConstantAsMetadata *spec_id_md =
1437 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001438 int spec_id = static_cast<int>(
1439 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001440
1441 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1442 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001443 if (LocalSpecIdInfoMap.count(spec_id))
1444 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001445
1446 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1447 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1448 nextID + 1, nextID + 2,
1449 nextID + 3, spec_id};
1450 LocalSpecIdInfoMap[spec_id] = info;
1451 nextID += 4;
1452
1453 // Ensure the types necessary for this argument get generated.
1454 Type *IdxTy = Type::getInt32Ty(M.getContext());
1455 FindConstant(ConstantInt::get(IdxTy, 0));
1456 FindType(IdxTy);
1457 FindType(arg->getType());
1458 }
1459}
1460
David Neto22f144c2017-06-12 14:26:21 -04001461void SPIRVProducerPass::FindType(Type *Ty) {
1462 TypeList &TyList = getTypeList();
1463
1464 if (0 != TyList.idFor(Ty)) {
1465 return;
1466 }
1467
1468 if (Ty->isPointerTy()) {
1469 auto AddrSpace = Ty->getPointerAddressSpace();
1470 if ((AddressSpace::Constant == AddrSpace) ||
1471 (AddressSpace::Global == AddrSpace)) {
1472 auto PointeeTy = Ty->getPointerElementType();
1473
1474 if (PointeeTy->isStructTy() &&
1475 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1476 FindType(PointeeTy);
1477 auto ActualPointerTy =
1478 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1479 FindType(ActualPointerTy);
1480 return;
1481 }
1482 }
1483 }
1484
David Neto862b7d82018-06-14 18:48:37 -04001485 // By convention, LLVM array type with 0 elements will map to
1486 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1487 // has a constant number of elements. We need to support type of the
1488 // constant.
1489 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1490 if (arrayTy->getNumElements() > 0) {
1491 LLVMContext &Context = Ty->getContext();
1492 FindType(Type::getInt32Ty(Context));
1493 }
David Neto22f144c2017-06-12 14:26:21 -04001494 }
1495
1496 for (Type *SubTy : Ty->subtypes()) {
1497 FindType(SubTy);
1498 }
1499
1500 TyList.insert(Ty);
1501}
1502
1503void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1504 // If the global variable has a (non undef) initializer.
1505 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001506 // Generate the constant if it's not the initializer to a module scope
1507 // constant that we will expect in a storage buffer.
1508 const bool module_scope_constant_external_init =
1509 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1510 clspv::Option::ModuleConstantsInStorageBuffer();
1511 if (!module_scope_constant_external_init) {
1512 FindConstant(GV.getInitializer());
1513 }
David Neto22f144c2017-06-12 14:26:21 -04001514 }
1515}
1516
1517void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1518 // Investigate constants in function body.
1519 for (BasicBlock &BB : F) {
1520 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001521 if (auto *call = dyn_cast<CallInst>(&I)) {
1522 auto name = call->getCalledFunction()->getName();
1523 if (name == "clspv.sampler.var.literal") {
1524 // We've handled these constants elsewhere, so skip it.
1525 continue;
1526 }
Alan Baker202c8c72018-08-13 13:47:44 -04001527 if (name.startswith(clspv::ResourceAccessorFunction())) {
1528 continue;
1529 }
1530 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001531 continue;
1532 }
David Neto22f144c2017-06-12 14:26:21 -04001533 }
1534
1535 if (isa<AllocaInst>(I)) {
1536 // Alloca instruction has constant for the number of element. Ignore it.
1537 continue;
1538 } else if (isa<ShuffleVectorInst>(I)) {
1539 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1540 // Ignore constant for mask of shuffle vector instruction.
1541 if (i == 2) {
1542 continue;
1543 }
1544
1545 if (isa<Constant>(I.getOperand(i)) &&
1546 !isa<GlobalValue>(I.getOperand(i))) {
1547 FindConstant(I.getOperand(i));
1548 }
1549 }
1550
1551 continue;
1552 } else if (isa<InsertElementInst>(I)) {
1553 // Handle InsertElement with <4 x i8> specially.
1554 Type *CompositeTy = I.getOperand(0)->getType();
1555 if (is4xi8vec(CompositeTy)) {
1556 LLVMContext &Context = CompositeTy->getContext();
1557 if (isa<Constant>(I.getOperand(0))) {
1558 FindConstant(I.getOperand(0));
1559 }
1560
1561 if (isa<Constant>(I.getOperand(1))) {
1562 FindConstant(I.getOperand(1));
1563 }
1564
1565 // Add mask constant 0xFF.
1566 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1567 FindConstant(CstFF);
1568
1569 // Add shift amount constant.
1570 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1571 uint64_t Idx = CI->getZExtValue();
1572 Constant *CstShiftAmount =
1573 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1574 FindConstant(CstShiftAmount);
1575 }
1576
1577 continue;
1578 }
1579
1580 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1581 // Ignore constant for index of InsertElement instruction.
1582 if (i == 2) {
1583 continue;
1584 }
1585
1586 if (isa<Constant>(I.getOperand(i)) &&
1587 !isa<GlobalValue>(I.getOperand(i))) {
1588 FindConstant(I.getOperand(i));
1589 }
1590 }
1591
1592 continue;
1593 } else if (isa<ExtractElementInst>(I)) {
1594 // Handle ExtractElement with <4 x i8> specially.
1595 Type *CompositeTy = I.getOperand(0)->getType();
1596 if (is4xi8vec(CompositeTy)) {
1597 LLVMContext &Context = CompositeTy->getContext();
1598 if (isa<Constant>(I.getOperand(0))) {
1599 FindConstant(I.getOperand(0));
1600 }
1601
1602 // Add mask constant 0xFF.
1603 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1604 FindConstant(CstFF);
1605
1606 // Add shift amount constant.
1607 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1608 uint64_t Idx = CI->getZExtValue();
1609 Constant *CstShiftAmount =
1610 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1611 FindConstant(CstShiftAmount);
1612 } else {
1613 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1614 FindConstant(Cst8);
1615 }
1616
1617 continue;
1618 }
1619
1620 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1621 // Ignore constant for index of ExtractElement instruction.
1622 if (i == 1) {
1623 continue;
1624 }
1625
1626 if (isa<Constant>(I.getOperand(i)) &&
1627 !isa<GlobalValue>(I.getOperand(i))) {
1628 FindConstant(I.getOperand(i));
1629 }
1630 }
1631
1632 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001633 } else if ((Instruction::Xor == I.getOpcode()) &&
1634 I.getType()->isIntegerTy(1)) {
1635 // We special case for Xor where the type is i1 and one of the arguments
1636 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1637 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001638 bool foundConstantTrue = false;
1639 for (Use &Op : I.operands()) {
1640 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1641 auto CI = cast<ConstantInt>(Op);
1642
1643 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001644 // If we already found the true constant, we might (probably only
1645 // on -O0) have an OpLogicalNot which is taking a constant
1646 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001647 FindConstant(Op);
1648 } else {
1649 foundConstantTrue = true;
1650 }
1651 }
1652 }
1653
1654 continue;
David Netod2de94a2017-08-28 17:27:47 -04001655 } else if (isa<TruncInst>(I)) {
1656 // For truncation to i8 we mask against 255.
1657 Type *ToTy = I.getType();
1658 if (8u == ToTy->getPrimitiveSizeInBits()) {
1659 LLVMContext &Context = ToTy->getContext();
1660 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1661 FindConstant(Cst255);
1662 }
1663 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001664 } else if (isa<AtomicRMWInst>(I)) {
1665 LLVMContext &Context = I.getContext();
1666
1667 FindConstant(
1668 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1669 FindConstant(ConstantInt::get(
1670 Type::getInt32Ty(Context),
1671 spv::MemorySemanticsUniformMemoryMask |
1672 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001673 }
1674
1675 for (Use &Op : I.operands()) {
1676 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1677 FindConstant(Op);
1678 }
1679 }
1680 }
1681 }
1682}
1683
1684void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001685 ValueList &CstList = getConstantList();
1686
David Netofb9a7972017-08-25 17:08:24 -04001687 // If V is already tracked, ignore it.
1688 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001689 return;
1690 }
1691
David Neto862b7d82018-06-14 18:48:37 -04001692 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1693 return;
1694 }
1695
David Neto22f144c2017-06-12 14:26:21 -04001696 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001697 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001698
1699 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001700 if (is4xi8vec(CstTy)) {
1701 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001702 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001703 }
1704 }
1705
1706 if (Cst->getNumOperands()) {
1707 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1708 ++I) {
1709 FindConstant(*I);
1710 }
1711
David Netofb9a7972017-08-25 17:08:24 -04001712 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001713 return;
1714 } else if (const ConstantDataSequential *CDS =
1715 dyn_cast<ConstantDataSequential>(Cst)) {
1716 // Add constants for each element to constant list.
1717 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1718 Constant *EleCst = CDS->getElementAsConstant(i);
1719 FindConstant(EleCst);
1720 }
1721 }
1722
1723 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001724 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001725 }
1726}
1727
1728spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1729 switch (AddrSpace) {
1730 default:
1731 llvm_unreachable("Unsupported OpenCL address space");
1732 case AddressSpace::Private:
1733 return spv::StorageClassFunction;
1734 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001735 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001736 case AddressSpace::Constant:
1737 return clspv::Option::ConstantArgsInUniformBuffer()
1738 ? spv::StorageClassUniform
1739 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001740 case AddressSpace::Input:
1741 return spv::StorageClassInput;
1742 case AddressSpace::Local:
1743 return spv::StorageClassWorkgroup;
1744 case AddressSpace::UniformConstant:
1745 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001746 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001747 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001748 case AddressSpace::ModuleScopePrivate:
1749 return spv::StorageClassPrivate;
1750 }
1751}
1752
David Neto862b7d82018-06-14 18:48:37 -04001753spv::StorageClass
1754SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1755 switch (arg_kind) {
1756 case clspv::ArgKind::Buffer:
1757 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001758 case clspv::ArgKind::BufferUBO:
1759 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001760 case clspv::ArgKind::Pod:
1761 return clspv::Option::PodArgsInUniformBuffer()
1762 ? spv::StorageClassUniform
1763 : spv::StorageClassStorageBuffer;
1764 case clspv::ArgKind::Local:
1765 return spv::StorageClassWorkgroup;
1766 case clspv::ArgKind::ReadOnlyImage:
1767 case clspv::ArgKind::WriteOnlyImage:
1768 case clspv::ArgKind::Sampler:
1769 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001770 default:
1771 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001772 }
1773}
1774
David Neto22f144c2017-06-12 14:26:21 -04001775spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1776 return StringSwitch<spv::BuiltIn>(Name)
1777 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1778 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1779 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1780 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1781 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1782 .Default(spv::BuiltInMax);
1783}
1784
1785void SPIRVProducerPass::GenerateExtInstImport() {
1786 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1787 uint32_t &ExtInstImportID = getOpExtInstImportID();
1788
1789 //
1790 // Generate OpExtInstImport.
1791 //
1792 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001793 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001794 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1795 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001796}
1797
alan-bakerb6b09dc2018-11-08 16:59:28 -05001798void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1799 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001800 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1801 ValueMapType &VMap = getValueMap();
1802 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001803 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001804
1805 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1806 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1807 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1808
1809 for (Type *Ty : getTypeList()) {
1810 // Update TypeMap with nextID for reference later.
1811 TypeMap[Ty] = nextID;
1812
1813 switch (Ty->getTypeID()) {
1814 default: {
1815 Ty->print(errs());
1816 llvm_unreachable("Unsupported type???");
1817 break;
1818 }
1819 case Type::MetadataTyID:
1820 case Type::LabelTyID: {
1821 // Ignore these types.
1822 break;
1823 }
1824 case Type::PointerTyID: {
1825 PointerType *PTy = cast<PointerType>(Ty);
1826 unsigned AddrSpace = PTy->getAddressSpace();
1827
1828 // For the purposes of our Vulkan SPIR-V type system, constant and global
1829 // are conflated.
1830 bool UseExistingOpTypePointer = false;
1831 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001832 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1833 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001834 // Check to see if we already created this type (for instance, if we
1835 // had a constant <type>* and a global <type>*, the type would be
1836 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001837 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1838 if (0 < TypeMap.count(GlobalTy)) {
1839 TypeMap[PTy] = TypeMap[GlobalTy];
1840 UseExistingOpTypePointer = true;
1841 break;
1842 }
David Neto22f144c2017-06-12 14:26:21 -04001843 }
1844 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001845 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1846 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001847
alan-bakerb6b09dc2018-11-08 16:59:28 -05001848 // Check to see if we already created this type (for instance, if we
1849 // had a constant <type>* and a global <type>*, the type would be
1850 // created by one of these types, and shared by both).
1851 auto ConstantTy =
1852 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001853 if (0 < TypeMap.count(ConstantTy)) {
1854 TypeMap[PTy] = TypeMap[ConstantTy];
1855 UseExistingOpTypePointer = true;
1856 }
David Neto22f144c2017-06-12 14:26:21 -04001857 }
1858 }
1859
David Neto862b7d82018-06-14 18:48:37 -04001860 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001861
David Neto862b7d82018-06-14 18:48:37 -04001862 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001863 //
1864 // Generate OpTypePointer.
1865 //
1866
1867 // OpTypePointer
1868 // Ops[0] = Storage Class
1869 // Ops[1] = Element Type ID
1870 SPIRVOperandList Ops;
1871
David Neto257c3892018-04-11 13:19:45 -04001872 Ops << MkNum(GetStorageClass(AddrSpace))
1873 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001874
David Neto87846742018-04-11 17:36:22 -04001875 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001876 SPIRVInstList.push_back(Inst);
1877 }
David Neto22f144c2017-06-12 14:26:21 -04001878 break;
1879 }
1880 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001881 StructType *STy = cast<StructType>(Ty);
1882
1883 // Handle sampler type.
1884 if (STy->isOpaque()) {
1885 if (STy->getName().equals("opencl.sampler_t")) {
1886 //
1887 // Generate OpTypeSampler
1888 //
1889 // Empty Ops.
1890 SPIRVOperandList Ops;
1891
David Neto87846742018-04-11 17:36:22 -04001892 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001893 SPIRVInstList.push_back(Inst);
1894 break;
1895 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1896 STy->getName().equals("opencl.image2d_wo_t") ||
1897 STy->getName().equals("opencl.image3d_ro_t") ||
1898 STy->getName().equals("opencl.image3d_wo_t")) {
1899 //
1900 // Generate OpTypeImage
1901 //
1902 // Ops[0] = Sampled Type ID
1903 // Ops[1] = Dim ID
1904 // Ops[2] = Depth (Literal Number)
1905 // Ops[3] = Arrayed (Literal Number)
1906 // Ops[4] = MS (Literal Number)
1907 // Ops[5] = Sampled (Literal Number)
1908 // Ops[6] = Image Format ID
1909 //
1910 SPIRVOperandList Ops;
1911
1912 // TODO: Changed Sampled Type according to situations.
1913 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001914 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001915
1916 spv::Dim DimID = spv::Dim2D;
1917 if (STy->getName().equals("opencl.image3d_ro_t") ||
1918 STy->getName().equals("opencl.image3d_wo_t")) {
1919 DimID = spv::Dim3D;
1920 }
David Neto257c3892018-04-11 13:19:45 -04001921 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001922
1923 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001924 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001925
1926 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001927 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001928
1929 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001930 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001931
1932 // TODO: Set up Sampled.
1933 //
1934 // From Spec
1935 //
1936 // 0 indicates this is only known at run time, not at compile time
1937 // 1 indicates will be used with sampler
1938 // 2 indicates will be used without a sampler (a storage image)
1939 uint32_t Sampled = 1;
1940 if (STy->getName().equals("opencl.image2d_wo_t") ||
1941 STy->getName().equals("opencl.image3d_wo_t")) {
1942 Sampled = 2;
1943 }
David Neto257c3892018-04-11 13:19:45 -04001944 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001945
1946 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001947 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001948
David Neto87846742018-04-11 17:36:22 -04001949 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001950 SPIRVInstList.push_back(Inst);
1951 break;
1952 }
1953 }
1954
1955 //
1956 // Generate OpTypeStruct
1957 //
1958 // Ops[0] ... Ops[n] = Member IDs
1959 SPIRVOperandList Ops;
1960
1961 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001962 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001963 }
1964
David Neto22f144c2017-06-12 14:26:21 -04001965 uint32_t STyID = nextID;
1966
alan-bakerb6b09dc2018-11-08 16:59:28 -05001967 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001968 SPIRVInstList.push_back(Inst);
1969
1970 // Generate OpMemberDecorate.
1971 auto DecoInsertPoint =
1972 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1973 [](SPIRVInstruction *Inst) -> bool {
1974 return Inst->getOpcode() != spv::OpDecorate &&
1975 Inst->getOpcode() != spv::OpMemberDecorate &&
1976 Inst->getOpcode() != spv::OpExtInstImport;
1977 });
1978
David Netoc463b372017-08-10 15:32:21 -04001979 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001980 // Search for the correct offsets if this type was remapped.
1981 std::vector<uint32_t> *offsets = nullptr;
1982 auto iter = RemappedUBOTypeOffsets.find(STy);
1983 if (iter != RemappedUBOTypeOffsets.end()) {
1984 offsets = &iter->second;
1985 }
David Netoc463b372017-08-10 15:32:21 -04001986
David Neto862b7d82018-06-14 18:48:37 -04001987 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001988 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1989 MemberIdx++) {
1990 // Ops[0] = Structure Type ID
1991 // Ops[1] = Member Index(Literal Number)
1992 // Ops[2] = Decoration (Offset)
1993 // Ops[3] = Byte Offset (Literal Number)
1994 Ops.clear();
1995
David Neto257c3892018-04-11 13:19:45 -04001996 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001997
alan-bakerb6b09dc2018-11-08 16:59:28 -05001998 auto ByteOffset =
1999 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04002000 if (offsets) {
2001 ByteOffset = (*offsets)[MemberIdx];
2002 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05002003 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04002004 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04002005 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04002006
David Neto87846742018-04-11 17:36:22 -04002007 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002008 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002009 }
2010
2011 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04002012 if (StructTypesNeedingBlock.idFor(STy)) {
2013 Ops.clear();
2014 // Use Block decorations with StorageBuffer storage class.
2015 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002016
David Neto862b7d82018-06-14 18:48:37 -04002017 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2018 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002019 }
2020 break;
2021 }
2022 case Type::IntegerTyID: {
2023 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2024
2025 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002026 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002027 SPIRVInstList.push_back(Inst);
2028 } else {
2029 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002030 // No matter what LLVM type is requested first, always alias the
2031 // second one's SPIR-V type to be the same as the one we generated
2032 // first.
Neil Henning39672102017-09-29 14:33:13 +01002033 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002034 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002035 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002036 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002037 } else if (BitWidth == 32) {
2038 aliasToWidth = 8;
2039 }
2040 if (aliasToWidth) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002041 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
David Neto391aeb12017-08-26 15:51:58 -04002042 auto where = TypeMap.find(otherType);
2043 if (where == TypeMap.end()) {
2044 // Go ahead and make it, but also map the other type to it.
2045 TypeMap[otherType] = nextID;
2046 } else {
2047 // Alias this SPIR-V type the existing type.
2048 TypeMap[Ty] = where->second;
2049 break;
2050 }
David Neto22f144c2017-06-12 14:26:21 -04002051 }
2052
David Neto257c3892018-04-11 13:19:45 -04002053 SPIRVOperandList Ops;
2054 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002055
2056 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002057 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002058 }
2059 break;
2060 }
2061 case Type::HalfTyID:
2062 case Type::FloatTyID:
2063 case Type::DoubleTyID: {
2064 SPIRVOperand *WidthOp = new SPIRVOperand(
2065 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2066
2067 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002068 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002069 break;
2070 }
2071 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002072 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002073 const uint64_t Length = ArrTy->getArrayNumElements();
2074 if (Length == 0) {
2075 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002076
David Neto862b7d82018-06-14 18:48:37 -04002077 // Only generate the type once.
2078 // TODO(dneto): Can it ever be generated more than once?
2079 // Doesn't LLVM type uniqueness guarantee we'll only see this
2080 // once?
2081 Type *EleTy = ArrTy->getArrayElementType();
2082 if (OpRuntimeTyMap.count(EleTy) == 0) {
2083 uint32_t OpTypeRuntimeArrayID = nextID;
2084 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002085
David Neto862b7d82018-06-14 18:48:37 -04002086 //
2087 // Generate OpTypeRuntimeArray.
2088 //
David Neto22f144c2017-06-12 14:26:21 -04002089
David Neto862b7d82018-06-14 18:48:37 -04002090 // OpTypeRuntimeArray
2091 // Ops[0] = Element Type ID
2092 SPIRVOperandList Ops;
2093 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002094
David Neto862b7d82018-06-14 18:48:37 -04002095 SPIRVInstList.push_back(
2096 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002097
David Neto862b7d82018-06-14 18:48:37 -04002098 if (Hack_generate_runtime_array_stride_early) {
2099 // Generate OpDecorate.
2100 auto DecoInsertPoint = std::find_if(
2101 SPIRVInstList.begin(), SPIRVInstList.end(),
2102 [](SPIRVInstruction *Inst) -> bool {
2103 return Inst->getOpcode() != spv::OpDecorate &&
2104 Inst->getOpcode() != spv::OpMemberDecorate &&
2105 Inst->getOpcode() != spv::OpExtInstImport;
2106 });
David Neto22f144c2017-06-12 14:26:21 -04002107
David Neto862b7d82018-06-14 18:48:37 -04002108 // Ops[0] = Target ID
2109 // Ops[1] = Decoration (ArrayStride)
2110 // Ops[2] = Stride Number(Literal Number)
2111 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002112
David Neto862b7d82018-06-14 18:48:37 -04002113 Ops << MkId(OpTypeRuntimeArrayID)
2114 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002115 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002116
David Neto862b7d82018-06-14 18:48:37 -04002117 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2118 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2119 }
2120 }
David Neto22f144c2017-06-12 14:26:21 -04002121
David Neto862b7d82018-06-14 18:48:37 -04002122 } else {
David Neto22f144c2017-06-12 14:26:21 -04002123
David Neto862b7d82018-06-14 18:48:37 -04002124 //
2125 // Generate OpConstant and OpTypeArray.
2126 //
2127
2128 //
2129 // Generate OpConstant for array length.
2130 //
2131 // Ops[0] = Result Type ID
2132 // Ops[1] .. Ops[n] = Values LiteralNumber
2133 SPIRVOperandList Ops;
2134
2135 Type *LengthTy = Type::getInt32Ty(Context);
2136 uint32_t ResTyID = lookupType(LengthTy);
2137 Ops << MkId(ResTyID);
2138
2139 assert(Length < UINT32_MAX);
2140 Ops << MkNum(static_cast<uint32_t>(Length));
2141
2142 // Add constant for length to constant list.
2143 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2144 AllocatedVMap[CstLength] = nextID;
2145 VMap[CstLength] = nextID;
2146 uint32_t LengthID = nextID;
2147
2148 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2149 SPIRVInstList.push_back(CstInst);
2150
2151 // Remember to generate ArrayStride later
2152 getTypesNeedingArrayStride().insert(Ty);
2153
2154 //
2155 // Generate OpTypeArray.
2156 //
2157 // Ops[0] = Element Type ID
2158 // Ops[1] = Array Length Constant ID
2159 Ops.clear();
2160
2161 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2162 Ops << MkId(EleTyID) << MkId(LengthID);
2163
2164 // Update TypeMap with nextID.
2165 TypeMap[Ty] = nextID;
2166
2167 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2168 SPIRVInstList.push_back(ArrayInst);
2169 }
David Neto22f144c2017-06-12 14:26:21 -04002170 break;
2171 }
2172 case Type::VectorTyID: {
2173 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002174 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2175 if (Ty->getVectorNumElements() == 4) {
2176 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2177 break;
2178 } else {
2179 Ty->print(errs());
2180 llvm_unreachable("Support above i8 vector type");
2181 }
2182 }
2183
2184 // Ops[0] = Component Type ID
2185 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002186 SPIRVOperandList Ops;
2187 Ops << MkId(lookupType(Ty->getVectorElementType()))
2188 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002189
alan-bakerb6b09dc2018-11-08 16:59:28 -05002190 SPIRVInstruction *inst =
2191 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002192 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002193 break;
2194 }
2195 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002196 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002197 SPIRVInstList.push_back(Inst);
2198 break;
2199 }
2200 case Type::FunctionTyID: {
2201 // Generate SPIRV instruction for function type.
2202 FunctionType *FTy = cast<FunctionType>(Ty);
2203
2204 // Ops[0] = Return Type ID
2205 // Ops[1] ... Ops[n] = Parameter Type IDs
2206 SPIRVOperandList Ops;
2207
2208 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002209 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002210
2211 // Find SPIRV instructions for parameter types
2212 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2213 // Find SPIRV instruction for parameter type.
2214 auto ParamTy = FTy->getParamType(k);
2215 if (ParamTy->isPointerTy()) {
2216 auto PointeeTy = ParamTy->getPointerElementType();
2217 if (PointeeTy->isStructTy() &&
2218 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2219 ParamTy = PointeeTy;
2220 }
2221 }
2222
David Netoc6f3ab22018-04-06 18:02:31 -04002223 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002224 }
2225
David Neto87846742018-04-11 17:36:22 -04002226 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002227 SPIRVInstList.push_back(Inst);
2228 break;
2229 }
2230 }
2231 }
2232
2233 // Generate OpTypeSampledImage.
2234 TypeMapType &OpImageTypeMap = getImageTypeMap();
2235 for (auto &ImageType : OpImageTypeMap) {
2236 //
2237 // Generate OpTypeSampledImage.
2238 //
2239 // Ops[0] = Image Type ID
2240 //
2241 SPIRVOperandList Ops;
2242
2243 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002244 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002245
2246 // Update OpImageTypeMap.
2247 ImageType.second = nextID;
2248
David Neto87846742018-04-11 17:36:22 -04002249 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002250 SPIRVInstList.push_back(Inst);
2251 }
David Netoc6f3ab22018-04-06 18:02:31 -04002252
2253 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002254 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2255 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002256 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002257
2258 // Generate the spec constant.
2259 SPIRVOperandList Ops;
2260 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002261 SPIRVInstList.push_back(
2262 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002263
2264 // Generate the array type.
2265 Ops.clear();
2266 // The element type must have been created.
2267 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2268 assert(elem_ty_id);
2269 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2270
2271 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002272 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002273
2274 Ops.clear();
2275 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002276 SPIRVInstList.push_back(new SPIRVInstruction(
2277 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002278 }
David Neto22f144c2017-06-12 14:26:21 -04002279}
2280
2281void SPIRVProducerPass::GenerateSPIRVConstants() {
2282 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2283 ValueMapType &VMap = getValueMap();
2284 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2285 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002286 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002287
2288 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002289 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002290 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002291
2292 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002293 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002294 continue;
2295 }
2296
David Netofb9a7972017-08-25 17:08:24 -04002297 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002298 VMap[Cst] = nextID;
2299
2300 //
2301 // Generate OpConstant.
2302 //
2303
2304 // Ops[0] = Result Type ID
2305 // Ops[1] .. Ops[n] = Values LiteralNumber
2306 SPIRVOperandList Ops;
2307
David Neto257c3892018-04-11 13:19:45 -04002308 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002309
2310 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002311 spv::Op Opcode = spv::OpNop;
2312
2313 if (isa<UndefValue>(Cst)) {
2314 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002315 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002316 if (hack_undef && IsTypeNullable(Cst->getType())) {
2317 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002318 }
David Neto22f144c2017-06-12 14:26:21 -04002319 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2320 unsigned BitWidth = CI->getBitWidth();
2321 if (BitWidth == 1) {
2322 // If the bitwidth of constant is 1, generate OpConstantTrue or
2323 // OpConstantFalse.
2324 if (CI->getZExtValue()) {
2325 // Ops[0] = Result Type ID
2326 Opcode = spv::OpConstantTrue;
2327 } else {
2328 // Ops[0] = Result Type ID
2329 Opcode = spv::OpConstantFalse;
2330 }
David Neto22f144c2017-06-12 14:26:21 -04002331 } else {
2332 auto V = CI->getZExtValue();
2333 LiteralNum.push_back(V & 0xFFFFFFFF);
2334
2335 if (BitWidth > 32) {
2336 LiteralNum.push_back(V >> 32);
2337 }
2338
2339 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002340
David Neto257c3892018-04-11 13:19:45 -04002341 Ops << MkInteger(LiteralNum);
2342
2343 if (BitWidth == 32 && V == 0) {
2344 constant_i32_zero_id_ = nextID;
2345 }
David Neto22f144c2017-06-12 14:26:21 -04002346 }
2347 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2348 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2349 Type *CFPTy = CFP->getType();
2350 if (CFPTy->isFloatTy()) {
2351 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2352 } else {
2353 CFPTy->print(errs());
2354 llvm_unreachable("Implement this ConstantFP Type");
2355 }
2356
2357 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002358
David Neto257c3892018-04-11 13:19:45 -04002359 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002360 } else if (isa<ConstantDataSequential>(Cst) &&
2361 cast<ConstantDataSequential>(Cst)->isString()) {
2362 Cst->print(errs());
2363 llvm_unreachable("Implement this Constant");
2364
2365 } else if (const ConstantDataSequential *CDS =
2366 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002367 // Let's convert <4 x i8> constant to int constant specially.
2368 // This case occurs when all the values are specified as constant
2369 // ints.
2370 Type *CstTy = Cst->getType();
2371 if (is4xi8vec(CstTy)) {
2372 LLVMContext &Context = CstTy->getContext();
2373
2374 //
2375 // Generate OpConstant with OpTypeInt 32 0.
2376 //
Neil Henning39672102017-09-29 14:33:13 +01002377 uint32_t IntValue = 0;
2378 for (unsigned k = 0; k < 4; k++) {
2379 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002380 IntValue = (IntValue << 8) | (Val & 0xffu);
2381 }
2382
2383 Type *i32 = Type::getInt32Ty(Context);
2384 Constant *CstInt = ConstantInt::get(i32, IntValue);
2385 // If this constant is already registered on VMap, use it.
2386 if (VMap.count(CstInt)) {
2387 uint32_t CstID = VMap[CstInt];
2388 VMap[Cst] = CstID;
2389 continue;
2390 }
2391
David Neto257c3892018-04-11 13:19:45 -04002392 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002393
David Neto87846742018-04-11 17:36:22 -04002394 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002395 SPIRVInstList.push_back(CstInst);
2396
2397 continue;
2398 }
2399
2400 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002401 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2402 Constant *EleCst = CDS->getElementAsConstant(k);
2403 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002404 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002405 }
2406
2407 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002408 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2409 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002410 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002411 Type *CstTy = Cst->getType();
2412 if (is4xi8vec(CstTy)) {
2413 LLVMContext &Context = CstTy->getContext();
2414
2415 //
2416 // Generate OpConstant with OpTypeInt 32 0.
2417 //
Neil Henning39672102017-09-29 14:33:13 +01002418 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002419 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2420 I != E; ++I) {
2421 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002422 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002423 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2424 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002425 }
David Neto49351ac2017-08-26 17:32:20 -04002426 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002427 }
2428
David Neto49351ac2017-08-26 17:32:20 -04002429 Type *i32 = Type::getInt32Ty(Context);
2430 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002431 // If this constant is already registered on VMap, use it.
2432 if (VMap.count(CstInt)) {
2433 uint32_t CstID = VMap[CstInt];
2434 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002435 continue;
David Neto22f144c2017-06-12 14:26:21 -04002436 }
2437
David Neto257c3892018-04-11 13:19:45 -04002438 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002439
David Neto87846742018-04-11 17:36:22 -04002440 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002441 SPIRVInstList.push_back(CstInst);
2442
David Neto19a1bad2017-08-25 15:01:41 -04002443 continue;
David Neto22f144c2017-06-12 14:26:21 -04002444 }
2445
2446 // We use a constant composite in SPIR-V for our constant aggregate in
2447 // LLVM.
2448 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002449
2450 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2451 // Look up the ID of the element of this aggregate (which we will
2452 // previously have created a constant for).
2453 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2454
2455 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002456 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002457 }
2458 } else if (Cst->isNullValue()) {
2459 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002460 } else {
2461 Cst->print(errs());
2462 llvm_unreachable("Unsupported Constant???");
2463 }
2464
alan-baker5b86ed72019-02-15 08:26:50 -05002465 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2466 // Null pointer requires variable pointers.
2467 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2468 }
2469
David Neto87846742018-04-11 17:36:22 -04002470 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002471 SPIRVInstList.push_back(CstInst);
2472 }
2473}
2474
2475void SPIRVProducerPass::GenerateSamplers(Module &M) {
2476 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002477
alan-bakerb6b09dc2018-11-08 16:59:28 -05002478 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002479 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002480 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002481 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2482 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002483
David Neto862b7d82018-06-14 18:48:37 -04002484 // We might have samplers in the sampler map that are not used
2485 // in the translation unit. We need to allocate variables
2486 // for them and bindings too.
2487 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002488
alan-bakerb6b09dc2018-11-08 16:59:28 -05002489 auto *var_fn = M.getFunction("clspv.sampler.var.literal");
2490 if (!var_fn)
2491 return;
David Neto862b7d82018-06-14 18:48:37 -04002492 for (auto user : var_fn->users()) {
2493 // Populate SamplerLiteralToDescriptorSetMap and
2494 // SamplerLiteralToBindingMap.
2495 //
2496 // Look for calls like
2497 // call %opencl.sampler_t addrspace(2)*
2498 // @clspv.sampler.var.literal(
2499 // i32 descriptor,
2500 // i32 binding,
2501 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002502 if (auto *call = dyn_cast<CallInst>(user)) {
2503 const size_t index_into_sampler_map = static_cast<size_t>(
2504 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002505 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002506 errs() << "Out of bounds index to sampler map: "
2507 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002508 llvm_unreachable("bad sampler init: out of bounds");
2509 }
2510
2511 auto sampler_value = sampler_map[index_into_sampler_map].first;
2512 const auto descriptor_set = static_cast<unsigned>(
2513 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2514 const auto binding = static_cast<unsigned>(
2515 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2516
2517 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2518 SamplerLiteralToBindingMap[sampler_value] = binding;
2519 used_bindings.insert(binding);
2520 }
2521 }
2522
2523 unsigned index = 0;
2524 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002525 // Generate OpVariable.
2526 //
2527 // GIDOps[0] : Result Type ID
2528 // GIDOps[1] : Storage Class
2529 SPIRVOperandList Ops;
2530
David Neto257c3892018-04-11 13:19:45 -04002531 Ops << MkId(lookupType(SamplerTy))
2532 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002533
David Neto862b7d82018-06-14 18:48:37 -04002534 auto sampler_var_id = nextID++;
2535 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002536 SPIRVInstList.push_back(Inst);
2537
David Neto862b7d82018-06-14 18:48:37 -04002538 SamplerMapIndexToIDMap[index] = sampler_var_id;
2539 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002540
2541 // Find Insert Point for OpDecorate.
2542 auto DecoInsertPoint =
2543 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2544 [](SPIRVInstruction *Inst) -> bool {
2545 return Inst->getOpcode() != spv::OpDecorate &&
2546 Inst->getOpcode() != spv::OpMemberDecorate &&
2547 Inst->getOpcode() != spv::OpExtInstImport;
2548 });
2549
2550 // Ops[0] = Target ID
2551 // Ops[1] = Decoration (DescriptorSet)
2552 // Ops[2] = LiteralNumber according to Decoration
2553 Ops.clear();
2554
David Neto862b7d82018-06-14 18:48:37 -04002555 unsigned descriptor_set;
2556 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002557 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2558 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002559 // This sampler is not actually used. Find the next one.
2560 for (binding = 0; used_bindings.count(binding); binding++)
2561 ;
2562 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2563 used_bindings.insert(binding);
2564 } else {
2565 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2566 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2567 }
2568
2569 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2570 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002571
alan-bakerf5e5f692018-11-27 08:33:24 -05002572 version0::DescriptorMapEntry::SamplerData sampler_data = {SamplerLiteral.first};
2573 descriptorMapEntries->emplace_back(std::move(sampler_data), descriptor_set, binding);
David Neto22f144c2017-06-12 14:26:21 -04002574
David Neto87846742018-04-11 17:36:22 -04002575 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002576 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2577
2578 // Ops[0] = Target ID
2579 // Ops[1] = Decoration (Binding)
2580 // Ops[2] = LiteralNumber according to Decoration
2581 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002582 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2583 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002584
David Neto87846742018-04-11 17:36:22 -04002585 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002586 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002587
2588 index++;
David Neto22f144c2017-06-12 14:26:21 -04002589 }
David Neto862b7d82018-06-14 18:48:37 -04002590}
David Neto22f144c2017-06-12 14:26:21 -04002591
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002592void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002593 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2594 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002595
David Neto862b7d82018-06-14 18:48:37 -04002596 // Generate variables. Make one for each of resource var info object.
2597 for (auto *info : ModuleOrderedResourceVars) {
2598 Type *type = info->var_fn->getReturnType();
2599 // Remap the address space for opaque types.
2600 switch (info->arg_kind) {
2601 case clspv::ArgKind::Sampler:
2602 case clspv::ArgKind::ReadOnlyImage:
2603 case clspv::ArgKind::WriteOnlyImage:
2604 type = PointerType::get(type->getPointerElementType(),
2605 clspv::AddressSpace::UniformConstant);
2606 break;
2607 default:
2608 break;
2609 }
David Neto22f144c2017-06-12 14:26:21 -04002610
David Neto862b7d82018-06-14 18:48:37 -04002611 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002612
David Neto862b7d82018-06-14 18:48:37 -04002613 const auto type_id = lookupType(type);
2614 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2615 SPIRVOperandList Ops;
2616 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002617
David Neto862b7d82018-06-14 18:48:37 -04002618 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2619 SPIRVInstList.push_back(Inst);
2620
2621 // Map calls to the variable-builtin-function.
2622 for (auto &U : info->var_fn->uses()) {
2623 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2624 const auto set = unsigned(
2625 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2626 const auto binding = unsigned(
2627 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2628 if (set == info->descriptor_set && binding == info->binding) {
2629 switch (info->arg_kind) {
2630 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002631 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002632 case clspv::ArgKind::Pod:
2633 // The call maps to the variable directly.
2634 VMap[call] = info->var_id;
2635 break;
2636 case clspv::ArgKind::Sampler:
2637 case clspv::ArgKind::ReadOnlyImage:
2638 case clspv::ArgKind::WriteOnlyImage:
2639 // The call maps to a load we generate later.
2640 ResourceVarDeferredLoadCalls[call] = info->var_id;
2641 break;
2642 default:
2643 llvm_unreachable("Unhandled arg kind");
2644 }
2645 }
David Neto22f144c2017-06-12 14:26:21 -04002646 }
David Neto862b7d82018-06-14 18:48:37 -04002647 }
2648 }
David Neto22f144c2017-06-12 14:26:21 -04002649
David Neto862b7d82018-06-14 18:48:37 -04002650 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002651
David Neto862b7d82018-06-14 18:48:37 -04002652 // Find Insert Point for OpDecorate.
2653 auto DecoInsertPoint =
2654 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2655 [](SPIRVInstruction *Inst) -> bool {
2656 return Inst->getOpcode() != spv::OpDecorate &&
2657 Inst->getOpcode() != spv::OpMemberDecorate &&
2658 Inst->getOpcode() != spv::OpExtInstImport;
2659 });
2660
2661 SPIRVOperandList Ops;
2662 for (auto *info : ModuleOrderedResourceVars) {
2663 // Decorate with DescriptorSet and Binding.
2664 Ops.clear();
2665 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2666 << MkNum(info->descriptor_set);
2667 SPIRVInstList.insert(DecoInsertPoint,
2668 new SPIRVInstruction(spv::OpDecorate, Ops));
2669
2670 Ops.clear();
2671 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2672 << MkNum(info->binding);
2673 SPIRVInstList.insert(DecoInsertPoint,
2674 new SPIRVInstruction(spv::OpDecorate, Ops));
2675
2676 // Generate NonWritable and NonReadable
2677 switch (info->arg_kind) {
2678 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002679 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002680 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2681 clspv::AddressSpace::Constant) {
2682 Ops.clear();
2683 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2684 SPIRVInstList.insert(DecoInsertPoint,
2685 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002686 }
David Neto862b7d82018-06-14 18:48:37 -04002687 break;
2688 case clspv::ArgKind::ReadOnlyImage:
2689 Ops.clear();
2690 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2691 SPIRVInstList.insert(DecoInsertPoint,
2692 new SPIRVInstruction(spv::OpDecorate, Ops));
2693 break;
2694 case clspv::ArgKind::WriteOnlyImage:
2695 Ops.clear();
2696 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2697 SPIRVInstList.insert(DecoInsertPoint,
2698 new SPIRVInstruction(spv::OpDecorate, Ops));
2699 break;
2700 default:
2701 break;
David Neto22f144c2017-06-12 14:26:21 -04002702 }
2703 }
2704}
2705
2706void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002707 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002708 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2709 ValueMapType &VMap = getValueMap();
2710 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002711 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002712
2713 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2714 Type *Ty = GV.getType();
2715 PointerType *PTy = cast<PointerType>(Ty);
2716
2717 uint32_t InitializerID = 0;
2718
2719 // Workgroup size is handled differently (it goes into a constant)
2720 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2721 std::vector<bool> HasMDVec;
2722 uint32_t PrevXDimCst = 0xFFFFFFFF;
2723 uint32_t PrevYDimCst = 0xFFFFFFFF;
2724 uint32_t PrevZDimCst = 0xFFFFFFFF;
2725 for (Function &Func : *GV.getParent()) {
2726 if (Func.isDeclaration()) {
2727 continue;
2728 }
2729
2730 // We only need to check kernels.
2731 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2732 continue;
2733 }
2734
2735 if (const MDNode *MD =
2736 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2737 uint32_t CurXDimCst = static_cast<uint32_t>(
2738 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2739 uint32_t CurYDimCst = static_cast<uint32_t>(
2740 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2741 uint32_t CurZDimCst = static_cast<uint32_t>(
2742 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2743
2744 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2745 PrevZDimCst == 0xFFFFFFFF) {
2746 PrevXDimCst = CurXDimCst;
2747 PrevYDimCst = CurYDimCst;
2748 PrevZDimCst = CurZDimCst;
2749 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2750 CurZDimCst != PrevZDimCst) {
2751 llvm_unreachable(
2752 "reqd_work_group_size must be the same across all kernels");
2753 } else {
2754 continue;
2755 }
2756
2757 //
2758 // Generate OpConstantComposite.
2759 //
2760 // Ops[0] : Result Type ID
2761 // Ops[1] : Constant size for x dimension.
2762 // Ops[2] : Constant size for y dimension.
2763 // Ops[3] : Constant size for z dimension.
2764 SPIRVOperandList Ops;
2765
2766 uint32_t XDimCstID =
2767 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2768 uint32_t YDimCstID =
2769 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2770 uint32_t ZDimCstID =
2771 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2772
2773 InitializerID = nextID;
2774
David Neto257c3892018-04-11 13:19:45 -04002775 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2776 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002777
David Neto87846742018-04-11 17:36:22 -04002778 auto *Inst =
2779 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002780 SPIRVInstList.push_back(Inst);
2781
2782 HasMDVec.push_back(true);
2783 } else {
2784 HasMDVec.push_back(false);
2785 }
2786 }
2787
2788 // Check all kernels have same definitions for work_group_size.
2789 bool HasMD = false;
2790 if (!HasMDVec.empty()) {
2791 HasMD = HasMDVec[0];
2792 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2793 if (HasMD != HasMDVec[i]) {
2794 llvm_unreachable(
2795 "Kernels should have consistent work group size definition");
2796 }
2797 }
2798 }
2799
2800 // If all kernels do not have metadata for reqd_work_group_size, generate
2801 // OpSpecConstants for x/y/z dimension.
2802 if (!HasMD) {
2803 //
2804 // Generate OpSpecConstants for x/y/z dimension.
2805 //
2806 // Ops[0] : Result Type ID
2807 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2808 uint32_t XDimCstID = 0;
2809 uint32_t YDimCstID = 0;
2810 uint32_t ZDimCstID = 0;
2811
David Neto22f144c2017-06-12 14:26:21 -04002812 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002813 uint32_t result_type_id =
2814 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002815
David Neto257c3892018-04-11 13:19:45 -04002816 // X Dimension
2817 Ops << MkId(result_type_id) << MkNum(1);
2818 XDimCstID = nextID++;
2819 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002820 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002821
2822 // Y Dimension
2823 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002824 Ops << MkId(result_type_id) << MkNum(1);
2825 YDimCstID = nextID++;
2826 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002827 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002828
2829 // Z Dimension
2830 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002831 Ops << MkId(result_type_id) << MkNum(1);
2832 ZDimCstID = nextID++;
2833 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002834 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002835
David Neto257c3892018-04-11 13:19:45 -04002836 BuiltinDimVec.push_back(XDimCstID);
2837 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002838 BuiltinDimVec.push_back(ZDimCstID);
2839
David Neto22f144c2017-06-12 14:26:21 -04002840 //
2841 // Generate OpSpecConstantComposite.
2842 //
2843 // Ops[0] : Result Type ID
2844 // Ops[1] : Constant size for x dimension.
2845 // Ops[2] : Constant size for y dimension.
2846 // Ops[3] : Constant size for z dimension.
2847 InitializerID = nextID;
2848
2849 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002850 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2851 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002852
David Neto87846742018-04-11 17:36:22 -04002853 auto *Inst =
2854 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002855 SPIRVInstList.push_back(Inst);
2856 }
2857 }
2858
David Neto22f144c2017-06-12 14:26:21 -04002859 VMap[&GV] = nextID;
2860
2861 //
2862 // Generate OpVariable.
2863 //
2864 // GIDOps[0] : Result Type ID
2865 // GIDOps[1] : Storage Class
2866 SPIRVOperandList Ops;
2867
David Neto85082642018-03-24 06:55:20 -07002868 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002869 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002870
David Neto85082642018-03-24 06:55:20 -07002871 if (GV.hasInitializer()) {
2872 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002873 }
2874
David Neto85082642018-03-24 06:55:20 -07002875 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002876 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002877 clspv::Option::ModuleConstantsInStorageBuffer();
2878
2879 if (0 != InitializerID) {
2880 if (!module_scope_constant_external_init) {
2881 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002882 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002883 }
2884 }
2885 const uint32_t var_id = nextID++;
2886
David Neto87846742018-04-11 17:36:22 -04002887 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002888 SPIRVInstList.push_back(Inst);
2889
2890 // If we have a builtin.
2891 if (spv::BuiltInMax != BuiltinType) {
2892 // Find Insert Point for OpDecorate.
2893 auto DecoInsertPoint =
2894 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2895 [](SPIRVInstruction *Inst) -> bool {
2896 return Inst->getOpcode() != spv::OpDecorate &&
2897 Inst->getOpcode() != spv::OpMemberDecorate &&
2898 Inst->getOpcode() != spv::OpExtInstImport;
2899 });
2900 //
2901 // Generate OpDecorate.
2902 //
2903 // DOps[0] = Target ID
2904 // DOps[1] = Decoration (Builtin)
2905 // DOps[2] = BuiltIn ID
2906 uint32_t ResultID;
2907
2908 // WorkgroupSize is different, we decorate the constant composite that has
2909 // its value, rather than the variable that we use to access the value.
2910 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2911 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002912 // Save both the value and variable IDs for later.
2913 WorkgroupSizeValueID = InitializerID;
2914 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002915 } else {
2916 ResultID = VMap[&GV];
2917 }
2918
2919 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002920 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2921 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002922
David Neto87846742018-04-11 17:36:22 -04002923 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002924 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002925 } else if (module_scope_constant_external_init) {
2926 // This module scope constant is initialized from a storage buffer with data
2927 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002928 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002929
David Neto862b7d82018-06-14 18:48:37 -04002930 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002931 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2932 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002933 std::string hexbytes;
2934 llvm::raw_string_ostream str(hexbytes);
2935 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
2936 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer, str.str()};
2937 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set, 0);
David Neto85082642018-03-24 06:55:20 -07002938
2939 // Find Insert Point for OpDecorate.
2940 auto DecoInsertPoint =
2941 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2942 [](SPIRVInstruction *Inst) -> bool {
2943 return Inst->getOpcode() != spv::OpDecorate &&
2944 Inst->getOpcode() != spv::OpMemberDecorate &&
2945 Inst->getOpcode() != spv::OpExtInstImport;
2946 });
2947
David Neto257c3892018-04-11 13:19:45 -04002948 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002949 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002950 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2951 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002952 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002953
2954 // OpDecorate %var DescriptorSet <descriptor_set>
2955 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002956 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2957 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002958 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002959 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002960 }
2961}
2962
David Netoc6f3ab22018-04-06 18:02:31 -04002963void SPIRVProducerPass::GenerateWorkgroupVars() {
2964 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002965 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2966 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002967 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002968
2969 // Generate OpVariable.
2970 //
2971 // GIDOps[0] : Result Type ID
2972 // GIDOps[1] : Storage Class
2973 SPIRVOperandList Ops;
2974 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2975
2976 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002977 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002978 }
2979}
2980
David Neto862b7d82018-06-14 18:48:37 -04002981void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2982 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002983 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2984 return;
2985 }
David Neto862b7d82018-06-14 18:48:37 -04002986 // Gather the list of resources that are used by this function's arguments.
2987 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2988
alan-bakerf5e5f692018-11-27 08:33:24 -05002989 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2990 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002991 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002992 std::string kind =
2993 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2994 ? "pod_ubo"
2995 : argKind;
2996 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002997 };
2998
2999 auto *fty = F.getType()->getPointerElementType();
3000 auto *func_ty = dyn_cast<FunctionType>(fty);
3001
3002 // If we've clustereed POD arguments, then argument details are in metadata.
3003 // If an argument maps to a resource variable, then get descriptor set and
3004 // binding from the resoure variable. Other info comes from the metadata.
3005 const auto *arg_map = F.getMetadata("kernel_arg_map");
3006 if (arg_map) {
3007 for (const auto &arg : arg_map->operands()) {
3008 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00003009 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04003010 const auto name =
3011 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
3012 const auto old_index =
3013 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
3014 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05003015 const size_t new_index = static_cast<size_t>(
3016 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04003017 const auto offset =
3018 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00003019 const auto arg_size =
3020 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003021 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003022 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003023 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003024 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05003025
3026 uint32_t descriptor_set = 0;
3027 uint32_t binding = 0;
3028 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3029 F.getName(),
3030 name,
3031 static_cast<uint32_t>(old_index),
3032 argKind,
3033 static_cast<uint32_t>(spec_id),
3034 // This will be set below for pointer-to-local args.
3035 0,
3036 static_cast<uint32_t>(offset),
3037 static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04003038 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05003039 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
3040 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
3041 DL));
David Neto862b7d82018-06-14 18:48:37 -04003042 } else {
3043 auto *info = resource_var_at_index[new_index];
3044 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05003045 descriptor_set = info->descriptor_set;
3046 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04003047 }
alan-bakerf5e5f692018-11-27 08:33:24 -05003048 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04003049 }
3050 } else {
3051 // There is no argument map.
3052 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003053 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003054
3055 SmallVector<Argument *, 4> arguments;
3056 for (auto &arg : F.args()) {
3057 arguments.push_back(&arg);
3058 }
3059
3060 unsigned arg_index = 0;
3061 for (auto *info : resource_var_at_index) {
3062 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003063 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05003064 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00003065 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05003066 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00003067 }
3068
alan-bakerf5e5f692018-11-27 08:33:24 -05003069 // Local pointer arguments are unused in this case. Offset is always zero.
3070 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3071 F.getName(), arg->getName(),
3072 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
3073 0, 0,
3074 0, arg_size};
3075 descriptorMapEntries->emplace_back(std::move(kernel_data),
3076 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04003077 }
3078 arg_index++;
3079 }
3080 // Generate mappings for pointer-to-local arguments.
3081 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3082 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003083 auto where = LocalArgSpecIds.find(arg);
3084 if (where != LocalArgSpecIds.end()) {
3085 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05003086 // Pod arguments members are unused in this case.
3087 version0::DescriptorMapEntry::KernelArgData kernel_data = {
3088 F.getName(),
3089 arg->getName(),
3090 arg_index,
3091 ArgKind::Local,
3092 static_cast<uint32_t>(local_arg_info.spec_id),
3093 static_cast<uint32_t>(GetTypeAllocSize(local_arg_info.elem_type, DL)),
3094 0,
3095 0};
3096 // Pointer-to-local arguments do not utilize descriptor set and binding.
3097 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003098 }
3099 }
3100 }
3101}
3102
David Neto22f144c2017-06-12 14:26:21 -04003103void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3104 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3105 ValueMapType &VMap = getValueMap();
3106 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003107 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3108 auto &GlobalConstArgSet = getGlobalConstArgSet();
3109
3110 FunctionType *FTy = F.getFunctionType();
3111
3112 //
David Neto22f144c2017-06-12 14:26:21 -04003113 // Generate OPFunction.
3114 //
3115
3116 // FOps[0] : Result Type ID
3117 // FOps[1] : Function Control
3118 // FOps[2] : Function Type ID
3119 SPIRVOperandList FOps;
3120
3121 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003122 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003123
3124 // Check function attributes for SPIRV Function Control.
3125 uint32_t FuncControl = spv::FunctionControlMaskNone;
3126 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3127 FuncControl |= spv::FunctionControlInlineMask;
3128 }
3129 if (F.hasFnAttribute(Attribute::NoInline)) {
3130 FuncControl |= spv::FunctionControlDontInlineMask;
3131 }
3132 // TODO: Check llvm attribute for Function Control Pure.
3133 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3134 FuncControl |= spv::FunctionControlPureMask;
3135 }
3136 // TODO: Check llvm attribute for Function Control Const.
3137 if (F.hasFnAttribute(Attribute::ReadNone)) {
3138 FuncControl |= spv::FunctionControlConstMask;
3139 }
3140
David Neto257c3892018-04-11 13:19:45 -04003141 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003142
3143 uint32_t FTyID;
3144 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3145 SmallVector<Type *, 4> NewFuncParamTys;
3146 FunctionType *NewFTy =
3147 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3148 FTyID = lookupType(NewFTy);
3149 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003150 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003151 if (GlobalConstFuncTyMap.count(FTy)) {
3152 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3153 } else {
3154 FTyID = lookupType(FTy);
3155 }
3156 }
3157
David Neto257c3892018-04-11 13:19:45 -04003158 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003159
3160 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3161 EntryPoints.push_back(std::make_pair(&F, nextID));
3162 }
3163
3164 VMap[&F] = nextID;
3165
David Neto482550a2018-03-24 05:21:07 -07003166 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003167 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3168 }
David Neto22f144c2017-06-12 14:26:21 -04003169 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003170 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003171 SPIRVInstList.push_back(FuncInst);
3172
3173 //
3174 // Generate OpFunctionParameter for Normal function.
3175 //
3176
3177 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3178 // Iterate Argument for name instead of param type from function type.
3179 unsigned ArgIdx = 0;
3180 for (Argument &Arg : F.args()) {
3181 VMap[&Arg] = nextID;
3182
3183 // ParamOps[0] : Result Type ID
3184 SPIRVOperandList ParamOps;
3185
3186 // Find SPIRV instruction for parameter type.
3187 uint32_t ParamTyID = lookupType(Arg.getType());
3188 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3189 if (GlobalConstFuncTyMap.count(FTy)) {
3190 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3191 Type *EleTy = PTy->getPointerElementType();
3192 Type *ArgTy =
3193 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3194 ParamTyID = lookupType(ArgTy);
3195 GlobalConstArgSet.insert(&Arg);
3196 }
3197 }
3198 }
David Neto257c3892018-04-11 13:19:45 -04003199 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003200
3201 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003202 auto *ParamInst =
3203 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003204 SPIRVInstList.push_back(ParamInst);
3205
3206 ArgIdx++;
3207 }
3208 }
3209}
3210
alan-bakerb6b09dc2018-11-08 16:59:28 -05003211void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003212 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3213 EntryPointVecType &EntryPoints = getEntryPointVec();
3214 ValueMapType &VMap = getValueMap();
3215 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3216 uint32_t &ExtInstImportID = getOpExtInstImportID();
3217 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3218
3219 // Set up insert point.
3220 auto InsertPoint = SPIRVInstList.begin();
3221
3222 //
3223 // Generate OpCapability
3224 //
3225 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3226
3227 // Ops[0] = Capability
3228 SPIRVOperandList Ops;
3229
David Neto87846742018-04-11 17:36:22 -04003230 auto *CapInst =
3231 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003232 SPIRVInstList.insert(InsertPoint, CapInst);
3233
3234 for (Type *Ty : getTypeList()) {
3235 // Find the i16 type.
3236 if (Ty->isIntegerTy(16)) {
3237 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003238 SPIRVInstList.insert(InsertPoint,
3239 new SPIRVInstruction(spv::OpCapability,
3240 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003241 } else if (Ty->isIntegerTy(64)) {
3242 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003243 SPIRVInstList.insert(InsertPoint,
3244 new SPIRVInstruction(spv::OpCapability,
3245 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003246 } else if (Ty->isHalfTy()) {
3247 // Generate OpCapability for half type.
3248 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003249 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3250 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003251 } else if (Ty->isDoubleTy()) {
3252 // Generate OpCapability for double type.
3253 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003254 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3255 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003256 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3257 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003258 if (STy->getName().equals("opencl.image2d_wo_t") ||
3259 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003260 // Generate OpCapability for write only image type.
3261 SPIRVInstList.insert(
3262 InsertPoint,
3263 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003264 spv::OpCapability,
3265 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003266 }
3267 }
3268 }
3269 }
3270
David Neto5c22a252018-03-15 16:07:41 -04003271 { // OpCapability ImageQuery
3272 bool hasImageQuery = false;
3273 for (const char *imageQuery : {
3274 "_Z15get_image_width14ocl_image2d_ro",
3275 "_Z15get_image_width14ocl_image2d_wo",
3276 "_Z16get_image_height14ocl_image2d_ro",
3277 "_Z16get_image_height14ocl_image2d_wo",
3278 }) {
3279 if (module.getFunction(imageQuery)) {
3280 hasImageQuery = true;
3281 break;
3282 }
3283 }
3284 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003285 auto *ImageQueryCapInst = new SPIRVInstruction(
3286 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003287 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3288 }
3289 }
3290
David Neto22f144c2017-06-12 14:26:21 -04003291 if (hasVariablePointers()) {
3292 //
David Neto22f144c2017-06-12 14:26:21 -04003293 // Generate OpCapability.
3294 //
3295 // Ops[0] = Capability
3296 //
3297 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003298 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003299
David Neto87846742018-04-11 17:36:22 -04003300 SPIRVInstList.insert(InsertPoint,
3301 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003302 } else if (hasVariablePointersStorageBuffer()) {
3303 //
3304 // Generate OpCapability.
3305 //
3306 // Ops[0] = Capability
3307 //
3308 Ops.clear();
3309 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003310
alan-baker5b86ed72019-02-15 08:26:50 -05003311 SPIRVInstList.insert(InsertPoint,
3312 new SPIRVInstruction(spv::OpCapability, Ops));
3313 }
3314
3315 // Always add the storage buffer extension
3316 {
David Neto22f144c2017-06-12 14:26:21 -04003317 //
3318 // Generate OpExtension.
3319 //
3320 // Ops[0] = Name (Literal String)
3321 //
alan-baker5b86ed72019-02-15 08:26:50 -05003322 auto *ExtensionInst = new SPIRVInstruction(
3323 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3324 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3325 }
David Neto22f144c2017-06-12 14:26:21 -04003326
alan-baker5b86ed72019-02-15 08:26:50 -05003327 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3328 //
3329 // Generate OpExtension.
3330 //
3331 // Ops[0] = Name (Literal String)
3332 //
3333 auto *ExtensionInst = new SPIRVInstruction(
3334 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3335 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003336 }
3337
3338 if (ExtInstImportID) {
3339 ++InsertPoint;
3340 }
3341
3342 //
3343 // Generate OpMemoryModel
3344 //
3345 // Memory model for Vulkan will always be GLSL450.
3346
3347 // Ops[0] = Addressing Model
3348 // Ops[1] = Memory Model
3349 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003350 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003351
David Neto87846742018-04-11 17:36:22 -04003352 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003353 SPIRVInstList.insert(InsertPoint, MemModelInst);
3354
3355 //
3356 // Generate OpEntryPoint
3357 //
3358 for (auto EntryPoint : EntryPoints) {
3359 // Ops[0] = Execution Model
3360 // Ops[1] = EntryPoint ID
3361 // Ops[2] = Name (Literal String)
3362 // ...
3363 //
3364 // TODO: Do we need to consider Interface ID for forward references???
3365 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003366 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003367 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3368 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003369
David Neto22f144c2017-06-12 14:26:21 -04003370 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003371 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003372 }
3373
David Neto87846742018-04-11 17:36:22 -04003374 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003375 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3376 }
3377
3378 for (auto EntryPoint : EntryPoints) {
3379 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3380 ->getMetadata("reqd_work_group_size")) {
3381
3382 if (!BuiltinDimVec.empty()) {
3383 llvm_unreachable(
3384 "Kernels should have consistent work group size definition");
3385 }
3386
3387 //
3388 // Generate OpExecutionMode
3389 //
3390
3391 // Ops[0] = Entry Point ID
3392 // Ops[1] = Execution Mode
3393 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3394 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003395 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003396
3397 uint32_t XDim = static_cast<uint32_t>(
3398 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3399 uint32_t YDim = static_cast<uint32_t>(
3400 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3401 uint32_t ZDim = static_cast<uint32_t>(
3402 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3403
David Neto257c3892018-04-11 13:19:45 -04003404 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003405
David Neto87846742018-04-11 17:36:22 -04003406 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003407 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3408 }
3409 }
3410
3411 //
3412 // Generate OpSource.
3413 //
3414 // Ops[0] = SourceLanguage ID
3415 // Ops[1] = Version (LiteralNum)
3416 //
3417 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003418 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003419
David Neto87846742018-04-11 17:36:22 -04003420 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003421 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3422
3423 if (!BuiltinDimVec.empty()) {
3424 //
3425 // Generate OpDecorates for x/y/z dimension.
3426 //
3427 // Ops[0] = Target ID
3428 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003429 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003430
3431 // X Dimension
3432 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003433 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003434 SPIRVInstList.insert(InsertPoint,
3435 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003436
3437 // Y Dimension
3438 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003439 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003440 SPIRVInstList.insert(InsertPoint,
3441 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003442
3443 // Z Dimension
3444 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003445 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003446 SPIRVInstList.insert(InsertPoint,
3447 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003448 }
3449}
3450
David Netob6e2e062018-04-25 10:32:06 -04003451void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3452 // Work around a driver bug. Initializers on Private variables might not
3453 // work. So the start of the kernel should store the initializer value to the
3454 // variables. Yes, *every* entry point pays this cost if *any* entry point
3455 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3456 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003457 // TODO(dneto): Remove this at some point once fixed drivers are widely
3458 // available.
David Netob6e2e062018-04-25 10:32:06 -04003459 if (WorkgroupSizeVarID) {
3460 assert(WorkgroupSizeValueID);
3461
3462 SPIRVOperandList Ops;
3463 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3464
3465 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3466 getSPIRVInstList().push_back(Inst);
3467 }
3468}
3469
David Neto22f144c2017-06-12 14:26:21 -04003470void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3471 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3472 ValueMapType &VMap = getValueMap();
3473
David Netob6e2e062018-04-25 10:32:06 -04003474 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003475
3476 for (BasicBlock &BB : F) {
3477 // Register BasicBlock to ValueMap.
3478 VMap[&BB] = nextID;
3479
3480 //
3481 // Generate OpLabel for Basic Block.
3482 //
3483 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003484 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003485 SPIRVInstList.push_back(Inst);
3486
David Neto6dcd4712017-06-23 11:06:47 -04003487 // OpVariable instructions must come first.
3488 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003489 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3490 // Allocating a pointer requires variable pointers.
3491 if (alloca->getAllocatedType()->isPointerTy()) {
3492 setVariablePointersCapabilities(alloca->getAllocatedType()->getPointerAddressSpace());
3493 }
David Neto6dcd4712017-06-23 11:06:47 -04003494 GenerateInstruction(I);
3495 }
3496 }
3497
David Neto22f144c2017-06-12 14:26:21 -04003498 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003499 if (clspv::Option::HackInitializers()) {
3500 GenerateEntryPointInitialStores();
3501 }
David Neto22f144c2017-06-12 14:26:21 -04003502 }
3503
3504 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003505 if (!isa<AllocaInst>(I)) {
3506 GenerateInstruction(I);
3507 }
David Neto22f144c2017-06-12 14:26:21 -04003508 }
3509 }
3510}
3511
3512spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3513 const std::map<CmpInst::Predicate, spv::Op> Map = {
3514 {CmpInst::ICMP_EQ, spv::OpIEqual},
3515 {CmpInst::ICMP_NE, spv::OpINotEqual},
3516 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3517 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3518 {CmpInst::ICMP_ULT, spv::OpULessThan},
3519 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3520 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3521 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3522 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3523 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3524 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3525 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3526 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3527 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3528 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3529 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3530 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3531 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3532 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3533 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3534 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3535 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3536
3537 assert(0 != Map.count(I->getPredicate()));
3538
3539 return Map.at(I->getPredicate());
3540}
3541
3542spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3543 const std::map<unsigned, spv::Op> Map{
3544 {Instruction::Trunc, spv::OpUConvert},
3545 {Instruction::ZExt, spv::OpUConvert},
3546 {Instruction::SExt, spv::OpSConvert},
3547 {Instruction::FPToUI, spv::OpConvertFToU},
3548 {Instruction::FPToSI, spv::OpConvertFToS},
3549 {Instruction::UIToFP, spv::OpConvertUToF},
3550 {Instruction::SIToFP, spv::OpConvertSToF},
3551 {Instruction::FPTrunc, spv::OpFConvert},
3552 {Instruction::FPExt, spv::OpFConvert},
3553 {Instruction::BitCast, spv::OpBitcast}};
3554
3555 assert(0 != Map.count(I.getOpcode()));
3556
3557 return Map.at(I.getOpcode());
3558}
3559
3560spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003561 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003562 switch (I.getOpcode()) {
3563 default:
3564 break;
3565 case Instruction::Or:
3566 return spv::OpLogicalOr;
3567 case Instruction::And:
3568 return spv::OpLogicalAnd;
3569 case Instruction::Xor:
3570 return spv::OpLogicalNotEqual;
3571 }
3572 }
3573
alan-bakerb6b09dc2018-11-08 16:59:28 -05003574 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003575 {Instruction::Add, spv::OpIAdd},
3576 {Instruction::FAdd, spv::OpFAdd},
3577 {Instruction::Sub, spv::OpISub},
3578 {Instruction::FSub, spv::OpFSub},
3579 {Instruction::Mul, spv::OpIMul},
3580 {Instruction::FMul, spv::OpFMul},
3581 {Instruction::UDiv, spv::OpUDiv},
3582 {Instruction::SDiv, spv::OpSDiv},
3583 {Instruction::FDiv, spv::OpFDiv},
3584 {Instruction::URem, spv::OpUMod},
3585 {Instruction::SRem, spv::OpSRem},
3586 {Instruction::FRem, spv::OpFRem},
3587 {Instruction::Or, spv::OpBitwiseOr},
3588 {Instruction::Xor, spv::OpBitwiseXor},
3589 {Instruction::And, spv::OpBitwiseAnd},
3590 {Instruction::Shl, spv::OpShiftLeftLogical},
3591 {Instruction::LShr, spv::OpShiftRightLogical},
3592 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3593
3594 assert(0 != Map.count(I.getOpcode()));
3595
3596 return Map.at(I.getOpcode());
3597}
3598
3599void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3600 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3601 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003602 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3603 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3604
3605 // Register Instruction to ValueMap.
3606 if (0 == VMap[&I]) {
3607 VMap[&I] = nextID;
3608 }
3609
3610 switch (I.getOpcode()) {
3611 default: {
3612 if (Instruction::isCast(I.getOpcode())) {
3613 //
3614 // Generate SPIRV instructions for cast operators.
3615 //
3616
David Netod2de94a2017-08-28 17:27:47 -04003617 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003618 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003619 auto toI8 = Ty == Type::getInt8Ty(Context);
3620 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003621 // Handle zext, sext and uitofp with i1 type specially.
3622 if ((I.getOpcode() == Instruction::ZExt ||
3623 I.getOpcode() == Instruction::SExt ||
3624 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003625 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003626 //
3627 // Generate OpSelect.
3628 //
3629
3630 // Ops[0] = Result Type ID
3631 // Ops[1] = Condition ID
3632 // Ops[2] = True Constant ID
3633 // Ops[3] = False Constant ID
3634 SPIRVOperandList Ops;
3635
David Neto257c3892018-04-11 13:19:45 -04003636 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003637
David Neto22f144c2017-06-12 14:26:21 -04003638 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003639 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003640
3641 uint32_t TrueID = 0;
3642 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003643 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003644 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003645 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003646 } else {
3647 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3648 }
David Neto257c3892018-04-11 13:19:45 -04003649 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003650
3651 uint32_t FalseID = 0;
3652 if (I.getOpcode() == Instruction::ZExt) {
3653 FalseID = VMap[Constant::getNullValue(I.getType())];
3654 } else if (I.getOpcode() == Instruction::SExt) {
3655 FalseID = VMap[Constant::getNullValue(I.getType())];
3656 } else {
3657 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3658 }
David Neto257c3892018-04-11 13:19:45 -04003659 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003660
David Neto87846742018-04-11 17:36:22 -04003661 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003662 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003663 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3664 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3665 // 8 bits.
3666 // Before:
3667 // %result = trunc i32 %a to i8
3668 // After
3669 // %result = OpBitwiseAnd %uint %a %uint_255
3670
3671 SPIRVOperandList Ops;
3672
David Neto257c3892018-04-11 13:19:45 -04003673 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003674
3675 Type *UintTy = Type::getInt32Ty(Context);
3676 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003677 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003678
David Neto87846742018-04-11 17:36:22 -04003679 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003680 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003681 } else {
3682 // Ops[0] = Result Type ID
3683 // Ops[1] = Source Value ID
3684 SPIRVOperandList Ops;
3685
David Neto257c3892018-04-11 13:19:45 -04003686 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003687
David Neto87846742018-04-11 17:36:22 -04003688 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003689 SPIRVInstList.push_back(Inst);
3690 }
3691 } else if (isa<BinaryOperator>(I)) {
3692 //
3693 // Generate SPIRV instructions for binary operators.
3694 //
3695
3696 // Handle xor with i1 type specially.
3697 if (I.getOpcode() == Instruction::Xor &&
3698 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003699 ((isa<ConstantInt>(I.getOperand(0)) &&
3700 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3701 (isa<ConstantInt>(I.getOperand(1)) &&
3702 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003703 //
3704 // Generate OpLogicalNot.
3705 //
3706 // Ops[0] = Result Type ID
3707 // Ops[1] = Operand
3708 SPIRVOperandList Ops;
3709
David Neto257c3892018-04-11 13:19:45 -04003710 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003711
3712 Value *CondV = I.getOperand(0);
3713 if (isa<Constant>(I.getOperand(0))) {
3714 CondV = I.getOperand(1);
3715 }
David Neto257c3892018-04-11 13:19:45 -04003716 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003717
David Neto87846742018-04-11 17:36:22 -04003718 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003719 SPIRVInstList.push_back(Inst);
3720 } else {
3721 // Ops[0] = Result Type ID
3722 // Ops[1] = Operand 0
3723 // Ops[2] = Operand 1
3724 SPIRVOperandList Ops;
3725
David Neto257c3892018-04-11 13:19:45 -04003726 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3727 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003728
David Neto87846742018-04-11 17:36:22 -04003729 auto *Inst =
3730 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003731 SPIRVInstList.push_back(Inst);
3732 }
3733 } else {
3734 I.print(errs());
3735 llvm_unreachable("Unsupported instruction???");
3736 }
3737 break;
3738 }
3739 case Instruction::GetElementPtr: {
3740 auto &GlobalConstArgSet = getGlobalConstArgSet();
3741
3742 //
3743 // Generate OpAccessChain.
3744 //
3745 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3746
3747 //
3748 // Generate OpAccessChain.
3749 //
3750
3751 // Ops[0] = Result Type ID
3752 // Ops[1] = Base ID
3753 // Ops[2] ... Ops[n] = Indexes ID
3754 SPIRVOperandList Ops;
3755
alan-bakerb6b09dc2018-11-08 16:59:28 -05003756 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003757 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3758 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3759 // Use pointer type with private address space for global constant.
3760 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003761 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003762 }
David Neto257c3892018-04-11 13:19:45 -04003763
3764 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003765
David Neto862b7d82018-06-14 18:48:37 -04003766 // Generate the base pointer.
3767 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003768
David Neto862b7d82018-06-14 18:48:37 -04003769 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003770
3771 //
3772 // Follows below rules for gep.
3773 //
David Neto862b7d82018-06-14 18:48:37 -04003774 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3775 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003776 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3777 // first index.
3778 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3779 // use gep's first index.
3780 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3781 // gep's first index.
3782 //
3783 spv::Op Opcode = spv::OpAccessChain;
3784 unsigned offset = 0;
3785 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003786 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003787 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003788 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003789 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003790 }
David Neto862b7d82018-06-14 18:48:37 -04003791 } else {
David Neto22f144c2017-06-12 14:26:21 -04003792 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003793 }
3794
3795 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003796 // Do we need to generate ArrayStride? Check against the GEP result type
3797 // rather than the pointer type of the base because when indexing into
3798 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3799 // for something else in the SPIR-V.
3800 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003801 auto address_space = ResultType->getAddressSpace();
3802 setVariablePointersCapabilities(address_space);
3803 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003804 case spv::StorageClassStorageBuffer:
3805 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003806 // Save the need to generate an ArrayStride decoration. But defer
3807 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003808 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003809 break;
3810 default:
3811 break;
David Neto1a1a0582017-07-07 12:01:44 -04003812 }
David Neto22f144c2017-06-12 14:26:21 -04003813 }
3814
3815 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003816 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003817 }
3818
David Neto87846742018-04-11 17:36:22 -04003819 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003820 SPIRVInstList.push_back(Inst);
3821 break;
3822 }
3823 case Instruction::ExtractValue: {
3824 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3825 // Ops[0] = Result Type ID
3826 // Ops[1] = Composite ID
3827 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3828 SPIRVOperandList Ops;
3829
David Neto257c3892018-04-11 13:19:45 -04003830 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003831
3832 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003833 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003834
3835 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003836 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003837 }
3838
David Neto87846742018-04-11 17:36:22 -04003839 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003840 SPIRVInstList.push_back(Inst);
3841 break;
3842 }
3843 case Instruction::InsertValue: {
3844 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3845 // Ops[0] = Result Type ID
3846 // Ops[1] = Object ID
3847 // Ops[2] = Composite ID
3848 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3849 SPIRVOperandList Ops;
3850
3851 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003852 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003853
3854 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003855 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003856
3857 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003858 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003859
3860 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003861 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003862 }
3863
David Neto87846742018-04-11 17:36:22 -04003864 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003865 SPIRVInstList.push_back(Inst);
3866 break;
3867 }
3868 case Instruction::Select: {
3869 //
3870 // Generate OpSelect.
3871 //
3872
3873 // Ops[0] = Result Type ID
3874 // Ops[1] = Condition ID
3875 // Ops[2] = True Constant ID
3876 // Ops[3] = False Constant ID
3877 SPIRVOperandList Ops;
3878
3879 // Find SPIRV instruction for parameter type.
3880 auto Ty = I.getType();
3881 if (Ty->isPointerTy()) {
3882 auto PointeeTy = Ty->getPointerElementType();
3883 if (PointeeTy->isStructTy() &&
3884 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3885 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003886 } else {
3887 // Selecting between pointers requires variable pointers.
3888 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3889 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3890 setVariablePointers(true);
3891 }
David Neto22f144c2017-06-12 14:26:21 -04003892 }
3893 }
3894
David Neto257c3892018-04-11 13:19:45 -04003895 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3896 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003897
David Neto87846742018-04-11 17:36:22 -04003898 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003899 SPIRVInstList.push_back(Inst);
3900 break;
3901 }
3902 case Instruction::ExtractElement: {
3903 // Handle <4 x i8> type manually.
3904 Type *CompositeTy = I.getOperand(0)->getType();
3905 if (is4xi8vec(CompositeTy)) {
3906 //
3907 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3908 // <4 x i8>.
3909 //
3910
3911 //
3912 // Generate OpShiftRightLogical
3913 //
3914 // Ops[0] = Result Type ID
3915 // Ops[1] = Operand 0
3916 // Ops[2] = Operand 1
3917 //
3918 SPIRVOperandList Ops;
3919
David Neto257c3892018-04-11 13:19:45 -04003920 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003921
3922 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003923 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003924
3925 uint32_t Op1ID = 0;
3926 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3927 // Handle constant index.
3928 uint64_t Idx = CI->getZExtValue();
3929 Value *ShiftAmount =
3930 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3931 Op1ID = VMap[ShiftAmount];
3932 } else {
3933 // Handle variable index.
3934 SPIRVOperandList TmpOps;
3935
David Neto257c3892018-04-11 13:19:45 -04003936 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3937 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003938
3939 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003940 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003941
3942 Op1ID = nextID;
3943
David Neto87846742018-04-11 17:36:22 -04003944 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003945 SPIRVInstList.push_back(TmpInst);
3946 }
David Neto257c3892018-04-11 13:19:45 -04003947 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003948
3949 uint32_t ShiftID = nextID;
3950
David Neto87846742018-04-11 17:36:22 -04003951 auto *Inst =
3952 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003953 SPIRVInstList.push_back(Inst);
3954
3955 //
3956 // Generate OpBitwiseAnd
3957 //
3958 // Ops[0] = Result Type ID
3959 // Ops[1] = Operand 0
3960 // Ops[2] = Operand 1
3961 //
3962 Ops.clear();
3963
David Neto257c3892018-04-11 13:19:45 -04003964 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003965
3966 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003967 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003968
David Neto9b2d6252017-09-06 15:47:37 -04003969 // Reset mapping for this value to the result of the bitwise and.
3970 VMap[&I] = nextID;
3971
David Neto87846742018-04-11 17:36:22 -04003972 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003973 SPIRVInstList.push_back(Inst);
3974 break;
3975 }
3976
3977 // Ops[0] = Result Type ID
3978 // Ops[1] = Composite ID
3979 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3980 SPIRVOperandList Ops;
3981
David Neto257c3892018-04-11 13:19:45 -04003982 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003983
3984 spv::Op Opcode = spv::OpCompositeExtract;
3985 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003986 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003987 } else {
David Neto257c3892018-04-11 13:19:45 -04003988 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003989 Opcode = spv::OpVectorExtractDynamic;
3990 }
3991
David Neto87846742018-04-11 17:36:22 -04003992 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003993 SPIRVInstList.push_back(Inst);
3994 break;
3995 }
3996 case Instruction::InsertElement: {
3997 // Handle <4 x i8> type manually.
3998 Type *CompositeTy = I.getOperand(0)->getType();
3999 if (is4xi8vec(CompositeTy)) {
4000 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4001 uint32_t CstFFID = VMap[CstFF];
4002
4003 uint32_t ShiftAmountID = 0;
4004 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4005 // Handle constant index.
4006 uint64_t Idx = CI->getZExtValue();
4007 Value *ShiftAmount =
4008 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4009 ShiftAmountID = VMap[ShiftAmount];
4010 } else {
4011 // Handle variable index.
4012 SPIRVOperandList TmpOps;
4013
David Neto257c3892018-04-11 13:19:45 -04004014 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
4015 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004016
4017 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04004018 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04004019
4020 ShiftAmountID = nextID;
4021
David Neto87846742018-04-11 17:36:22 -04004022 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04004023 SPIRVInstList.push_back(TmpInst);
4024 }
4025
4026 //
4027 // Generate mask operations.
4028 //
4029
4030 // ShiftLeft mask according to index of insertelement.
4031 SPIRVOperandList Ops;
4032
David Neto257c3892018-04-11 13:19:45 -04004033 const uint32_t ResTyID = lookupType(CompositeTy);
4034 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004035
4036 uint32_t MaskID = nextID;
4037
David Neto87846742018-04-11 17:36:22 -04004038 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004039 SPIRVInstList.push_back(Inst);
4040
4041 // Inverse mask.
4042 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004043 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004044
4045 uint32_t InvMaskID = nextID;
4046
David Neto87846742018-04-11 17:36:22 -04004047 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004048 SPIRVInstList.push_back(Inst);
4049
4050 // Apply mask.
4051 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004052 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004053
4054 uint32_t OrgValID = nextID;
4055
David Neto87846742018-04-11 17:36:22 -04004056 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 SPIRVInstList.push_back(Inst);
4058
4059 // Create correct value according to index of insertelement.
4060 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05004061 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
4062 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004063
4064 uint32_t InsertValID = nextID;
4065
David Neto87846742018-04-11 17:36:22 -04004066 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004067 SPIRVInstList.push_back(Inst);
4068
4069 // Insert value to original value.
4070 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004071 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004072
David Netoa394f392017-08-26 20:45:29 -04004073 VMap[&I] = nextID;
4074
David Neto87846742018-04-11 17:36:22 -04004075 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004076 SPIRVInstList.push_back(Inst);
4077
4078 break;
4079 }
4080
David Neto22f144c2017-06-12 14:26:21 -04004081 SPIRVOperandList Ops;
4082
James Priced26efea2018-06-09 23:28:32 +01004083 // Ops[0] = Result Type ID
4084 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004085
4086 spv::Op Opcode = spv::OpCompositeInsert;
4087 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004088 const auto value = CI->getZExtValue();
4089 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004090 // Ops[1] = Object ID
4091 // Ops[2] = Composite ID
4092 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004093 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004094 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004095 } else {
James Priced26efea2018-06-09 23:28:32 +01004096 // Ops[1] = Composite ID
4097 // Ops[2] = Object ID
4098 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004099 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004100 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004101 Opcode = spv::OpVectorInsertDynamic;
4102 }
4103
David Neto87846742018-04-11 17:36:22 -04004104 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004105 SPIRVInstList.push_back(Inst);
4106 break;
4107 }
4108 case Instruction::ShuffleVector: {
4109 // Ops[0] = Result Type ID
4110 // Ops[1] = Vector 1 ID
4111 // Ops[2] = Vector 2 ID
4112 // Ops[3] ... Ops[n] = Components (Literal Number)
4113 SPIRVOperandList Ops;
4114
David Neto257c3892018-04-11 13:19:45 -04004115 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4116 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004117
4118 uint64_t NumElements = 0;
4119 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4120 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4121
4122 if (Cst->isNullValue()) {
4123 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004124 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004125 }
4126 } else if (const ConstantDataSequential *CDS =
4127 dyn_cast<ConstantDataSequential>(Cst)) {
4128 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4129 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004130 const auto value = CDS->getElementAsInteger(i);
4131 assert(value <= UINT32_MAX);
4132 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004133 }
4134 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4135 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4136 auto Op = CV->getOperand(i);
4137
4138 uint32_t literal = 0;
4139
4140 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4141 literal = static_cast<uint32_t>(CI->getZExtValue());
4142 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4143 literal = 0xFFFFFFFFu;
4144 } else {
4145 Op->print(errs());
4146 llvm_unreachable("Unsupported element in ConstantVector!");
4147 }
4148
David Neto257c3892018-04-11 13:19:45 -04004149 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004150 }
4151 } else {
4152 Cst->print(errs());
4153 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4154 }
4155 }
4156
David Neto87846742018-04-11 17:36:22 -04004157 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004158 SPIRVInstList.push_back(Inst);
4159 break;
4160 }
4161 case Instruction::ICmp:
4162 case Instruction::FCmp: {
4163 CmpInst *CmpI = cast<CmpInst>(&I);
4164
David Netod4ca2e62017-07-06 18:47:35 -04004165 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004166 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004167 if (isa<PointerType>(ArgTy)) {
4168 CmpI->print(errs());
4169 std::string name = I.getParent()->getParent()->getName();
4170 errs()
4171 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4172 << "in function " << name << "\n";
4173 llvm_unreachable("Pointer equality check is invalid");
4174 break;
4175 }
4176
David Neto257c3892018-04-11 13:19:45 -04004177 // Ops[0] = Result Type ID
4178 // Ops[1] = Operand 1 ID
4179 // Ops[2] = Operand 2 ID
4180 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004181
David Neto257c3892018-04-11 13:19:45 -04004182 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4183 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004184
4185 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004186 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004187 SPIRVInstList.push_back(Inst);
4188 break;
4189 }
4190 case Instruction::Br: {
4191 // Branch instrucion is deferred because it needs label's ID. Record slot's
4192 // location on SPIRVInstructionList.
4193 DeferredInsts.push_back(
4194 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4195 break;
4196 }
4197 case Instruction::Switch: {
4198 I.print(errs());
4199 llvm_unreachable("Unsupported instruction???");
4200 break;
4201 }
4202 case Instruction::IndirectBr: {
4203 I.print(errs());
4204 llvm_unreachable("Unsupported instruction???");
4205 break;
4206 }
4207 case Instruction::PHI: {
4208 // Branch instrucion is deferred because it needs label's ID. Record slot's
4209 // location on SPIRVInstructionList.
4210 DeferredInsts.push_back(
4211 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4212 break;
4213 }
4214 case Instruction::Alloca: {
4215 //
4216 // Generate OpVariable.
4217 //
4218 // Ops[0] : Result Type ID
4219 // Ops[1] : Storage Class
4220 SPIRVOperandList Ops;
4221
David Neto257c3892018-04-11 13:19:45 -04004222 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004223
David Neto87846742018-04-11 17:36:22 -04004224 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004225 SPIRVInstList.push_back(Inst);
4226 break;
4227 }
4228 case Instruction::Load: {
4229 LoadInst *LD = cast<LoadInst>(&I);
4230 //
4231 // Generate OpLoad.
4232 //
alan-baker5b86ed72019-02-15 08:26:50 -05004233
4234 if (LD->getType()->isPointerTy()) {
4235 // Loading a pointer requires variable pointers.
4236 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4237 }
David Neto22f144c2017-06-12 14:26:21 -04004238
David Neto0a2f98d2017-09-15 19:38:40 -04004239 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004240 uint32_t PointerID = VMap[LD->getPointerOperand()];
4241
4242 // This is a hack to work around what looks like a driver bug.
4243 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004244 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4245 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004246 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004247 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004248 // Generate a bitwise-and of the original value with itself.
4249 // We should have been able to get away with just an OpCopyObject,
4250 // but we need something more complex to get past certain driver bugs.
4251 // This is ridiculous, but necessary.
4252 // TODO(dneto): Revisit this once drivers fix their bugs.
4253
4254 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004255 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4256 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004257
David Neto87846742018-04-11 17:36:22 -04004258 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004259 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004260 break;
4261 }
4262
4263 // This is the normal path. Generate a load.
4264
David Neto22f144c2017-06-12 14:26:21 -04004265 // Ops[0] = Result Type ID
4266 // Ops[1] = Pointer ID
4267 // Ops[2] ... Ops[n] = Optional Memory Access
4268 //
4269 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004270
David Neto22f144c2017-06-12 14:26:21 -04004271 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004272 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004273
David Neto87846742018-04-11 17:36:22 -04004274 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004275 SPIRVInstList.push_back(Inst);
4276 break;
4277 }
4278 case Instruction::Store: {
4279 StoreInst *ST = cast<StoreInst>(&I);
4280 //
4281 // Generate OpStore.
4282 //
4283
alan-baker5b86ed72019-02-15 08:26:50 -05004284 if (ST->getValueOperand()->getType()->isPointerTy()) {
4285 // Storing a pointer requires variable pointers.
4286 setVariablePointersCapabilities(
4287 ST->getValueOperand()->getType()->getPointerAddressSpace());
4288 }
4289
David Neto22f144c2017-06-12 14:26:21 -04004290 // Ops[0] = Pointer ID
4291 // Ops[1] = Object ID
4292 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4293 //
4294 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004295 SPIRVOperandList Ops;
4296 Ops << MkId(VMap[ST->getPointerOperand()])
4297 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004298
David Neto87846742018-04-11 17:36:22 -04004299 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004300 SPIRVInstList.push_back(Inst);
4301 break;
4302 }
4303 case Instruction::AtomicCmpXchg: {
4304 I.print(errs());
4305 llvm_unreachable("Unsupported instruction???");
4306 break;
4307 }
4308 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004309 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4310
4311 spv::Op opcode;
4312
4313 switch (AtomicRMW->getOperation()) {
4314 default:
4315 I.print(errs());
4316 llvm_unreachable("Unsupported instruction???");
4317 case llvm::AtomicRMWInst::Add:
4318 opcode = spv::OpAtomicIAdd;
4319 break;
4320 case llvm::AtomicRMWInst::Sub:
4321 opcode = spv::OpAtomicISub;
4322 break;
4323 case llvm::AtomicRMWInst::Xchg:
4324 opcode = spv::OpAtomicExchange;
4325 break;
4326 case llvm::AtomicRMWInst::Min:
4327 opcode = spv::OpAtomicSMin;
4328 break;
4329 case llvm::AtomicRMWInst::Max:
4330 opcode = spv::OpAtomicSMax;
4331 break;
4332 case llvm::AtomicRMWInst::UMin:
4333 opcode = spv::OpAtomicUMin;
4334 break;
4335 case llvm::AtomicRMWInst::UMax:
4336 opcode = spv::OpAtomicUMax;
4337 break;
4338 case llvm::AtomicRMWInst::And:
4339 opcode = spv::OpAtomicAnd;
4340 break;
4341 case llvm::AtomicRMWInst::Or:
4342 opcode = spv::OpAtomicOr;
4343 break;
4344 case llvm::AtomicRMWInst::Xor:
4345 opcode = spv::OpAtomicXor;
4346 break;
4347 }
4348
4349 //
4350 // Generate OpAtomic*.
4351 //
4352 SPIRVOperandList Ops;
4353
David Neto257c3892018-04-11 13:19:45 -04004354 Ops << MkId(lookupType(I.getType()))
4355 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004356
4357 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004358 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004359 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004360
4361 const auto ConstantMemorySemantics = ConstantInt::get(
4362 IntTy, spv::MemorySemanticsUniformMemoryMask |
4363 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004365
David Neto257c3892018-04-11 13:19:45 -04004366 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004367
4368 VMap[&I] = nextID;
4369
David Neto87846742018-04-11 17:36:22 -04004370 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004371 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004372 break;
4373 }
4374 case Instruction::Fence: {
4375 I.print(errs());
4376 llvm_unreachable("Unsupported instruction???");
4377 break;
4378 }
4379 case Instruction::Call: {
4380 CallInst *Call = dyn_cast<CallInst>(&I);
4381 Function *Callee = Call->getCalledFunction();
4382
Alan Baker202c8c72018-08-13 13:47:44 -04004383 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004384 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4385 // Generate an OpLoad
4386 SPIRVOperandList Ops;
4387 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004388
David Neto862b7d82018-06-14 18:48:37 -04004389 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4390 << MkId(ResourceVarDeferredLoadCalls[Call]);
4391
4392 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4393 SPIRVInstList.push_back(Inst);
4394 VMap[Call] = load_id;
4395 break;
4396
4397 } else {
4398 // This maps to an OpVariable we've already generated.
4399 // No code is generated for the call.
4400 }
4401 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004402 } else if (Callee->getName().startswith(
4403 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004404 // Don't codegen an instruction here, but instead map this call directly
4405 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004406 int spec_id = static_cast<int>(
4407 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004408 const auto &info = LocalSpecIdInfoMap[spec_id];
4409 VMap[Call] = info.variable_id;
4410 break;
David Neto862b7d82018-06-14 18:48:37 -04004411 }
4412
4413 // Sampler initializers become a load of the corresponding sampler.
4414
4415 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4416 // Map this to a load from the variable.
4417 const auto index_into_sampler_map =
4418 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4419
4420 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004421 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004422 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004423
David Neto257c3892018-04-11 13:19:45 -04004424 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004425 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4426 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004427
David Neto862b7d82018-06-14 18:48:37 -04004428 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004429 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004430 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004431 break;
4432 }
4433
4434 if (Callee->getName().startswith("spirv.atomic")) {
4435 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4436 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4437 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4438 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4439 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4440 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4441 .Case("spirv.atomic_compare_exchange",
4442 spv::OpAtomicCompareExchange)
4443 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4444 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4445 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4446 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4447 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4448 .Case("spirv.atomic_or", spv::OpAtomicOr)
4449 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4450 .Default(spv::OpNop);
4451
4452 //
4453 // Generate OpAtomic*.
4454 //
4455 SPIRVOperandList Ops;
4456
David Neto257c3892018-04-11 13:19:45 -04004457 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004458
4459 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004460 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004461 }
4462
4463 VMap[&I] = nextID;
4464
David Neto87846742018-04-11 17:36:22 -04004465 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004466 SPIRVInstList.push_back(Inst);
4467 break;
4468 }
4469
4470 if (Callee->getName().startswith("_Z3dot")) {
4471 // If the argument is a vector type, generate OpDot
4472 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4473 //
4474 // Generate OpDot.
4475 //
4476 SPIRVOperandList Ops;
4477
David Neto257c3892018-04-11 13:19:45 -04004478 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004479
4480 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004481 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004482 }
4483
4484 VMap[&I] = nextID;
4485
David Neto87846742018-04-11 17:36:22 -04004486 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004487 SPIRVInstList.push_back(Inst);
4488 } else {
4489 //
4490 // Generate OpFMul.
4491 //
4492 SPIRVOperandList Ops;
4493
David Neto257c3892018-04-11 13:19:45 -04004494 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004495
4496 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004497 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004498 }
4499
4500 VMap[&I] = nextID;
4501
David Neto87846742018-04-11 17:36:22 -04004502 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004503 SPIRVInstList.push_back(Inst);
4504 }
4505 break;
4506 }
4507
David Neto8505ebf2017-10-13 18:50:50 -04004508 if (Callee->getName().startswith("_Z4fmod")) {
4509 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4510 // The sign for a non-zero result is taken from x.
4511 // (Try an example.)
4512 // So translate to OpFRem
4513
4514 SPIRVOperandList Ops;
4515
David Neto257c3892018-04-11 13:19:45 -04004516 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004517
4518 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004519 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004520 }
4521
4522 VMap[&I] = nextID;
4523
David Neto87846742018-04-11 17:36:22 -04004524 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004525 SPIRVInstList.push_back(Inst);
4526 break;
4527 }
4528
David Neto22f144c2017-06-12 14:26:21 -04004529 // spirv.store_null.* intrinsics become OpStore's.
4530 if (Callee->getName().startswith("spirv.store_null")) {
4531 //
4532 // Generate OpStore.
4533 //
4534
4535 // Ops[0] = Pointer ID
4536 // Ops[1] = Object ID
4537 // Ops[2] ... Ops[n]
4538 SPIRVOperandList Ops;
4539
4540 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004541 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004542 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004543
David Neto87846742018-04-11 17:36:22 -04004544 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004545
4546 break;
4547 }
4548
4549 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4550 if (Callee->getName().startswith("spirv.copy_memory")) {
4551 //
4552 // Generate OpCopyMemory.
4553 //
4554
4555 // Ops[0] = Dst ID
4556 // Ops[1] = Src ID
4557 // Ops[2] = Memory Access
4558 // Ops[3] = Alignment
4559
4560 auto IsVolatile =
4561 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4562
4563 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4564 : spv::MemoryAccessMaskNone;
4565
4566 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4567
4568 auto Alignment =
4569 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4570
David Neto257c3892018-04-11 13:19:45 -04004571 SPIRVOperandList Ops;
4572 Ops << MkId(VMap[Call->getArgOperand(0)])
4573 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4574 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004575
David Neto87846742018-04-11 17:36:22 -04004576 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004577
4578 SPIRVInstList.push_back(Inst);
4579
4580 break;
4581 }
4582
4583 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4584 // with unit.
4585 if (Callee->getName().equals("_Z3absj") ||
4586 Callee->getName().equals("_Z3absDv2_j") ||
4587 Callee->getName().equals("_Z3absDv3_j") ||
4588 Callee->getName().equals("_Z3absDv4_j")) {
4589 VMap[&I] = VMap[Call->getOperand(0)];
4590 break;
4591 }
4592
4593 // barrier is converted to OpControlBarrier
4594 if (Callee->getName().equals("__spirv_control_barrier")) {
4595 //
4596 // Generate OpControlBarrier.
4597 //
4598 // Ops[0] = Execution Scope ID
4599 // Ops[1] = Memory Scope ID
4600 // Ops[2] = Memory Semantics ID
4601 //
4602 Value *ExecutionScope = Call->getArgOperand(0);
4603 Value *MemoryScope = Call->getArgOperand(1);
4604 Value *MemorySemantics = Call->getArgOperand(2);
4605
David Neto257c3892018-04-11 13:19:45 -04004606 SPIRVOperandList Ops;
4607 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4608 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004609
David Neto87846742018-04-11 17:36:22 -04004610 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004611 break;
4612 }
4613
4614 // memory barrier is converted to OpMemoryBarrier
4615 if (Callee->getName().equals("__spirv_memory_barrier")) {
4616 //
4617 // Generate OpMemoryBarrier.
4618 //
4619 // Ops[0] = Memory Scope ID
4620 // Ops[1] = Memory Semantics ID
4621 //
4622 SPIRVOperandList Ops;
4623
David Neto257c3892018-04-11 13:19:45 -04004624 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4625 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004626
David Neto257c3892018-04-11 13:19:45 -04004627 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004628
David Neto87846742018-04-11 17:36:22 -04004629 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004630 SPIRVInstList.push_back(Inst);
4631 break;
4632 }
4633
4634 // isinf is converted to OpIsInf
4635 if (Callee->getName().equals("__spirv_isinff") ||
4636 Callee->getName().equals("__spirv_isinfDv2_f") ||
4637 Callee->getName().equals("__spirv_isinfDv3_f") ||
4638 Callee->getName().equals("__spirv_isinfDv4_f")) {
4639 //
4640 // Generate OpIsInf.
4641 //
4642 // Ops[0] = Result Type ID
4643 // Ops[1] = X ID
4644 //
4645 SPIRVOperandList Ops;
4646
David Neto257c3892018-04-11 13:19:45 -04004647 Ops << MkId(lookupType(I.getType()))
4648 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004649
4650 VMap[&I] = nextID;
4651
David Neto87846742018-04-11 17:36:22 -04004652 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004653 SPIRVInstList.push_back(Inst);
4654 break;
4655 }
4656
4657 // isnan is converted to OpIsNan
4658 if (Callee->getName().equals("__spirv_isnanf") ||
4659 Callee->getName().equals("__spirv_isnanDv2_f") ||
4660 Callee->getName().equals("__spirv_isnanDv3_f") ||
4661 Callee->getName().equals("__spirv_isnanDv4_f")) {
4662 //
4663 // Generate OpIsInf.
4664 //
4665 // Ops[0] = Result Type ID
4666 // Ops[1] = X ID
4667 //
4668 SPIRVOperandList Ops;
4669
David Neto257c3892018-04-11 13:19:45 -04004670 Ops << MkId(lookupType(I.getType()))
4671 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004672
4673 VMap[&I] = nextID;
4674
David Neto87846742018-04-11 17:36:22 -04004675 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004676 SPIRVInstList.push_back(Inst);
4677 break;
4678 }
4679
4680 // all is converted to OpAll
Kévin Petitfd27cca2018-10-31 13:00:17 +00004681 if (Callee->getName().startswith("__spirv_allDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004682 //
4683 // Generate OpAll.
4684 //
4685 // Ops[0] = Result Type ID
4686 // Ops[1] = Vector ID
4687 //
4688 SPIRVOperandList Ops;
4689
David Neto257c3892018-04-11 13:19:45 -04004690 Ops << MkId(lookupType(I.getType()))
4691 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004692
4693 VMap[&I] = nextID;
4694
David Neto87846742018-04-11 17:36:22 -04004695 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004696 SPIRVInstList.push_back(Inst);
4697 break;
4698 }
4699
4700 // any is converted to OpAny
Kévin Petitfd27cca2018-10-31 13:00:17 +00004701 if (Callee->getName().startswith("__spirv_anyDv")) {
David Neto22f144c2017-06-12 14:26:21 -04004702 //
4703 // Generate OpAny.
4704 //
4705 // Ops[0] = Result Type ID
4706 // Ops[1] = Vector ID
4707 //
4708 SPIRVOperandList Ops;
4709
David Neto257c3892018-04-11 13:19:45 -04004710 Ops << MkId(lookupType(I.getType()))
4711 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004712
4713 VMap[&I] = nextID;
4714
David Neto87846742018-04-11 17:36:22 -04004715 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004716 SPIRVInstList.push_back(Inst);
4717 break;
4718 }
4719
4720 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4721 // Additionally, OpTypeSampledImage is generated.
4722 if (Callee->getName().equals(
4723 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4724 Callee->getName().equals(
4725 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4726 //
4727 // Generate OpSampledImage.
4728 //
4729 // Ops[0] = Result Type ID
4730 // Ops[1] = Image ID
4731 // Ops[2] = Sampler ID
4732 //
4733 SPIRVOperandList Ops;
4734
4735 Value *Image = Call->getArgOperand(0);
4736 Value *Sampler = Call->getArgOperand(1);
4737 Value *Coordinate = Call->getArgOperand(2);
4738
4739 TypeMapType &OpImageTypeMap = getImageTypeMap();
4740 Type *ImageTy = Image->getType()->getPointerElementType();
4741 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004742 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004743 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004744
4745 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004746
4747 uint32_t SampledImageID = nextID;
4748
David Neto87846742018-04-11 17:36:22 -04004749 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004750 SPIRVInstList.push_back(Inst);
4751
4752 //
4753 // Generate OpImageSampleExplicitLod.
4754 //
4755 // Ops[0] = Result Type ID
4756 // Ops[1] = Sampled Image ID
4757 // Ops[2] = Coordinate ID
4758 // Ops[3] = Image Operands Type ID
4759 // Ops[4] ... Ops[n] = Operands ID
4760 //
4761 Ops.clear();
4762
David Neto257c3892018-04-11 13:19:45 -04004763 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4764 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004765
4766 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004767 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004768
4769 VMap[&I] = nextID;
4770
David Neto87846742018-04-11 17:36:22 -04004771 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004772 SPIRVInstList.push_back(Inst);
4773 break;
4774 }
4775
4776 // write_imagef is mapped to OpImageWrite.
4777 if (Callee->getName().equals(
4778 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4779 Callee->getName().equals(
4780 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4781 //
4782 // Generate OpImageWrite.
4783 //
4784 // Ops[0] = Image ID
4785 // Ops[1] = Coordinate ID
4786 // Ops[2] = Texel ID
4787 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4788 // Ops[4] ... Ops[n] = (Optional) Operands ID
4789 //
4790 SPIRVOperandList Ops;
4791
4792 Value *Image = Call->getArgOperand(0);
4793 Value *Coordinate = Call->getArgOperand(1);
4794 Value *Texel = Call->getArgOperand(2);
4795
4796 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004797 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004798 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004799 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004800
David Neto87846742018-04-11 17:36:22 -04004801 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004802 SPIRVInstList.push_back(Inst);
4803 break;
4804 }
4805
David Neto5c22a252018-03-15 16:07:41 -04004806 // get_image_width is mapped to OpImageQuerySize
4807 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4808 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4809 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4810 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4811 //
4812 // Generate OpImageQuerySize, then pull out the right component.
4813 // Assume 2D image for now.
4814 //
4815 // Ops[0] = Image ID
4816 //
4817 // %sizes = OpImageQuerySizes %uint2 %im
4818 // %result = OpCompositeExtract %uint %sizes 0-or-1
4819 SPIRVOperandList Ops;
4820
4821 // Implement:
4822 // %sizes = OpImageQuerySizes %uint2 %im
4823 uint32_t SizesTypeID =
4824 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004825 Value *Image = Call->getArgOperand(0);
4826 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004827 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004828
4829 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004830 auto *QueryInst =
4831 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004832 SPIRVInstList.push_back(QueryInst);
4833
4834 // Reset value map entry since we generated an intermediate instruction.
4835 VMap[&I] = nextID;
4836
4837 // Implement:
4838 // %result = OpCompositeExtract %uint %sizes 0-or-1
4839 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004840 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004841
4842 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004843 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004844
David Neto87846742018-04-11 17:36:22 -04004845 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004846 SPIRVInstList.push_back(Inst);
4847 break;
4848 }
4849
David Neto22f144c2017-06-12 14:26:21 -04004850 // Call instrucion is deferred because it needs function's ID. Record
4851 // slot's location on SPIRVInstructionList.
4852 DeferredInsts.push_back(
4853 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4854
David Neto3fbb4072017-10-16 11:28:14 -04004855 // Check whether the implementation of this call uses an extended
4856 // instruction plus one more value-producing instruction. If so, then
4857 // reserve the id for the extra value-producing slot.
4858 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4859 if (EInst != kGlslExtInstBad) {
4860 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004861 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004862 VMap[&I] = nextID;
4863 nextID++;
4864 }
4865 break;
4866 }
4867 case Instruction::Ret: {
4868 unsigned NumOps = I.getNumOperands();
4869 if (NumOps == 0) {
4870 //
4871 // Generate OpReturn.
4872 //
David Neto87846742018-04-11 17:36:22 -04004873 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004874 } else {
4875 //
4876 // Generate OpReturnValue.
4877 //
4878
4879 // Ops[0] = Return Value ID
4880 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004881
4882 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004883
David Neto87846742018-04-11 17:36:22 -04004884 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004885 SPIRVInstList.push_back(Inst);
4886 break;
4887 }
4888 break;
4889 }
4890 }
4891}
4892
4893void SPIRVProducerPass::GenerateFuncEpilogue() {
4894 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4895
4896 //
4897 // Generate OpFunctionEnd
4898 //
4899
David Neto87846742018-04-11 17:36:22 -04004900 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004901 SPIRVInstList.push_back(Inst);
4902}
4903
4904bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4905 LLVMContext &Context = Ty->getContext();
4906 if (Ty->isVectorTy()) {
4907 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4908 Ty->getVectorNumElements() == 4) {
4909 return true;
4910 }
4911 }
4912
4913 return false;
4914}
4915
David Neto257c3892018-04-11 13:19:45 -04004916uint32_t SPIRVProducerPass::GetI32Zero() {
4917 if (0 == constant_i32_zero_id_) {
4918 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4919 "defined in the SPIR-V module");
4920 }
4921 return constant_i32_zero_id_;
4922}
4923
David Neto22f144c2017-06-12 14:26:21 -04004924void SPIRVProducerPass::HandleDeferredInstruction() {
4925 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4926 ValueMapType &VMap = getValueMap();
4927 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4928
4929 for (auto DeferredInst = DeferredInsts.rbegin();
4930 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4931 Value *Inst = std::get<0>(*DeferredInst);
4932 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4933 if (InsertPoint != SPIRVInstList.end()) {
4934 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4935 ++InsertPoint;
4936 }
4937 }
4938
4939 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4940 // Check whether basic block, which has this branch instruction, is loop
4941 // header or not. If it is loop header, generate OpLoopMerge and
4942 // OpBranchConditional.
4943 Function *Func = Br->getParent()->getParent();
4944 DominatorTree &DT =
4945 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4946 const LoopInfo &LI =
4947 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4948
4949 BasicBlock *BrBB = Br->getParent();
4950 if (LI.isLoopHeader(BrBB)) {
4951 Value *ContinueBB = nullptr;
4952 Value *MergeBB = nullptr;
4953
4954 Loop *L = LI.getLoopFor(BrBB);
4955 MergeBB = L->getExitBlock();
4956 if (!MergeBB) {
4957 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4958 // has regions with single entry/exit. As a result, loop should not
4959 // have multiple exits.
4960 llvm_unreachable("Loop has multiple exits???");
4961 }
4962
4963 if (L->isLoopLatch(BrBB)) {
4964 ContinueBB = BrBB;
4965 } else {
4966 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4967 // block.
4968 BasicBlock *Header = L->getHeader();
4969 BasicBlock *Latch = L->getLoopLatch();
4970 for (BasicBlock *BB : L->blocks()) {
4971 if (BB == Header) {
4972 continue;
4973 }
4974
4975 // Check whether block dominates block with back-edge.
4976 if (DT.dominates(BB, Latch)) {
4977 ContinueBB = BB;
4978 }
4979 }
4980
4981 if (!ContinueBB) {
4982 llvm_unreachable("Wrong continue block from loop");
4983 }
4984 }
4985
4986 //
4987 // Generate OpLoopMerge.
4988 //
4989 // Ops[0] = Merge Block ID
4990 // Ops[1] = Continue Target ID
4991 // Ops[2] = Selection Control
4992 SPIRVOperandList Ops;
4993
4994 // StructurizeCFG pass already manipulated CFG. Just use false block of
4995 // branch instruction as merge block.
4996 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004997 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004998 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4999 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005000
David Neto87846742018-04-11 17:36:22 -04005001 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005002 SPIRVInstList.insert(InsertPoint, MergeInst);
5003
5004 } else if (Br->isConditional()) {
5005 bool HasBackEdge = false;
5006
5007 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
5008 if (LI.isLoopHeader(Br->getSuccessor(i))) {
5009 HasBackEdge = true;
5010 }
5011 }
5012 if (!HasBackEdge) {
5013 //
5014 // Generate OpSelectionMerge.
5015 //
5016 // Ops[0] = Merge Block ID
5017 // Ops[1] = Selection Control
5018 SPIRVOperandList Ops;
5019
5020 // StructurizeCFG pass already manipulated CFG. Just use false block
5021 // of branch instruction as merge block.
5022 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005023 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04005024
David Neto87846742018-04-11 17:36:22 -04005025 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005026 SPIRVInstList.insert(InsertPoint, MergeInst);
5027 }
5028 }
5029
5030 if (Br->isConditional()) {
5031 //
5032 // Generate OpBranchConditional.
5033 //
5034 // Ops[0] = Condition ID
5035 // Ops[1] = True Label ID
5036 // Ops[2] = False Label ID
5037 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5038 SPIRVOperandList Ops;
5039
5040 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04005041 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04005042 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04005043
5044 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04005045
David Neto87846742018-04-11 17:36:22 -04005046 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04005047 SPIRVInstList.insert(InsertPoint, BrInst);
5048 } else {
5049 //
5050 // Generate OpBranch.
5051 //
5052 // Ops[0] = Target Label ID
5053 SPIRVOperandList Ops;
5054
5055 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005056 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005057
David Neto87846742018-04-11 17:36:22 -04005058 SPIRVInstList.insert(InsertPoint,
5059 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005060 }
5061 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05005062 if (PHI->getType()->isPointerTy()) {
5063 // OpPhi on pointers requires variable pointers.
5064 setVariablePointersCapabilities(
5065 PHI->getType()->getPointerAddressSpace());
5066 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
5067 setVariablePointers(true);
5068 }
5069 }
5070
David Neto22f144c2017-06-12 14:26:21 -04005071 //
5072 // Generate OpPhi.
5073 //
5074 // Ops[0] = Result Type ID
5075 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5076 SPIRVOperandList Ops;
5077
David Neto257c3892018-04-11 13:19:45 -04005078 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005079
David Neto22f144c2017-06-12 14:26:21 -04005080 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5081 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005082 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005083 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005084 }
5085
5086 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005087 InsertPoint,
5088 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005089 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5090 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005091 auto callee_name = Callee->getName();
5092 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005093
5094 if (EInst) {
5095 uint32_t &ExtInstImportID = getOpExtInstImportID();
5096
5097 //
5098 // Generate OpExtInst.
5099 //
5100
5101 // Ops[0] = Result Type ID
5102 // Ops[1] = Set ID (OpExtInstImport ID)
5103 // Ops[2] = Instruction Number (Literal Number)
5104 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5105 SPIRVOperandList Ops;
5106
David Neto862b7d82018-06-14 18:48:37 -04005107 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5108 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005109
David Neto22f144c2017-06-12 14:26:21 -04005110 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5111 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005112 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005113 }
5114
David Neto87846742018-04-11 17:36:22 -04005115 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5116 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005117 SPIRVInstList.insert(InsertPoint, ExtInst);
5118
David Neto3fbb4072017-10-16 11:28:14 -04005119 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5120 if (IndirectExtInst != kGlslExtInstBad) {
5121 // Generate one more instruction that uses the result of the extended
5122 // instruction. Its result id is one more than the id of the
5123 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005124 LLVMContext &Context =
5125 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005126
David Neto3fbb4072017-10-16 11:28:14 -04005127 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5128 &VMap, &SPIRVInstList, &InsertPoint](
5129 spv::Op opcode, Constant *constant) {
5130 //
5131 // Generate instruction like:
5132 // result = opcode constant <extinst-result>
5133 //
5134 // Ops[0] = Result Type ID
5135 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5136 // Ops[2] = Operand 1 ;; the result of the extended instruction
5137 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005138
David Neto3fbb4072017-10-16 11:28:14 -04005139 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005140 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005141
5142 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5143 constant = ConstantVector::getSplat(
5144 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5145 }
David Neto257c3892018-04-11 13:19:45 -04005146 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005147
5148 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005149 InsertPoint, new SPIRVInstruction(
5150 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005151 };
5152
5153 switch (IndirectExtInst) {
5154 case glsl::ExtInstFindUMsb: // Implementing clz
5155 generate_extra_inst(
5156 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5157 break;
5158 case glsl::ExtInstAcos: // Implementing acospi
5159 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005160 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005161 case glsl::ExtInstAtan2: // Implementing atan2pi
5162 generate_extra_inst(
5163 spv::OpFMul,
5164 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5165 break;
5166
5167 default:
5168 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005169 }
David Neto22f144c2017-06-12 14:26:21 -04005170 }
David Neto3fbb4072017-10-16 11:28:14 -04005171
David Neto862b7d82018-06-14 18:48:37 -04005172 } else if (callee_name.equals("_Z8popcounti") ||
5173 callee_name.equals("_Z8popcountj") ||
5174 callee_name.equals("_Z8popcountDv2_i") ||
5175 callee_name.equals("_Z8popcountDv3_i") ||
5176 callee_name.equals("_Z8popcountDv4_i") ||
5177 callee_name.equals("_Z8popcountDv2_j") ||
5178 callee_name.equals("_Z8popcountDv3_j") ||
5179 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005180 //
5181 // Generate OpBitCount
5182 //
5183 // Ops[0] = Result Type ID
5184 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005185 SPIRVOperandList Ops;
5186 Ops << MkId(lookupType(Call->getType()))
5187 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005188
5189 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005190 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005191 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005192
David Neto862b7d82018-06-14 18:48:37 -04005193 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005194
5195 // Generate an OpCompositeConstruct
5196 SPIRVOperandList Ops;
5197
5198 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005199 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005200
5201 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005202 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005203 }
5204
5205 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005206 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5207 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005208
Alan Baker202c8c72018-08-13 13:47:44 -04005209 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5210
5211 // We have already mapped the call's result value to an ID.
5212 // Don't generate any code now.
5213
5214 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005215
5216 // We have already mapped the call's result value to an ID.
5217 // Don't generate any code now.
5218
David Neto22f144c2017-06-12 14:26:21 -04005219 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05005220 if (Call->getType()->isPointerTy()) {
5221 // Functions returning pointers require variable pointers.
5222 setVariablePointersCapabilities(
5223 Call->getType()->getPointerAddressSpace());
5224 }
5225
David Neto22f144c2017-06-12 14:26:21 -04005226 //
5227 // Generate OpFunctionCall.
5228 //
5229
5230 // Ops[0] = Result Type ID
5231 // Ops[1] = Callee Function ID
5232 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5233 SPIRVOperandList Ops;
5234
David Neto862b7d82018-06-14 18:48:37 -04005235 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005236
5237 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005238 if (CalleeID == 0) {
5239 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005240 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005241 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5242 // causes an infinite loop. Instead, go ahead and generate
5243 // the bad function call. A validator will catch the 0-Id.
5244 // llvm_unreachable("Can't translate function call");
5245 }
David Neto22f144c2017-06-12 14:26:21 -04005246
David Neto257c3892018-04-11 13:19:45 -04005247 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005248
David Neto22f144c2017-06-12 14:26:21 -04005249 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5250 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05005251 auto *operand = Call->getOperand(i);
5252 if (operand->getType()->isPointerTy()) {
5253 auto sc =
5254 GetStorageClass(operand->getType()->getPointerAddressSpace());
5255 if (sc == spv::StorageClassStorageBuffer) {
5256 // Passing SSBO by reference requires variable pointers storage
5257 // buffer.
5258 setVariablePointersStorageBuffer(true);
5259 } else if (sc == spv::StorageClassWorkgroup) {
5260 // Workgroup references require variable pointers if they are not
5261 // memory object declarations.
5262 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
5263 // Workgroup accessor represents a variable reference.
5264 if (!operand_call->getCalledFunction()->getName().startswith(
5265 clspv::WorkgroupAccessorFunction()))
5266 setVariablePointers(true);
5267 } else {
5268 // Arguments are function parameters.
5269 if (!isa<Argument>(operand))
5270 setVariablePointers(true);
5271 }
5272 }
5273 }
5274 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04005275 }
5276
David Neto87846742018-04-11 17:36:22 -04005277 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5278 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005279 SPIRVInstList.insert(InsertPoint, CallInst);
5280 }
5281 }
5282 }
5283}
5284
David Neto1a1a0582017-07-07 12:01:44 -04005285void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005286 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005287 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005288 }
David Neto1a1a0582017-07-07 12:01:44 -04005289
5290 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005291
5292 // Find an iterator pointing just past the last decoration.
5293 bool seen_decorations = false;
5294 auto DecoInsertPoint =
5295 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5296 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5297 const bool is_decoration =
5298 Inst->getOpcode() == spv::OpDecorate ||
5299 Inst->getOpcode() == spv::OpMemberDecorate;
5300 if (is_decoration) {
5301 seen_decorations = true;
5302 return false;
5303 } else {
5304 return seen_decorations;
5305 }
5306 });
5307
David Netoc6f3ab22018-04-06 18:02:31 -04005308 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5309 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005310 for (auto *type : getTypesNeedingArrayStride()) {
5311 Type *elemTy = nullptr;
5312 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5313 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005314 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005315 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005316 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005317 elemTy = seqTy->getSequentialElementType();
5318 } else {
5319 errs() << "Unhandled strided type " << *type << "\n";
5320 llvm_unreachable("Unhandled strided type");
5321 }
David Neto1a1a0582017-07-07 12:01:44 -04005322
5323 // Ops[0] = Target ID
5324 // Ops[1] = Decoration (ArrayStride)
5325 // Ops[2] = Stride number (Literal Number)
5326 SPIRVOperandList Ops;
5327
David Neto85082642018-03-24 06:55:20 -07005328 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005329 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005330
5331 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5332 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005333
David Neto87846742018-04-11 17:36:22 -04005334 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005335 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5336 }
David Netoc6f3ab22018-04-06 18:02:31 -04005337
5338 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005339 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5340 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005341 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005342 SPIRVOperandList Ops;
5343 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5344 << MkNum(arg_info.spec_id);
5345 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005346 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005347 }
David Neto1a1a0582017-07-07 12:01:44 -04005348}
5349
David Neto22f144c2017-06-12 14:26:21 -04005350glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5351 return StringSwitch<glsl::ExtInst>(Name)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005352 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5353 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5354 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5355 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005356 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5357 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5358 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5359 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005360 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5361 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5362 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5363 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
Kévin Petit495255d2019-03-06 13:56:48 +00005364 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5365 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5366 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5367 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5368 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5369 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5370 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5371 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005372 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5373 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5374 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5375 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5376 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5377 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5378 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5379 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005380 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5381 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5382 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5383 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5384 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5385 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5386 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5387 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005388 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5389 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5390 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5391 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005392 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5393 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5394 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5395 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5396 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5397 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5398 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5399 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005400 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5401 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5402 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5403 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5404 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5405 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5406 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5407 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005408 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5409 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5410 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5411 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5412 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5413 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5414 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5415 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005416 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5417 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5418 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5419 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5420 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005421 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5422 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5423 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5424 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5425 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5426 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5427 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5428 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005429 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5430 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5431 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5432 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5433 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5434 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5435 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5436 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005437 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5438 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5439 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5440 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5441 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5442 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5443 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5444 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005445 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5446 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5447 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5448 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5449 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5450 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5451 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5452 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5453 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5454 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5455 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5456 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5457 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5458 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5459 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5460 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5461 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5462 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5463 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5464 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5465 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5466 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5467 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5468 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5469 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5470 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5471 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5472 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5473 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5474 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5475 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5476 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5477 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5478 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5479 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5480 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5481 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5482 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5483 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5484 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5485 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005486 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005487 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5488 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5489 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5490 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5491 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5492 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5493 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5494 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5495 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5496 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5497 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5498 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5499 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5500 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5501 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5502 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5503 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005504 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005505 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005506 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005507 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005508 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005509 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5510 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005511 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005512 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5513 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5514 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005515 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5516 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5517 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5518 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005519 .Default(kGlslExtInstBad);
5520}
5521
5522glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5523 // Check indirect cases.
5524 return StringSwitch<glsl::ExtInst>(Name)
5525 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5526 // Use exact match on float arg because these need a multiply
5527 // of a constant of the right floating point type.
5528 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5529 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5530 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5531 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5532 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5533 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5534 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5535 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005536 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5537 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5538 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5539 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005540 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5541 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5542 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5543 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5544 .Default(kGlslExtInstBad);
5545}
5546
alan-bakerb6b09dc2018-11-08 16:59:28 -05005547glsl::ExtInst
5548SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005549 auto direct = getExtInstEnum(Name);
5550 if (direct != kGlslExtInstBad)
5551 return direct;
5552 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005553}
5554
5555void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5556 out << "%" << Inst->getResultID();
5557}
5558
5559void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5560 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5561 out << "\t" << spv::getOpName(Opcode);
5562}
5563
5564void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5565 SPIRVOperandType OpTy = Op->getType();
5566 switch (OpTy) {
5567 default: {
5568 llvm_unreachable("Unsupported SPIRV Operand Type???");
5569 break;
5570 }
5571 case SPIRVOperandType::NUMBERID: {
5572 out << "%" << Op->getNumID();
5573 break;
5574 }
5575 case SPIRVOperandType::LITERAL_STRING: {
5576 out << "\"" << Op->getLiteralStr() << "\"";
5577 break;
5578 }
5579 case SPIRVOperandType::LITERAL_INTEGER: {
5580 // TODO: Handle LiteralNum carefully.
Kévin Petite7d0cce2018-10-31 12:38:56 +00005581 auto Words = Op->getLiteralNum();
5582 auto NumWords = Words.size();
5583
5584 if (NumWords == 1) {
5585 out << Words[0];
5586 } else if (NumWords == 2) {
5587 uint64_t Val = (static_cast<uint64_t>(Words[1]) << 32) | Words[0];
5588 out << Val;
5589 } else {
5590 llvm_unreachable("Handle printing arbitrary precision integer literals.");
David Neto22f144c2017-06-12 14:26:21 -04005591 }
5592 break;
5593 }
5594 case SPIRVOperandType::LITERAL_FLOAT: {
5595 // TODO: Handle LiteralNum carefully.
5596 for (auto Word : Op->getLiteralNum()) {
5597 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5598 SmallString<8> Str;
5599 APF.toString(Str, 6, 2);
5600 out << Str;
5601 }
5602 break;
5603 }
5604 }
5605}
5606
5607void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5608 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5609 out << spv::getCapabilityName(Cap);
5610}
5611
5612void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5613 auto LiteralNum = Op->getLiteralNum();
5614 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5615 out << glsl::getExtInstName(Ext);
5616}
5617
5618void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5619 spv::AddressingModel AddrModel =
5620 static_cast<spv::AddressingModel>(Op->getNumID());
5621 out << spv::getAddressingModelName(AddrModel);
5622}
5623
5624void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5625 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5626 out << spv::getMemoryModelName(MemModel);
5627}
5628
5629void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5630 spv::ExecutionModel ExecModel =
5631 static_cast<spv::ExecutionModel>(Op->getNumID());
5632 out << spv::getExecutionModelName(ExecModel);
5633}
5634
5635void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5636 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5637 out << spv::getExecutionModeName(ExecMode);
5638}
5639
5640void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005641 spv::SourceLanguage SourceLang =
5642 static_cast<spv::SourceLanguage>(Op->getNumID());
David Neto22f144c2017-06-12 14:26:21 -04005643 out << spv::getSourceLanguageName(SourceLang);
5644}
5645
5646void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5647 spv::FunctionControlMask FuncCtrl =
5648 static_cast<spv::FunctionControlMask>(Op->getNumID());
5649 out << spv::getFunctionControlName(FuncCtrl);
5650}
5651
5652void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5653 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5654 out << getStorageClassName(StClass);
5655}
5656
5657void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5658 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5659 out << getDecorationName(Deco);
5660}
5661
5662void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5663 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5664 out << getBuiltInName(BIn);
5665}
5666
5667void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5668 spv::SelectionControlMask BIn =
5669 static_cast<spv::SelectionControlMask>(Op->getNumID());
5670 out << getSelectionControlName(BIn);
5671}
5672
5673void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5674 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5675 out << getLoopControlName(BIn);
5676}
5677
5678void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5679 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5680 out << getDimName(DIM);
5681}
5682
5683void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5684 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5685 out << getImageFormatName(Format);
5686}
5687
5688void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5689 out << spv::getMemoryAccessName(
5690 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5691}
5692
5693void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5694 auto LiteralNum = Op->getLiteralNum();
5695 spv::ImageOperandsMask Type =
5696 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5697 out << getImageOperandsName(Type);
5698}
5699
5700void SPIRVProducerPass::WriteSPIRVAssembly() {
5701 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5702
5703 for (auto Inst : SPIRVInstList) {
5704 SPIRVOperandList Ops = Inst->getOperands();
5705 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5706
5707 switch (Opcode) {
5708 default: {
5709 llvm_unreachable("Unsupported SPIRV instruction");
5710 break;
5711 }
5712 case spv::OpCapability: {
5713 // Ops[0] = Capability
5714 PrintOpcode(Inst);
5715 out << " ";
5716 PrintCapability(Ops[0]);
5717 out << "\n";
5718 break;
5719 }
5720 case spv::OpMemoryModel: {
5721 // Ops[0] = Addressing Model
5722 // Ops[1] = Memory Model
5723 PrintOpcode(Inst);
5724 out << " ";
5725 PrintAddrModel(Ops[0]);
5726 out << " ";
5727 PrintMemModel(Ops[1]);
5728 out << "\n";
5729 break;
5730 }
5731 case spv::OpEntryPoint: {
5732 // Ops[0] = Execution Model
5733 // Ops[1] = EntryPoint ID
5734 // Ops[2] = Name (Literal String)
5735 // Ops[3] ... Ops[n] = Interface ID
5736 PrintOpcode(Inst);
5737 out << " ";
5738 PrintExecModel(Ops[0]);
5739 for (uint32_t i = 1; i < Ops.size(); i++) {
5740 out << " ";
5741 PrintOperand(Ops[i]);
5742 }
5743 out << "\n";
5744 break;
5745 }
5746 case spv::OpExecutionMode: {
5747 // Ops[0] = Entry Point ID
5748 // Ops[1] = Execution Mode
5749 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5750 PrintOpcode(Inst);
5751 out << " ";
5752 PrintOperand(Ops[0]);
5753 out << " ";
5754 PrintExecMode(Ops[1]);
5755 for (uint32_t i = 2; i < Ops.size(); i++) {
5756 out << " ";
5757 PrintOperand(Ops[i]);
5758 }
5759 out << "\n";
5760 break;
5761 }
5762 case spv::OpSource: {
5763 // Ops[0] = SourceLanguage ID
5764 // Ops[1] = Version (LiteralNum)
5765 PrintOpcode(Inst);
5766 out << " ";
5767 PrintSourceLanguage(Ops[0]);
5768 out << " ";
5769 PrintOperand(Ops[1]);
5770 out << "\n";
5771 break;
5772 }
5773 case spv::OpDecorate: {
5774 // Ops[0] = Target ID
5775 // Ops[1] = Decoration (Block or BufferBlock)
5776 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5777 PrintOpcode(Inst);
5778 out << " ";
5779 PrintOperand(Ops[0]);
5780 out << " ";
5781 PrintDecoration(Ops[1]);
5782 // Handle BuiltIn OpDecorate specially.
5783 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5784 out << " ";
5785 PrintBuiltIn(Ops[2]);
5786 } else {
5787 for (uint32_t i = 2; i < Ops.size(); i++) {
5788 out << " ";
5789 PrintOperand(Ops[i]);
5790 }
5791 }
5792 out << "\n";
5793 break;
5794 }
5795 case spv::OpMemberDecorate: {
5796 // Ops[0] = Structure Type ID
5797 // Ops[1] = Member Index(Literal Number)
5798 // Ops[2] = Decoration
5799 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5800 PrintOpcode(Inst);
5801 out << " ";
5802 PrintOperand(Ops[0]);
5803 out << " ";
5804 PrintOperand(Ops[1]);
5805 out << " ";
5806 PrintDecoration(Ops[2]);
5807 for (uint32_t i = 3; i < Ops.size(); i++) {
5808 out << " ";
5809 PrintOperand(Ops[i]);
5810 }
5811 out << "\n";
5812 break;
5813 }
5814 case spv::OpTypePointer: {
5815 // Ops[0] = Storage Class
5816 // Ops[1] = Element Type ID
5817 PrintResID(Inst);
5818 out << " = ";
5819 PrintOpcode(Inst);
5820 out << " ";
5821 PrintStorageClass(Ops[0]);
5822 out << " ";
5823 PrintOperand(Ops[1]);
5824 out << "\n";
5825 break;
5826 }
5827 case spv::OpTypeImage: {
5828 // Ops[0] = Sampled Type ID
5829 // Ops[1] = Dim ID
5830 // Ops[2] = Depth (Literal Number)
5831 // Ops[3] = Arrayed (Literal Number)
5832 // Ops[4] = MS (Literal Number)
5833 // Ops[5] = Sampled (Literal Number)
5834 // Ops[6] = Image Format ID
5835 PrintResID(Inst);
5836 out << " = ";
5837 PrintOpcode(Inst);
5838 out << " ";
5839 PrintOperand(Ops[0]);
5840 out << " ";
5841 PrintDimensionality(Ops[1]);
5842 out << " ";
5843 PrintOperand(Ops[2]);
5844 out << " ";
5845 PrintOperand(Ops[3]);
5846 out << " ";
5847 PrintOperand(Ops[4]);
5848 out << " ";
5849 PrintOperand(Ops[5]);
5850 out << " ";
5851 PrintImageFormat(Ops[6]);
5852 out << "\n";
5853 break;
5854 }
5855 case spv::OpFunction: {
5856 // Ops[0] : Result Type ID
5857 // Ops[1] : Function Control
5858 // Ops[2] : Function Type ID
5859 PrintResID(Inst);
5860 out << " = ";
5861 PrintOpcode(Inst);
5862 out << " ";
5863 PrintOperand(Ops[0]);
5864 out << " ";
5865 PrintFuncCtrl(Ops[1]);
5866 out << " ";
5867 PrintOperand(Ops[2]);
5868 out << "\n";
5869 break;
5870 }
5871 case spv::OpSelectionMerge: {
5872 // Ops[0] = Merge Block ID
5873 // Ops[1] = Selection Control
5874 PrintOpcode(Inst);
5875 out << " ";
5876 PrintOperand(Ops[0]);
5877 out << " ";
5878 PrintSelectionControl(Ops[1]);
5879 out << "\n";
5880 break;
5881 }
5882 case spv::OpLoopMerge: {
5883 // Ops[0] = Merge Block ID
5884 // Ops[1] = Continue Target ID
5885 // Ops[2] = Selection Control
5886 PrintOpcode(Inst);
5887 out << " ";
5888 PrintOperand(Ops[0]);
5889 out << " ";
5890 PrintOperand(Ops[1]);
5891 out << " ";
5892 PrintLoopControl(Ops[2]);
5893 out << "\n";
5894 break;
5895 }
5896 case spv::OpImageSampleExplicitLod: {
5897 // Ops[0] = Result Type ID
5898 // Ops[1] = Sampled Image ID
5899 // Ops[2] = Coordinate ID
5900 // Ops[3] = Image Operands Type ID
5901 // Ops[4] ... Ops[n] = Operands ID
5902 PrintResID(Inst);
5903 out << " = ";
5904 PrintOpcode(Inst);
5905 for (uint32_t i = 0; i < 3; i++) {
5906 out << " ";
5907 PrintOperand(Ops[i]);
5908 }
5909 out << " ";
5910 PrintImageOperandsType(Ops[3]);
5911 for (uint32_t i = 4; i < Ops.size(); i++) {
5912 out << " ";
5913 PrintOperand(Ops[i]);
5914 }
5915 out << "\n";
5916 break;
5917 }
5918 case spv::OpVariable: {
5919 // Ops[0] : Result Type ID
5920 // Ops[1] : Storage Class
5921 // Ops[2] ... Ops[n] = Initializer IDs
5922 PrintResID(Inst);
5923 out << " = ";
5924 PrintOpcode(Inst);
5925 out << " ";
5926 PrintOperand(Ops[0]);
5927 out << " ";
5928 PrintStorageClass(Ops[1]);
5929 for (uint32_t i = 2; i < Ops.size(); i++) {
5930 out << " ";
5931 PrintOperand(Ops[i]);
5932 }
5933 out << "\n";
5934 break;
5935 }
5936 case spv::OpExtInst: {
5937 // Ops[0] = Result Type ID
5938 // Ops[1] = Set ID (OpExtInstImport ID)
5939 // Ops[2] = Instruction Number (Literal Number)
5940 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5941 PrintResID(Inst);
5942 out << " = ";
5943 PrintOpcode(Inst);
5944 out << " ";
5945 PrintOperand(Ops[0]);
5946 out << " ";
5947 PrintOperand(Ops[1]);
5948 out << " ";
5949 PrintExtInst(Ops[2]);
5950 for (uint32_t i = 3; i < Ops.size(); i++) {
5951 out << " ";
5952 PrintOperand(Ops[i]);
5953 }
5954 out << "\n";
5955 break;
5956 }
5957 case spv::OpCopyMemory: {
5958 // Ops[0] = Addressing Model
5959 // Ops[1] = Memory Model
5960 PrintOpcode(Inst);
5961 out << " ";
5962 PrintOperand(Ops[0]);
5963 out << " ";
5964 PrintOperand(Ops[1]);
5965 out << " ";
5966 PrintMemoryAccess(Ops[2]);
5967 out << " ";
5968 PrintOperand(Ops[3]);
5969 out << "\n";
5970 break;
5971 }
5972 case spv::OpExtension:
5973 case spv::OpControlBarrier:
5974 case spv::OpMemoryBarrier:
5975 case spv::OpBranch:
5976 case spv::OpBranchConditional:
5977 case spv::OpStore:
5978 case spv::OpImageWrite:
5979 case spv::OpReturnValue:
5980 case spv::OpReturn:
5981 case spv::OpFunctionEnd: {
5982 PrintOpcode(Inst);
5983 for (uint32_t i = 0; i < Ops.size(); i++) {
5984 out << " ";
5985 PrintOperand(Ops[i]);
5986 }
5987 out << "\n";
5988 break;
5989 }
5990 case spv::OpExtInstImport:
5991 case spv::OpTypeRuntimeArray:
5992 case spv::OpTypeStruct:
5993 case spv::OpTypeSampler:
5994 case spv::OpTypeSampledImage:
5995 case spv::OpTypeInt:
5996 case spv::OpTypeFloat:
5997 case spv::OpTypeArray:
5998 case spv::OpTypeVector:
5999 case spv::OpTypeBool:
6000 case spv::OpTypeVoid:
6001 case spv::OpTypeFunction:
6002 case spv::OpFunctionParameter:
6003 case spv::OpLabel:
6004 case spv::OpPhi:
6005 case spv::OpLoad:
6006 case spv::OpSelect:
6007 case spv::OpAccessChain:
6008 case spv::OpPtrAccessChain:
6009 case spv::OpInBoundsAccessChain:
6010 case spv::OpUConvert:
6011 case spv::OpSConvert:
6012 case spv::OpConvertFToU:
6013 case spv::OpConvertFToS:
6014 case spv::OpConvertUToF:
6015 case spv::OpConvertSToF:
6016 case spv::OpFConvert:
6017 case spv::OpConvertPtrToU:
6018 case spv::OpConvertUToPtr:
6019 case spv::OpBitcast:
6020 case spv::OpIAdd:
6021 case spv::OpFAdd:
6022 case spv::OpISub:
6023 case spv::OpFSub:
6024 case spv::OpIMul:
6025 case spv::OpFMul:
6026 case spv::OpUDiv:
6027 case spv::OpSDiv:
6028 case spv::OpFDiv:
6029 case spv::OpUMod:
6030 case spv::OpSRem:
6031 case spv::OpFRem:
6032 case spv::OpBitwiseOr:
6033 case spv::OpBitwiseXor:
6034 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006035 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006036 case spv::OpShiftLeftLogical:
6037 case spv::OpShiftRightLogical:
6038 case spv::OpShiftRightArithmetic:
6039 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006040 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006041 case spv::OpCompositeExtract:
6042 case spv::OpVectorExtractDynamic:
6043 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006044 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006045 case spv::OpVectorInsertDynamic:
6046 case spv::OpVectorShuffle:
6047 case spv::OpIEqual:
6048 case spv::OpINotEqual:
6049 case spv::OpUGreaterThan:
6050 case spv::OpUGreaterThanEqual:
6051 case spv::OpULessThan:
6052 case spv::OpULessThanEqual:
6053 case spv::OpSGreaterThan:
6054 case spv::OpSGreaterThanEqual:
6055 case spv::OpSLessThan:
6056 case spv::OpSLessThanEqual:
6057 case spv::OpFOrdEqual:
6058 case spv::OpFOrdGreaterThan:
6059 case spv::OpFOrdGreaterThanEqual:
6060 case spv::OpFOrdLessThan:
6061 case spv::OpFOrdLessThanEqual:
6062 case spv::OpFOrdNotEqual:
6063 case spv::OpFUnordEqual:
6064 case spv::OpFUnordGreaterThan:
6065 case spv::OpFUnordGreaterThanEqual:
6066 case spv::OpFUnordLessThan:
6067 case spv::OpFUnordLessThanEqual:
6068 case spv::OpFUnordNotEqual:
6069 case spv::OpSampledImage:
6070 case spv::OpFunctionCall:
6071 case spv::OpConstantTrue:
6072 case spv::OpConstantFalse:
6073 case spv::OpConstant:
6074 case spv::OpSpecConstant:
6075 case spv::OpConstantComposite:
6076 case spv::OpSpecConstantComposite:
6077 case spv::OpConstantNull:
6078 case spv::OpLogicalOr:
6079 case spv::OpLogicalAnd:
6080 case spv::OpLogicalNot:
6081 case spv::OpLogicalNotEqual:
6082 case spv::OpUndef:
6083 case spv::OpIsInf:
6084 case spv::OpIsNan:
6085 case spv::OpAny:
6086 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04006087 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006088 case spv::OpAtomicIAdd:
6089 case spv::OpAtomicISub:
6090 case spv::OpAtomicExchange:
6091 case spv::OpAtomicIIncrement:
6092 case spv::OpAtomicIDecrement:
6093 case spv::OpAtomicCompareExchange:
6094 case spv::OpAtomicUMin:
6095 case spv::OpAtomicSMin:
6096 case spv::OpAtomicUMax:
6097 case spv::OpAtomicSMax:
6098 case spv::OpAtomicAnd:
6099 case spv::OpAtomicOr:
6100 case spv::OpAtomicXor:
6101 case spv::OpDot: {
6102 PrintResID(Inst);
6103 out << " = ";
6104 PrintOpcode(Inst);
6105 for (uint32_t i = 0; i < Ops.size(); i++) {
6106 out << " ";
6107 PrintOperand(Ops[i]);
6108 }
6109 out << "\n";
6110 break;
6111 }
6112 }
6113 }
6114}
6115
6116void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006117 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006118}
6119
6120void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6121 WriteOneWord(Inst->getResultID());
6122}
6123
6124void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6125 // High 16 bit : Word Count
6126 // Low 16 bit : Opcode
6127 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04006128 const uint32_t count = Inst->getWordCount();
6129 if (count > 65535) {
6130 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
6131 llvm_unreachable("Word count too high");
6132 }
David Neto22f144c2017-06-12 14:26:21 -04006133 Word |= Inst->getWordCount() << 16;
6134 WriteOneWord(Word);
6135}
6136
6137void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6138 SPIRVOperandType OpTy = Op->getType();
6139 switch (OpTy) {
6140 default: {
6141 llvm_unreachable("Unsupported SPIRV Operand Type???");
6142 break;
6143 }
6144 case SPIRVOperandType::NUMBERID: {
6145 WriteOneWord(Op->getNumID());
6146 break;
6147 }
6148 case SPIRVOperandType::LITERAL_STRING: {
6149 std::string Str = Op->getLiteralStr();
6150 const char *Data = Str.c_str();
6151 size_t WordSize = Str.size() / 4;
6152 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6153 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6154 }
6155
6156 uint32_t Remainder = Str.size() % 4;
6157 uint32_t LastWord = 0;
6158 if (Remainder) {
6159 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6160 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6161 }
6162 }
6163
6164 WriteOneWord(LastWord);
6165 break;
6166 }
6167 case SPIRVOperandType::LITERAL_INTEGER:
6168 case SPIRVOperandType::LITERAL_FLOAT: {
6169 auto LiteralNum = Op->getLiteralNum();
6170 // TODO: Handle LiteranNum carefully.
6171 for (auto Word : LiteralNum) {
6172 WriteOneWord(Word);
6173 }
6174 break;
6175 }
6176 }
6177}
6178
6179void SPIRVProducerPass::WriteSPIRVBinary() {
6180 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6181
6182 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006183 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006184 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6185
6186 switch (Opcode) {
6187 default: {
David Neto5c22a252018-03-15 16:07:41 -04006188 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006189 llvm_unreachable("Unsupported SPIRV instruction");
6190 break;
6191 }
6192 case spv::OpCapability:
6193 case spv::OpExtension:
6194 case spv::OpMemoryModel:
6195 case spv::OpEntryPoint:
6196 case spv::OpExecutionMode:
6197 case spv::OpSource:
6198 case spv::OpDecorate:
6199 case spv::OpMemberDecorate:
6200 case spv::OpBranch:
6201 case spv::OpBranchConditional:
6202 case spv::OpSelectionMerge:
6203 case spv::OpLoopMerge:
6204 case spv::OpStore:
6205 case spv::OpImageWrite:
6206 case spv::OpReturnValue:
6207 case spv::OpControlBarrier:
6208 case spv::OpMemoryBarrier:
6209 case spv::OpReturn:
6210 case spv::OpFunctionEnd:
6211 case spv::OpCopyMemory: {
6212 WriteWordCountAndOpcode(Inst);
6213 for (uint32_t i = 0; i < Ops.size(); i++) {
6214 WriteOperand(Ops[i]);
6215 }
6216 break;
6217 }
6218 case spv::OpTypeBool:
6219 case spv::OpTypeVoid:
6220 case spv::OpTypeSampler:
6221 case spv::OpLabel:
6222 case spv::OpExtInstImport:
6223 case spv::OpTypePointer:
6224 case spv::OpTypeRuntimeArray:
6225 case spv::OpTypeStruct:
6226 case spv::OpTypeImage:
6227 case spv::OpTypeSampledImage:
6228 case spv::OpTypeInt:
6229 case spv::OpTypeFloat:
6230 case spv::OpTypeArray:
6231 case spv::OpTypeVector:
6232 case spv::OpTypeFunction: {
6233 WriteWordCountAndOpcode(Inst);
6234 WriteResultID(Inst);
6235 for (uint32_t i = 0; i < Ops.size(); i++) {
6236 WriteOperand(Ops[i]);
6237 }
6238 break;
6239 }
6240 case spv::OpFunction:
6241 case spv::OpFunctionParameter:
6242 case spv::OpAccessChain:
6243 case spv::OpPtrAccessChain:
6244 case spv::OpInBoundsAccessChain:
6245 case spv::OpUConvert:
6246 case spv::OpSConvert:
6247 case spv::OpConvertFToU:
6248 case spv::OpConvertFToS:
6249 case spv::OpConvertUToF:
6250 case spv::OpConvertSToF:
6251 case spv::OpFConvert:
6252 case spv::OpConvertPtrToU:
6253 case spv::OpConvertUToPtr:
6254 case spv::OpBitcast:
6255 case spv::OpIAdd:
6256 case spv::OpFAdd:
6257 case spv::OpISub:
6258 case spv::OpFSub:
6259 case spv::OpIMul:
6260 case spv::OpFMul:
6261 case spv::OpUDiv:
6262 case spv::OpSDiv:
6263 case spv::OpFDiv:
6264 case spv::OpUMod:
6265 case spv::OpSRem:
6266 case spv::OpFRem:
6267 case spv::OpBitwiseOr:
6268 case spv::OpBitwiseXor:
6269 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006270 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006271 case spv::OpShiftLeftLogical:
6272 case spv::OpShiftRightLogical:
6273 case spv::OpShiftRightArithmetic:
6274 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006275 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006276 case spv::OpCompositeExtract:
6277 case spv::OpVectorExtractDynamic:
6278 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006279 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006280 case spv::OpVectorInsertDynamic:
6281 case spv::OpVectorShuffle:
6282 case spv::OpIEqual:
6283 case spv::OpINotEqual:
6284 case spv::OpUGreaterThan:
6285 case spv::OpUGreaterThanEqual:
6286 case spv::OpULessThan:
6287 case spv::OpULessThanEqual:
6288 case spv::OpSGreaterThan:
6289 case spv::OpSGreaterThanEqual:
6290 case spv::OpSLessThan:
6291 case spv::OpSLessThanEqual:
6292 case spv::OpFOrdEqual:
6293 case spv::OpFOrdGreaterThan:
6294 case spv::OpFOrdGreaterThanEqual:
6295 case spv::OpFOrdLessThan:
6296 case spv::OpFOrdLessThanEqual:
6297 case spv::OpFOrdNotEqual:
6298 case spv::OpFUnordEqual:
6299 case spv::OpFUnordGreaterThan:
6300 case spv::OpFUnordGreaterThanEqual:
6301 case spv::OpFUnordLessThan:
6302 case spv::OpFUnordLessThanEqual:
6303 case spv::OpFUnordNotEqual:
6304 case spv::OpExtInst:
6305 case spv::OpIsInf:
6306 case spv::OpIsNan:
6307 case spv::OpAny:
6308 case spv::OpAll:
6309 case spv::OpUndef:
6310 case spv::OpConstantNull:
6311 case spv::OpLogicalOr:
6312 case spv::OpLogicalAnd:
6313 case spv::OpLogicalNot:
6314 case spv::OpLogicalNotEqual:
6315 case spv::OpConstantComposite:
6316 case spv::OpSpecConstantComposite:
6317 case spv::OpConstantTrue:
6318 case spv::OpConstantFalse:
6319 case spv::OpConstant:
6320 case spv::OpSpecConstant:
6321 case spv::OpVariable:
6322 case spv::OpFunctionCall:
6323 case spv::OpSampledImage:
6324 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006325 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006326 case spv::OpSelect:
6327 case spv::OpPhi:
6328 case spv::OpLoad:
6329 case spv::OpAtomicIAdd:
6330 case spv::OpAtomicISub:
6331 case spv::OpAtomicExchange:
6332 case spv::OpAtomicIIncrement:
6333 case spv::OpAtomicIDecrement:
6334 case spv::OpAtomicCompareExchange:
6335 case spv::OpAtomicUMin:
6336 case spv::OpAtomicSMin:
6337 case spv::OpAtomicUMax:
6338 case spv::OpAtomicSMax:
6339 case spv::OpAtomicAnd:
6340 case spv::OpAtomicOr:
6341 case spv::OpAtomicXor:
6342 case spv::OpDot: {
6343 WriteWordCountAndOpcode(Inst);
6344 WriteOperand(Ops[0]);
6345 WriteResultID(Inst);
6346 for (uint32_t i = 1; i < Ops.size(); i++) {
6347 WriteOperand(Ops[i]);
6348 }
6349 break;
6350 }
6351 }
6352 }
6353}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006354
alan-bakerb6b09dc2018-11-08 16:59:28 -05006355bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04006356 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05006357 case Type::HalfTyID:
6358 case Type::FloatTyID:
6359 case Type::DoubleTyID:
6360 case Type::IntegerTyID:
6361 case Type::VectorTyID:
6362 return true;
6363 case Type::PointerTyID: {
6364 const PointerType *pointer_type = cast<PointerType>(type);
6365 if (pointer_type->getPointerAddressSpace() !=
6366 AddressSpace::UniformConstant) {
6367 auto pointee_type = pointer_type->getPointerElementType();
6368 if (pointee_type->isStructTy() &&
6369 cast<StructType>(pointee_type)->isOpaque()) {
6370 // Images and samplers are not nullable.
6371 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006372 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04006373 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05006374 return true;
6375 }
6376 case Type::ArrayTyID:
6377 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6378 case Type::StructTyID: {
6379 const StructType *struct_type = cast<StructType>(type);
6380 // Images and samplers are not nullable.
6381 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04006382 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05006383 for (const auto element : struct_type->elements()) {
6384 if (!IsTypeNullable(element))
6385 return false;
6386 }
6387 return true;
6388 }
6389 default:
6390 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04006391 }
6392}
Alan Bakerfcda9482018-10-02 17:09:59 -04006393
6394void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6395 if (auto *offsets_md =
6396 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6397 // Metdata is stored as key-value pair operands. The first element of each
6398 // operand is the type and the second is a vector of offsets.
6399 for (const auto *operand : offsets_md->operands()) {
6400 const auto *pair = cast<MDTuple>(operand);
6401 auto *type =
6402 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6403 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6404 std::vector<uint32_t> offsets;
6405 for (const Metadata *offset_md : offset_vector->operands()) {
6406 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05006407 offsets.push_back(static_cast<uint32_t>(
6408 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04006409 }
6410 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6411 }
6412 }
6413
6414 if (auto *sizes_md =
6415 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6416 // Metadata is stored as key-value pair operands. The first element of each
6417 // operand is the type and the second is a triple of sizes: type size in
6418 // bits, store size and alloc size.
6419 for (const auto *operand : sizes_md->operands()) {
6420 const auto *pair = cast<MDTuple>(operand);
6421 auto *type =
6422 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6423 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6424 uint64_t type_size_in_bits =
6425 cast<ConstantInt>(
6426 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6427 ->getZExtValue();
6428 uint64_t type_store_size =
6429 cast<ConstantInt>(
6430 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6431 ->getZExtValue();
6432 uint64_t type_alloc_size =
6433 cast<ConstantInt>(
6434 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6435 ->getZExtValue();
6436 RemappedUBOTypeSizes.insert(std::make_pair(
6437 type, std::make_tuple(type_size_in_bits, type_store_size,
6438 type_alloc_size)));
6439 }
6440 }
6441}
6442
6443uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6444 const DataLayout &DL) {
6445 auto iter = RemappedUBOTypeSizes.find(type);
6446 if (iter != RemappedUBOTypeSizes.end()) {
6447 return std::get<0>(iter->second);
6448 }
6449
6450 return DL.getTypeSizeInBits(type);
6451}
6452
6453uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6454 auto iter = RemappedUBOTypeSizes.find(type);
6455 if (iter != RemappedUBOTypeSizes.end()) {
6456 return std::get<1>(iter->second);
6457 }
6458
6459 return DL.getTypeStoreSize(type);
6460}
6461
6462uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6463 auto iter = RemappedUBOTypeSizes.find(type);
6464 if (iter != RemappedUBOTypeSizes.end()) {
6465 return std::get<2>(iter->second);
6466 }
6467
6468 return DL.getTypeAllocSize(type);
6469}
alan-baker5b86ed72019-02-15 08:26:50 -05006470
6471void SPIRVProducerPass::setVariablePointersCapabilities(unsigned address_space) {
6472 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
6473 setVariablePointersStorageBuffer(true);
6474 } else {
6475 setVariablePointers(true);
6476 }
6477}
6478
6479Value *SPIRVProducerPass::GetBasePointer(Value* v) {
6480 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
6481 return GetBasePointer(gep->getPointerOperand());
6482 }
6483
6484 // Conservatively return |v|.
6485 return v;
6486}
6487
6488bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
6489 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
6490 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
6491 if (lhs_call->getCalledFunction()->getName().startswith(
6492 clspv::ResourceAccessorFunction()) &&
6493 rhs_call->getCalledFunction()->getName().startswith(
6494 clspv::ResourceAccessorFunction())) {
6495 // For resource accessors, match descriptor set and binding.
6496 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
6497 lhs_call->getOperand(1) == rhs_call->getOperand(1))
6498 return true;
6499 } else if (lhs_call->getCalledFunction()->getName().startswith(
6500 clspv::WorkgroupAccessorFunction()) &&
6501 rhs_call->getCalledFunction()->getName().startswith(
6502 clspv::WorkgroupAccessorFunction())) {
6503 // For workgroup resources, match spec id.
6504 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
6505 return true;
6506 }
6507 }
6508 }
6509
6510 return false;
6511}
6512
6513bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
6514 assert(inst->getType()->isPointerTy());
6515 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
6516 spv::StorageClassStorageBuffer);
6517 const bool hack_undef = clspv::Option::HackUndef();
6518 if (auto *select = dyn_cast<SelectInst>(inst)) {
6519 auto *true_base = GetBasePointer(select->getTrueValue());
6520 auto *false_base = GetBasePointer(select->getFalseValue());
6521
6522 if (true_base == false_base)
6523 return true;
6524
6525 // If either the true or false operand is a null, then we satisfy the same
6526 // object constraint.
6527 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
6528 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
6529 return true;
6530 }
6531
6532 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
6533 if (false_cst->isNullValue() ||
6534 (hack_undef && isa<UndefValue>(false_base)))
6535 return true;
6536 }
6537
6538 if (sameResource(true_base, false_base))
6539 return true;
6540 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
6541 Value *value = nullptr;
6542 bool ok = true;
6543 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
6544 auto *base = GetBasePointer(phi->getIncomingValue(i));
6545 // Null values satisfy the constraint of selecting of selecting from the
6546 // same object.
6547 if (!value) {
6548 if (auto *cst = dyn_cast<Constant>(base)) {
6549 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
6550 value = base;
6551 } else {
6552 value = base;
6553 }
6554 } else if (base != value) {
6555 if (auto *base_cst = dyn_cast<Constant>(base)) {
6556 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
6557 continue;
6558 }
6559
6560 if (sameResource(value, base))
6561 continue;
6562
6563 // Values don't represent the same base.
6564 ok = false;
6565 }
6566 }
6567
6568 return ok;
6569 }
6570
6571 // Conservatively return false.
6572 return false;
6573}