blob: fff48741a02534aa74188dbf4a3d53c228cb15e8 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto118188e2018-08-24 11:27:54 -040031#include "llvm/ADT/StringSwitch.h"
32#include "llvm/ADT/UniqueVector.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/Pass.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto85082642018-03-24 06:55:20 -070044#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040045
David Neto85082642018-03-24 06:55:20 -070046#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include "clspv/DescriptorMap.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
David Neto85082642018-03-24 06:55:20 -070049#include "clspv/spirv_c_strings.hpp"
50#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040051
David Neto4feb7a42017-10-06 17:29:42 -040052#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070053#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040054#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040055#include "DescriptorCounter.h"
alan-baker56f7aff2019-05-22 08:06:42 -040056#include "NormalizeGlobalVariable.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040057#include "Passes.h"
David Neto48f56a42017-10-06 16:44:25 -040058
David Neto22f144c2017-06-12 14:26:21 -040059#if defined(_MSC_VER)
60#pragma warning(pop)
61#endif
62
63using namespace llvm;
64using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040065using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040066
67namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040068
David Neto862b7d82018-06-14 18:48:37 -040069cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
70 cl::desc("Show resource variable creation"));
71
72// These hacks exist to help transition code generation algorithms
73// without making huge noise in detailed test output.
74const bool Hack_generate_runtime_array_stride_early = true;
75
David Neto3fbb4072017-10-16 11:28:14 -040076// The value of 1/pi. This value is from MSDN
77// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
78const double kOneOverPi = 0.318309886183790671538;
79const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
80
alan-bakerb6b09dc2018-11-08 16:59:28 -050081const char *kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
David Netoab03f432017-11-03 17:00:44 -040082
David Neto22f144c2017-06-12 14:26:21 -040083enum SPIRVOperandType {
84 NUMBERID,
85 LITERAL_INTEGER,
86 LITERAL_STRING,
87 LITERAL_FLOAT
88};
89
90struct SPIRVOperand {
91 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
92 : Type(Ty), LiteralNum(1, Num) {}
93 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
94 : Type(Ty), LiteralStr(Str) {}
95 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
96 : Type(Ty), LiteralStr(Str) {}
97 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
98 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
99
100 SPIRVOperandType getType() { return Type; };
101 uint32_t getNumID() { return LiteralNum[0]; };
102 std::string getLiteralStr() { return LiteralStr; };
103 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
104
David Neto87846742018-04-11 17:36:22 -0400105 uint32_t GetNumWords() const {
106 switch (Type) {
107 case NUMBERID:
108 return 1;
109 case LITERAL_INTEGER:
110 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400111 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400112 case LITERAL_STRING:
113 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400114 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400115 }
116 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
117 }
118
David Neto22f144c2017-06-12 14:26:21 -0400119private:
120 SPIRVOperandType Type;
121 std::string LiteralStr;
122 SmallVector<uint32_t, 4> LiteralNum;
123};
124
David Netoc6f3ab22018-04-06 18:02:31 -0400125class SPIRVOperandList {
126public:
127 SPIRVOperandList() {}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500128 SPIRVOperandList(const SPIRVOperandList &other) = delete;
129 SPIRVOperandList(SPIRVOperandList &&other) {
David Netoc6f3ab22018-04-06 18:02:31 -0400130 contents_ = std::move(other.contents_);
131 other.contents_.clear();
132 }
133 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
134 : contents_(init.begin(), init.end()) {}
135 operator ArrayRef<SPIRVOperand *>() { return contents_; }
136 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500137 void clear() { contents_.clear(); }
David Netoc6f3ab22018-04-06 18:02:31 -0400138 size_t size() const { return contents_.size(); }
139 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
140
David Neto87846742018-04-11 17:36:22 -0400141 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
142 return contents_;
143 }
144
David Netoc6f3ab22018-04-06 18:02:31 -0400145private:
alan-bakerb6b09dc2018-11-08 16:59:28 -0500146 SmallVector<SPIRVOperand *, 8> contents_;
David Netoc6f3ab22018-04-06 18:02:31 -0400147};
148
149SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
150 list.push_back(elem);
151 return list;
152}
153
alan-bakerb6b09dc2018-11-08 16:59:28 -0500154SPIRVOperand *MkNum(uint32_t num) {
David Netoc6f3ab22018-04-06 18:02:31 -0400155 return new SPIRVOperand(LITERAL_INTEGER, num);
156}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500157SPIRVOperand *MkInteger(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400158 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
159}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500160SPIRVOperand *MkFloat(ArrayRef<uint32_t> num_vec) {
David Neto257c3892018-04-11 13:19:45 -0400161 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
162}
alan-bakerb6b09dc2018-11-08 16:59:28 -0500163SPIRVOperand *MkId(uint32_t id) { return new SPIRVOperand(NUMBERID, id); }
164SPIRVOperand *MkString(StringRef str) {
David Neto257c3892018-04-11 13:19:45 -0400165 return new SPIRVOperand(LITERAL_STRING, str);
166}
David Netoc6f3ab22018-04-06 18:02:31 -0400167
David Neto22f144c2017-06-12 14:26:21 -0400168struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400169 // Create an instruction with an opcode and no result ID, and with the given
170 // operands. This computes its own word count.
171 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
172 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
173 Operands(Ops.begin(), Ops.end()) {
174 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400175 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400176 }
177 }
178 // Create an instruction with an opcode and a no-zero result ID, and
179 // with the given operands. This computes its own word count.
180 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400181 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400182 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
183 Operands(Ops.begin(), Ops.end()) {
184 if (ResID == 0) {
185 llvm_unreachable("Result ID of 0 was provided");
186 }
187 for (auto *operand : Ops) {
188 WordCount += operand->GetNumWords();
189 }
190 }
David Neto22f144c2017-06-12 14:26:21 -0400191
David Netoee2660d2018-06-28 16:31:29 -0400192 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400193 uint16_t getOpcode() const { return Opcode; }
194 uint32_t getResultID() const { return ResultID; }
195 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
196
197private:
David Netoee2660d2018-06-28 16:31:29 -0400198 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400199 uint16_t Opcode;
200 uint32_t ResultID;
201 SmallVector<SPIRVOperand *, 4> Operands;
202};
203
204struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400205 typedef DenseMap<Type *, uint32_t> TypeMapType;
206 typedef UniqueVector<Type *> TypeList;
207 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400208 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400209 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
210 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400211 // A vector of tuples, each of which is:
212 // - the LLVM instruction that we will later generate SPIR-V code for
213 // - where the SPIR-V instruction should be inserted
214 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400215 typedef std::vector<
216 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
217 DeferredInstVecType;
218 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
219 GlobalConstFuncMapType;
220
David Neto44795152017-07-13 15:45:28 -0400221 explicit SPIRVProducerPass(
alan-bakerf5e5f692018-11-27 08:33:24 -0500222 raw_pwrite_stream &out,
223 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400224 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
David Neto44795152017-07-13 15:45:28 -0400225 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400226 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400227 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
alan-baker00e7a582019-06-07 12:54:21 -0400228 descriptorMapEntries(descriptor_map_entries),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
alan-baker5b86ed72019-02-15 08:26:50 -0500230 OpExtInstImportID(0), HasVariablePointersStorageBuffer(false),
231 HasVariablePointers(false), SamplerTy(nullptr), WorkgroupSizeValueID(0),
Kévin Petit89a525c2019-06-15 08:13:07 +0100232 WorkgroupSizeVarID(0), max_local_spec_id_(0) {}
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 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400286 bool hasVariablePointers() { return HasVariablePointers; };
David Neto22f144c2017-06-12 14:26:21 -0400287 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
alan-bakerb6b09dc2018-11-08 16:59:28 -0500288 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() {
289 return samplerMap;
290 }
David Neto22f144c2017-06-12 14:26:21 -0400291 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
292 return GlobalConstFuncTypeMap;
293 }
294 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
295 return GlobalConstArgumentSet;
296 }
alan-bakerb6b09dc2018-11-08 16:59:28 -0500297 TypeList &getTypesNeedingArrayStride() { return TypesNeedingArrayStride; }
David Neto22f144c2017-06-12 14:26:21 -0400298
David Netoc6f3ab22018-04-06 18:02:31 -0400299 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500300 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will
301 // *not* be converted to a storage buffer, replace each such global variable
302 // with one in the storage class expecgted by SPIR-V.
David Neto862b7d82018-06-14 18:48:37 -0400303 void FindGlobalConstVars(Module &M, const DataLayout &DL);
304 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
305 // ModuleOrderedResourceVars.
306 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400307 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400308 bool FindExtInst(Module &M);
309 void FindTypePerGlobalVar(GlobalVariable &GV);
310 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400311 void FindTypesForSamplerMap(Module &M);
312 void FindTypesForResourceVars(Module &M);
alan-bakerb6b09dc2018-11-08 16:59:28 -0500313 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating
314 // that |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400315 void FindType(Type *Ty);
316 void FindConstantPerGlobalVar(GlobalVariable &GV);
317 void FindConstantPerFunc(Function &F);
318 void FindConstant(Value *V);
319 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400320 // Generates instructions for SPIR-V types corresponding to the LLVM types
321 // saved in the |Types| member. A type follows its subtypes. IDs are
322 // allocated sequentially starting with the current value of nextID, and
323 // with a type following its subtypes. Also updates nextID to just beyond
324 // the last generated ID.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500325 void GenerateSPIRVTypes(LLVMContext &context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400326 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400327 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400328 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400329 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400330 // Generate descriptor map entries for resource variables associated with
331 // arguments to F.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500332 void GenerateDescriptorMapInfo(const DataLayout &DL, Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400333 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400334 // Generate OpVariables for %clspv.resource.var.* calls.
335 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400336 void GenerateFuncPrologue(Function &F);
337 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400338 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400339 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
340 spv::Op GetSPIRVCastOpcode(Instruction &I);
341 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
342 void GenerateInstruction(Instruction &I);
343 void GenerateFuncEpilogue();
344 void HandleDeferredInstruction();
alan-bakerb6b09dc2018-11-08 16:59:28 -0500345 void HandleDeferredDecorations(const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400346 bool is4xi8vec(Type *Ty) const;
347 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400348 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400349 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400350 // Returns the GLSL extended instruction enum that the given function
351 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400352 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400353 // Returns the GLSL extended instruction enum indirectly used by the given
354 // function. That is, to implement the given function, we use an extended
355 // instruction plus one more instruction. If none, then returns the 0 value,
356 // i.e. GLSLstd4580Bad.
357 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
358 // Returns the single GLSL extended instruction used directly or
359 // indirectly by the given function call.
360 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400361 void WriteOneWord(uint32_t Word);
362 void WriteResultID(SPIRVInstruction *Inst);
363 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
364 void WriteOperand(SPIRVOperand *Op);
365 void WriteSPIRVBinary();
366
Alan Baker9bf93fb2018-08-28 16:59:26 -0400367 // Returns true if |type| is compatible with OpConstantNull.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500368 bool IsTypeNullable(const Type *type) const;
Alan Baker9bf93fb2018-08-28 16:59:26 -0400369
Alan Bakerfcda9482018-10-02 17:09:59 -0400370 // Populate UBO remapped type maps.
371 void PopulateUBOTypeMaps(Module &module);
372
373 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
374 // uses the internal map, otherwise it falls back on the data layout.
375 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
376 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
377 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
378
alan-baker5b86ed72019-02-15 08:26:50 -0500379 // Returns the base pointer of |v|.
380 Value *GetBasePointer(Value *v);
381
382 // Sets |HasVariablePointersStorageBuffer| or |HasVariablePointers| base on
383 // |address_space|.
384 void setVariablePointersCapabilities(unsigned address_space);
385
386 // Returns true if |lhs| and |rhs| represent the same resource or workgroup
387 // variable.
388 bool sameResource(Value *lhs, Value *rhs) const;
389
390 // Returns true if |inst| is phi or select that selects from the same
391 // structure (or null).
392 bool selectFromSameObject(Instruction *inst);
393
alan-bakere9308012019-03-15 10:25:13 -0400394 // Returns true if |Arg| is called with a coherent resource.
395 bool CalledWithCoherentResource(Argument &Arg);
396
David Neto22f144c2017-06-12 14:26:21 -0400397private:
398 static char ID;
David Neto44795152017-07-13 15:45:28 -0400399 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400400 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400401
402 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
403 // convert to other formats on demand?
404
405 // When emitting a C initialization list, the WriteSPIRVBinary method
406 // will actually write its words to this vector via binaryTempOut.
407 SmallVector<char, 100> binaryTempUnderlyingVector;
408 raw_svector_ostream binaryTempOut;
409
410 // Binary output writes to this stream, which might be |out| or
411 // |binaryTempOut|. It's the latter when we really want to write a C
412 // initializer list.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400413 raw_pwrite_stream *binaryOut;
alan-bakerf5e5f692018-11-27 08:33:24 -0500414 std::vector<version0::DescriptorMapEntry> *descriptorMapEntries;
David Neto0676e6f2017-07-11 18:47:44 -0400415 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400416 uint64_t patchBoundOffset;
417 uint32_t nextID;
418
David Neto19a1bad2017-08-25 15:01:41 -0400419 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400420 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400421 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400422 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400423 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400424 TypeList Types;
425 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400426 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400427 ValueMapType ValueMap;
428 ValueMapType AllocatedValueMap;
429 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400430
David Neto22f144c2017-06-12 14:26:21 -0400431 EntryPointVecType EntryPointVec;
432 DeferredInstVecType DeferredInstVec;
433 ValueList EntryPointInterfacesVec;
434 uint32_t OpExtInstImportID;
435 std::vector<uint32_t> BuiltinDimensionVec;
alan-baker5b86ed72019-02-15 08:26:50 -0500436 bool HasVariablePointersStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -0400437 bool HasVariablePointers;
438 Type *SamplerTy;
alan-bakerb6b09dc2018-11-08 16:59:28 -0500439 DenseMap<unsigned, uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700440
441 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700442 // will map F's type to (G, index of the parameter), where in a first phase
443 // G is F's type. During FindTypePerFunc, G will be changed to F's type
444 // but replacing the pointer-to-constant parameter with
445 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700446 // TODO(dneto): This doesn't seem general enough? A function might have
447 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400448 GlobalConstFuncMapType GlobalConstFuncTypeMap;
449 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400450 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700451 // or array types, and which point into transparent memory (StorageBuffer
452 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400453 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700454 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400455
456 // This is truly ugly, but works around what look like driver bugs.
457 // For get_local_size, an earlier part of the flow has created a module-scope
458 // variable in Private address space to hold the value for the workgroup
459 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
460 // When this is present, save the IDs of the initializer value and variable
461 // in these two variables. We only ever do a vector load from it, and
462 // when we see one of those, substitute just the value of the intializer.
463 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700464 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400465 uint32_t WorkgroupSizeValueID;
466 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400467
David Neto862b7d82018-06-14 18:48:37 -0400468 // Bookkeeping for mapping kernel arguments to resource variables.
469 struct ResourceVarInfo {
470 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
alan-bakere9308012019-03-15 10:25:13 -0400471 Function *fn, clspv::ArgKind arg_kind_arg, int coherent_arg)
David Neto862b7d82018-06-14 18:48:37 -0400472 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
alan-bakere9308012019-03-15 10:25:13 -0400473 var_fn(fn), arg_kind(arg_kind_arg), coherent(coherent_arg),
David Neto862b7d82018-06-14 18:48:37 -0400474 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
475 const int index; // Index into ResourceVarInfoList
476 const unsigned descriptor_set;
477 const unsigned binding;
478 Function *const var_fn; // The @clspv.resource.var.* function.
479 const clspv::ArgKind arg_kind;
alan-bakere9308012019-03-15 10:25:13 -0400480 const int coherent;
David Neto862b7d82018-06-14 18:48:37 -0400481 const unsigned addr_space; // The LLVM address space
482 // The SPIR-V ID of the OpVariable. Not populated at construction time.
483 uint32_t var_id = 0;
484 };
485 // A list of resource var info. Each one correponds to a module-scope
486 // resource variable we will have to create. Resource var indices are
487 // indices into this vector.
488 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
489 // This is a vector of pointers of all the resource vars, but ordered by
490 // kernel function, and then by argument.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500491 UniqueVector<ResourceVarInfo *> ModuleOrderedResourceVars;
David Neto862b7d82018-06-14 18:48:37 -0400492 // Map a function to the ordered list of resource variables it uses, one for
493 // each argument. If an argument does not use a resource variable, it
494 // will have a null pointer entry.
495 using FunctionToResourceVarsMapType =
496 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
497 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
498
499 // What LLVM types map to SPIR-V types needing layout? These are the
500 // arrays and structures supporting storage buffers and uniform buffers.
501 TypeList TypesNeedingLayout;
502 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
503 UniqueVector<StructType *> StructTypesNeedingBlock;
504 // For a call that represents a load from an opaque type (samplers, images),
505 // map it to the variable id it should load from.
506 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700507
Alan Baker202c8c72018-08-13 13:47:44 -0400508 // One larger than the maximum used SpecId for pointer-to-local arguments.
509 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400510 // An ordered list of the kernel arguments of type pointer-to-local.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500511 using LocalArgList = SmallVector<Argument *, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400512 LocalArgList LocalArgs;
513 // Information about a pointer-to-local argument.
514 struct LocalArgInfo {
515 // The SPIR-V ID of the array variable.
516 uint32_t variable_id;
517 // The element type of the
alan-bakerb6b09dc2018-11-08 16:59:28 -0500518 Type *elem_type;
David Netoc6f3ab22018-04-06 18:02:31 -0400519 // The ID of the array type.
520 uint32_t array_size_id;
521 // The ID of the array type.
522 uint32_t array_type_id;
523 // The ID of the pointer to the array type.
524 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400525 // The specialization constant ID of the array size.
526 int spec_id;
527 };
Alan Baker202c8c72018-08-13 13:47:44 -0400528 // A mapping from Argument to its assigned SpecId.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500529 DenseMap<const Argument *, int> LocalArgSpecIds;
Alan Baker202c8c72018-08-13 13:47:44 -0400530 // A mapping from SpecId to its LocalArgInfo.
531 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400532 // A mapping from a remapped type to its real offsets.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500533 DenseMap<Type *, std::vector<uint32_t>> RemappedUBOTypeOffsets;
Alan Bakerfcda9482018-10-02 17:09:59 -0400534 // A mapping from a remapped type to its real sizes.
alan-bakerb6b09dc2018-11-08 16:59:28 -0500535 DenseMap<Type *, std::tuple<uint64_t, uint64_t, uint64_t>>
536 RemappedUBOTypeSizes;
David Neto22f144c2017-06-12 14:26:21 -0400537};
538
539char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400540
alan-bakerb6b09dc2018-11-08 16:59:28 -0500541} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400542
543namespace clspv {
alan-bakerf5e5f692018-11-27 08:33:24 -0500544ModulePass *createSPIRVProducerPass(
545 raw_pwrite_stream &out,
546 std::vector<version0::DescriptorMapEntry> *descriptor_map_entries,
alan-baker00e7a582019-06-07 12:54:21 -0400547 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
alan-bakerf5e5f692018-11-27 08:33:24 -0500548 bool outputCInitList) {
549 return new SPIRVProducerPass(out, descriptor_map_entries, samplerMap,
alan-baker00e7a582019-06-07 12:54:21 -0400550 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400551}
David Netoc2c368d2017-06-30 16:50:17 -0400552} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400553
554bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400555 binaryOut = outputCInitList ? &binaryTempOut : &out;
556
Alan Bakerfcda9482018-10-02 17:09:59 -0400557 PopulateUBOTypeMaps(module);
558
David Neto22f144c2017-06-12 14:26:21 -0400559 // SPIR-V always begins with its header information
560 outputHeader();
561
David Netoc6f3ab22018-04-06 18:02:31 -0400562 const DataLayout &DL = module.getDataLayout();
563
David Neto22f144c2017-06-12 14:26:21 -0400564 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400565 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400566
David Neto22f144c2017-06-12 14:26:21 -0400567 // Collect information on global variables too.
568 for (GlobalVariable &GV : module.globals()) {
569 // If the GV is one of our special __spirv_* variables, remove the
570 // initializer as it was only placed there to force LLVM to not throw the
571 // value away.
572 if (GV.getName().startswith("__spirv_")) {
573 GV.setInitializer(nullptr);
574 }
575
576 // Collect types' information from global variable.
577 FindTypePerGlobalVar(GV);
578
579 // Collect constant information from global variable.
580 FindConstantPerGlobalVar(GV);
581
582 // If the variable is an input, entry points need to know about it.
583 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400584 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400585 }
586 }
587
588 // If there are extended instructions, generate OpExtInstImport.
589 if (FindExtInst(module)) {
590 GenerateExtInstImport();
591 }
592
593 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400594 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400595
596 // Generate SPIRV constants.
597 GenerateSPIRVConstants();
598
599 // If we have a sampler map, we might have literal samplers to generate.
600 if (0 < getSamplerMap().size()) {
601 GenerateSamplers(module);
602 }
603
604 // Generate SPIRV variables.
605 for (GlobalVariable &GV : module.globals()) {
606 GenerateGlobalVar(GV);
607 }
David Neto862b7d82018-06-14 18:48:37 -0400608 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400609 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400610
611 // Generate SPIRV instructions for each function.
612 for (Function &F : module) {
613 if (F.isDeclaration()) {
614 continue;
615 }
616
David Neto862b7d82018-06-14 18:48:37 -0400617 GenerateDescriptorMapInfo(DL, F);
618
David Neto22f144c2017-06-12 14:26:21 -0400619 // Generate Function Prologue.
620 GenerateFuncPrologue(F);
621
622 // Generate SPIRV instructions for function body.
623 GenerateFuncBody(F);
624
625 // Generate Function Epilogue.
626 GenerateFuncEpilogue();
627 }
628
629 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400630 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400631
632 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400633 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400634
alan-baker00e7a582019-06-07 12:54:21 -0400635 WriteSPIRVBinary();
David Neto22f144c2017-06-12 14:26:21 -0400636
637 // We need to patch the SPIR-V header to set bound correctly.
638 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400639
640 if (outputCInitList) {
641 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400642 std::ostringstream os;
643
David Neto57fb0b92017-08-04 15:35:09 -0400644 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400645 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400646 os << ",\n";
647 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400648 first = false;
649 };
650
651 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400652 const std::string str(binaryTempOut.str());
653 for (unsigned i = 0; i < str.size(); i += 4) {
654 const uint32_t a = static_cast<unsigned char>(str[i]);
655 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
656 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
657 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
658 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400659 }
660 os << "}\n";
661 out << os.str();
662 }
663
David Neto22f144c2017-06-12 14:26:21 -0400664 return false;
665}
666
667void SPIRVProducerPass::outputHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400668 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
669 sizeof(spv::MagicNumber));
670 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
671 sizeof(spv::Version));
David Neto22f144c2017-06-12 14:26:21 -0400672
alan-baker0c18ab02019-06-12 10:23:21 -0400673 // use Google's vendor ID
674 const uint32_t vendor = 21 << 16;
alan-baker00e7a582019-06-07 12:54:21 -0400675 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400676
alan-baker00e7a582019-06-07 12:54:21 -0400677 // we record where we need to come back to and patch in the bound value
678 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400679
alan-baker00e7a582019-06-07 12:54:21 -0400680 // output a bad bound for now
681 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400682
alan-baker00e7a582019-06-07 12:54:21 -0400683 // output the schema (reserved for use and must be 0)
684 const uint32_t schema = 0;
685 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400686}
687
688void SPIRVProducerPass::patchHeader() {
alan-baker00e7a582019-06-07 12:54:21 -0400689 // for a binary we just write the value of nextID over bound
690 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
691 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400692}
693
David Netoc6f3ab22018-04-06 18:02:31 -0400694void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400695 // This function generates LLVM IR for function such as global variable for
696 // argument, constant and pointer type for argument access. These information
697 // is artificial one because we need Vulkan SPIR-V output. This function is
698 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400699 LLVMContext &Context = M.getContext();
700
David Neto862b7d82018-06-14 18:48:37 -0400701 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400702
David Neto862b7d82018-06-14 18:48:37 -0400703 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400704
705 bool HasWorkGroupBuiltin = false;
706 for (GlobalVariable &GV : M.globals()) {
707 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
708 if (spv::BuiltInWorkgroupSize == BuiltinType) {
709 HasWorkGroupBuiltin = true;
710 }
711 }
712
David Neto862b7d82018-06-14 18:48:37 -0400713 FindTypesForSamplerMap(M);
714 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400715 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400716
David Neto862b7d82018-06-14 18:48:37 -0400717 // These function calls need a <2 x i32> as an intermediate result but not
718 // the final result.
719 std::unordered_set<std::string> NeedsIVec2{
720 "_Z15get_image_width14ocl_image2d_ro",
721 "_Z15get_image_width14ocl_image2d_wo",
722 "_Z16get_image_height14ocl_image2d_ro",
723 "_Z16get_image_height14ocl_image2d_wo",
724 };
725
David Neto22f144c2017-06-12 14:26:21 -0400726 for (Function &F : M) {
Kévin Petitabef4522019-03-27 13:08:01 +0000727 if (F.isDeclaration()) {
David Neto22f144c2017-06-12 14:26:21 -0400728 continue;
729 }
730
731 for (BasicBlock &BB : F) {
732 for (Instruction &I : BB) {
733 if (I.getOpcode() == Instruction::ZExt ||
734 I.getOpcode() == Instruction::SExt ||
735 I.getOpcode() == Instruction::UIToFP) {
736 // If there is zext with i1 type, it will be changed to OpSelect. The
737 // OpSelect needs constant 0 and 1 so the constants are added here.
738
739 auto OpTy = I.getOperand(0)->getType();
740
Kévin Petit24272b62018-10-18 19:16:12 +0000741 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400742 if (I.getOpcode() == Instruction::ZExt) {
David Neto22f144c2017-06-12 14:26:21 -0400743 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000744 FindConstant(ConstantInt::get(I.getType(), 1));
David Neto22f144c2017-06-12 14:26:21 -0400745 } else if (I.getOpcode() == Instruction::SExt) {
David Neto22f144c2017-06-12 14:26:21 -0400746 FindConstant(Constant::getNullValue(I.getType()));
Kévin Petit7bfb8992019-02-26 13:45:08 +0000747 FindConstant(ConstantInt::getSigned(I.getType(), -1));
David Neto22f144c2017-06-12 14:26:21 -0400748 } else {
749 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
750 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
751 }
752 }
753 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400754 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400755
756 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400757 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400758 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400759 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400760 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
761 TypeMapType &OpImageTypeMap = getImageTypeMap();
762 Type *ImageTy =
763 Call->getArgOperand(0)->getType()->getPointerElementType();
764 OpImageTypeMap[ImageTy] = 0;
765
766 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
767 }
David Neto5c22a252018-03-15 16:07:41 -0400768
David Neto862b7d82018-06-14 18:48:37 -0400769 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400770 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
771 }
David Neto22f144c2017-06-12 14:26:21 -0400772 }
773 }
774 }
775
Kévin Petitabef4522019-03-27 13:08:01 +0000776 // More things to do on kernel functions
777 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
778 if (const MDNode *MD =
779 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
780 // We generate constants if the WorkgroupSize builtin is being used.
781 if (HasWorkGroupBuiltin) {
782 // Collect constant information for work group size.
783 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
784 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
785 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
David Neto22f144c2017-06-12 14:26:21 -0400786 }
787 }
788 }
789
790 if (M.getTypeByName("opencl.image2d_ro_t") ||
791 M.getTypeByName("opencl.image2d_wo_t") ||
792 M.getTypeByName("opencl.image3d_ro_t") ||
793 M.getTypeByName("opencl.image3d_wo_t")) {
794 // Assume Image type's sampled type is float type.
795 FindType(Type::getFloatTy(Context));
796 }
797
798 // Collect types' information from function.
799 FindTypePerFunc(F);
800
801 // Collect constant information from function.
802 FindConstantPerFunc(F);
803 }
804}
805
David Neto862b7d82018-06-14 18:48:37 -0400806void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
alan-baker56f7aff2019-05-22 08:06:42 -0400807 clspv::NormalizeGlobalVariables(M);
808
David Neto862b7d82018-06-14 18:48:37 -0400809 SmallVector<GlobalVariable *, 8> GVList;
810 SmallVector<GlobalVariable *, 8> DeadGVList;
811 for (GlobalVariable &GV : M.globals()) {
812 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
813 if (GV.use_empty()) {
814 DeadGVList.push_back(&GV);
815 } else {
816 GVList.push_back(&GV);
817 }
818 }
819 }
820
821 // Remove dead global __constant variables.
822 for (auto GV : DeadGVList) {
823 GV->eraseFromParent();
824 }
825 DeadGVList.clear();
826
827 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
828 // For now, we only support a single storage buffer.
829 if (GVList.size() > 0) {
830 assert(GVList.size() == 1);
831 const auto *GV = GVList[0];
832 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400833 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400834 const size_t kConstantMaxSize = 65536;
835 if (constants_byte_size > kConstantMaxSize) {
836 outs() << "Max __constant capacity of " << kConstantMaxSize
837 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
838 llvm_unreachable("Max __constant capacity exceeded");
839 }
840 }
841 } else {
842 // Change global constant variable's address space to ModuleScopePrivate.
843 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
844 for (auto GV : GVList) {
845 // Create new gv with ModuleScopePrivate address space.
846 Type *NewGVTy = GV->getType()->getPointerElementType();
847 GlobalVariable *NewGV = new GlobalVariable(
848 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
849 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
850 NewGV->takeName(GV);
851
852 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
853 SmallVector<User *, 8> CandidateUsers;
854
855 auto record_called_function_type_as_user =
856 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
857 // Find argument index.
858 unsigned index = 0;
859 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
860 if (gv == call->getOperand(i)) {
861 // TODO(dneto): Should we break here?
862 index = i;
863 }
864 }
865
866 // Record function type with global constant.
867 GlobalConstFuncTyMap[call->getFunctionType()] =
868 std::make_pair(call->getFunctionType(), index);
869 };
870
871 for (User *GVU : GVUsers) {
872 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
873 record_called_function_type_as_user(GV, Call);
874 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
875 // Check GEP users.
876 for (User *GEPU : GEP->users()) {
877 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
878 record_called_function_type_as_user(GEP, GEPCall);
879 }
880 }
881 }
882
883 CandidateUsers.push_back(GVU);
884 }
885
886 for (User *U : CandidateUsers) {
887 // Update users of gv with new gv.
alan-bakered80f572019-02-11 17:28:26 -0500888 if (!isa<Constant>(U)) {
889 // #254: Can't change operands of a constant, but this shouldn't be
890 // something that sticks around in the module.
891 U->replaceUsesOfWith(GV, NewGV);
892 }
David Neto862b7d82018-06-14 18:48:37 -0400893 }
894
895 // Delete original gv.
896 GV->eraseFromParent();
897 }
898 }
899}
900
Radek Szymanskibe4b0c42018-10-04 22:20:53 +0100901void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &) {
David Neto862b7d82018-06-14 18:48:37 -0400902 ResourceVarInfoList.clear();
903 FunctionToResourceVarsMap.clear();
904 ModuleOrderedResourceVars.reset();
905 // Normally, there is one resource variable per clspv.resource.var.*
906 // function, since that is unique'd by arg type and index. By design,
907 // we can share these resource variables across kernels because all
908 // kernels use the same descriptor set.
909 //
910 // But if the user requested distinct descriptor sets per kernel, then
911 // the descriptor allocator has made different (set,binding) pairs for
912 // the same (type,arg_index) pair. Since we can decorate a resource
913 // variable with only exactly one DescriptorSet and Binding, we are
914 // forced in this case to make distinct resource variables whenever
915 // the same clspv.reource.var.X function is seen with disintct
916 // (set,binding) values.
917 const bool always_distinct_sets =
918 clspv::Option::DistinctKernelDescriptorSets();
919 for (Function &F : M) {
920 // Rely on the fact the resource var functions have a stable ordering
921 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -0400922 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -0400923 // Find all calls to this function with distinct set and binding pairs.
924 // Save them in ResourceVarInfoList.
925
926 // Determine uniqueness of the (set,binding) pairs only withing this
927 // one resource-var builtin function.
928 using SetAndBinding = std::pair<unsigned, unsigned>;
929 // Maps set and binding to the resource var info.
930 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
931 bool first_use = true;
932 for (auto &U : F.uses()) {
933 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
934 const auto set = unsigned(
935 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
936 const auto binding = unsigned(
937 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
938 const auto arg_kind = clspv::ArgKind(
939 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
940 const auto arg_index = unsigned(
941 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
alan-bakere9308012019-03-15 10:25:13 -0400942 const auto coherent = unsigned(
943 dyn_cast<ConstantInt>(call->getArgOperand(5))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -0400944
945 // Find or make the resource var info for this combination.
946 ResourceVarInfo *rv = nullptr;
947 if (always_distinct_sets) {
948 // Make a new resource var any time we see a different
949 // (set,binding) pair.
950 SetAndBinding key{set, binding};
951 auto where = set_and_binding_map.find(key);
952 if (where == set_and_binding_map.end()) {
953 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -0400954 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -0400955 ResourceVarInfoList.emplace_back(rv);
956 set_and_binding_map[key] = rv;
957 } else {
958 rv = where->second;
959 }
960 } else {
961 // The default is to make exactly one resource for each
962 // clspv.resource.var.* function.
963 if (first_use) {
964 first_use = false;
965 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
alan-bakere9308012019-03-15 10:25:13 -0400966 binding, &F, arg_kind, coherent);
David Neto862b7d82018-06-14 18:48:37 -0400967 ResourceVarInfoList.emplace_back(rv);
968 } else {
969 rv = ResourceVarInfoList.back().get();
970 }
971 }
972
973 // Now populate FunctionToResourceVarsMap.
974 auto &mapping =
975 FunctionToResourceVarsMap[call->getParent()->getParent()];
976 while (mapping.size() <= arg_index) {
977 mapping.push_back(nullptr);
978 }
979 mapping[arg_index] = rv;
980 }
981 }
982 }
983 }
984
985 // Populate ModuleOrderedResourceVars.
986 for (Function &F : M) {
987 auto where = FunctionToResourceVarsMap.find(&F);
988 if (where != FunctionToResourceVarsMap.end()) {
989 for (auto &rv : where->second) {
990 if (rv != nullptr) {
991 ModuleOrderedResourceVars.insert(rv);
992 }
993 }
994 }
995 }
996 if (ShowResourceVars) {
997 for (auto *info : ModuleOrderedResourceVars) {
998 outs() << "MORV index " << info->index << " (" << info->descriptor_set
999 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1000 << "\n";
1001 }
1002 }
1003}
1004
David Neto22f144c2017-06-12 14:26:21 -04001005bool SPIRVProducerPass::FindExtInst(Module &M) {
1006 LLVMContext &Context = M.getContext();
1007 bool HasExtInst = false;
1008
1009 for (Function &F : M) {
1010 for (BasicBlock &BB : F) {
1011 for (Instruction &I : BB) {
1012 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1013 Function *Callee = Call->getCalledFunction();
1014 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001015 auto callee_name = Callee->getName();
1016 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1017 const glsl::ExtInst IndirectEInst =
1018 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001019
David Neto3fbb4072017-10-16 11:28:14 -04001020 HasExtInst |=
1021 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1022
1023 if (IndirectEInst) {
1024 // Register extra constants if needed.
1025
1026 // Registers a type and constant for computing the result of the
1027 // given instruction. If the result of the instruction is a vector,
1028 // then make a splat vector constant with the same number of
1029 // elements.
1030 auto register_constant = [this, &I](Constant *constant) {
1031 FindType(constant->getType());
1032 FindConstant(constant);
1033 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1034 // Register the splat vector of the value with the same
1035 // width as the result of the instruction.
1036 auto *vec_constant = ConstantVector::getSplat(
1037 static_cast<unsigned>(vectorTy->getNumElements()),
1038 constant);
1039 FindConstant(vec_constant);
1040 FindType(vec_constant->getType());
1041 }
1042 };
1043 switch (IndirectEInst) {
1044 case glsl::ExtInstFindUMsb:
1045 // clz needs OpExtInst and OpISub with constant 31, or splat
1046 // vector of 31. Add it to the constant list here.
1047 register_constant(
1048 ConstantInt::get(Type::getInt32Ty(Context), 31));
1049 break;
1050 case glsl::ExtInstAcos:
1051 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001052 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001053 case glsl::ExtInstAtan2:
1054 // We need 1/pi for acospi, asinpi, atan2pi.
1055 register_constant(
1056 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1057 break;
1058 default:
1059 assert(false && "internally inconsistent");
1060 }
David Neto22f144c2017-06-12 14:26:21 -04001061 }
1062 }
1063 }
1064 }
1065 }
1066
1067 return HasExtInst;
1068}
1069
1070void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1071 // Investigate global variable's type.
1072 FindType(GV.getType());
1073}
1074
1075void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1076 // Investigate function's type.
1077 FunctionType *FTy = F.getFunctionType();
1078
1079 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1080 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001081 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001082 if (GlobalConstFuncTyMap.count(FTy)) {
1083 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1084 SmallVector<Type *, 4> NewFuncParamTys;
1085 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1086 Type *ParamTy = FTy->getParamType(i);
1087 if (i == GVCstArgIdx) {
1088 Type *EleTy = ParamTy->getPointerElementType();
1089 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1090 }
1091
1092 NewFuncParamTys.push_back(ParamTy);
1093 }
1094
1095 FunctionType *NewFTy =
1096 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1097 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1098 FTy = NewFTy;
1099 }
1100
1101 FindType(FTy);
1102 } else {
1103 // As kernel functions do not have parameters, create new function type and
1104 // add it to type map.
1105 SmallVector<Type *, 4> NewFuncParamTys;
1106 FunctionType *NewFTy =
1107 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1108 FindType(NewFTy);
1109 }
1110
1111 // Investigate instructions' type in function body.
1112 for (BasicBlock &BB : F) {
1113 for (Instruction &I : BB) {
1114 if (isa<ShuffleVectorInst>(I)) {
1115 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1116 // Ignore type for mask of shuffle vector instruction.
1117 if (i == 2) {
1118 continue;
1119 }
1120
1121 Value *Op = I.getOperand(i);
1122 if (!isa<MetadataAsValue>(Op)) {
1123 FindType(Op->getType());
1124 }
1125 }
1126
1127 FindType(I.getType());
1128 continue;
1129 }
1130
David Neto862b7d82018-06-14 18:48:37 -04001131 CallInst *Call = dyn_cast<CallInst>(&I);
1132
1133 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001134 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001135 // This is a fake call representing access to a resource variable.
1136 // We handle that elsewhere.
1137 continue;
1138 }
1139
Alan Baker202c8c72018-08-13 13:47:44 -04001140 if (Call && Call->getCalledFunction()->getName().startswith(
1141 clspv::WorkgroupAccessorFunction())) {
1142 // This is a fake call representing access to a workgroup variable.
1143 // We handle that elsewhere.
1144 continue;
1145 }
1146
David Neto22f144c2017-06-12 14:26:21 -04001147 // Work through the operands of the instruction.
1148 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1149 Value *const Op = I.getOperand(i);
1150 // If any of the operands is a constant, find the type!
1151 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1152 FindType(Op->getType());
1153 }
1154 }
1155
1156 for (Use &Op : I.operands()) {
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001157 if (isa<CallInst>(&I)) {
David Neto22f144c2017-06-12 14:26:21 -04001158 // Avoid to check call instruction's type.
1159 break;
1160 }
Alan Baker202c8c72018-08-13 13:47:44 -04001161 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1162 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1163 clspv::WorkgroupAccessorFunction())) {
1164 // This is a fake call representing access to a workgroup variable.
1165 // We handle that elsewhere.
1166 continue;
1167 }
1168 }
David Neto22f144c2017-06-12 14:26:21 -04001169 if (!isa<MetadataAsValue>(&Op)) {
1170 FindType(Op->getType());
1171 continue;
1172 }
1173 }
1174
David Neto22f144c2017-06-12 14:26:21 -04001175 // We don't want to track the type of this call as we are going to replace
1176 // it.
Kévin Petitdf71de32019-04-09 14:09:50 +01001177 if (Call && (clspv::LiteralSamplerFunction() ==
David Neto22f144c2017-06-12 14:26:21 -04001178 Call->getCalledFunction()->getName())) {
1179 continue;
1180 }
1181
1182 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1183 // If gep's base operand has ModuleScopePrivate address space, make gep
1184 // return ModuleScopePrivate address space.
1185 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1186 // Add pointer type with private address space for global constant to
1187 // type list.
1188 Type *EleTy = I.getType()->getPointerElementType();
1189 Type *NewPTy =
1190 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1191
1192 FindType(NewPTy);
1193 continue;
1194 }
1195 }
1196
1197 FindType(I.getType());
1198 }
1199 }
1200}
1201
David Neto862b7d82018-06-14 18:48:37 -04001202void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1203 // If we are using a sampler map, find the type of the sampler.
Kévin Petitdf71de32019-04-09 14:09:50 +01001204 if (M.getFunction(clspv::LiteralSamplerFunction()) ||
David Neto862b7d82018-06-14 18:48:37 -04001205 0 < getSamplerMap().size()) {
1206 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1207 if (!SamplerStructTy) {
1208 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1209 }
1210
1211 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1212
1213 FindType(SamplerTy);
1214 }
1215}
1216
1217void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1218 // Record types so they are generated.
1219 TypesNeedingLayout.reset();
1220 StructTypesNeedingBlock.reset();
1221
1222 // To match older clspv codegen, generate the float type first if required
1223 // for images.
1224 for (const auto *info : ModuleOrderedResourceVars) {
1225 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1226 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1227 // We need "float" for the sampled component type.
1228 FindType(Type::getFloatTy(M.getContext()));
1229 // We only need to find it once.
1230 break;
1231 }
1232 }
1233
1234 for (const auto *info : ModuleOrderedResourceVars) {
1235 Type *type = info->var_fn->getReturnType();
1236
1237 switch (info->arg_kind) {
1238 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001239 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001240 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1241 StructTypesNeedingBlock.insert(sty);
1242 } else {
1243 errs() << *type << "\n";
1244 llvm_unreachable("Buffer arguments must map to structures!");
1245 }
1246 break;
1247 case clspv::ArgKind::Pod:
1248 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1249 StructTypesNeedingBlock.insert(sty);
1250 } else {
1251 errs() << *type << "\n";
1252 llvm_unreachable("POD arguments must map to structures!");
1253 }
1254 break;
1255 case clspv::ArgKind::ReadOnlyImage:
1256 case clspv::ArgKind::WriteOnlyImage:
1257 case clspv::ArgKind::Sampler:
1258 // Sampler and image types map to the pointee type but
1259 // in the uniform constant address space.
1260 type = PointerType::get(type->getPointerElementType(),
1261 clspv::AddressSpace::UniformConstant);
1262 break;
1263 default:
1264 break;
1265 }
1266
1267 // The converted type is the type of the OpVariable we will generate.
1268 // If the pointee type is an array of size zero, FindType will convert it
1269 // to a runtime array.
1270 FindType(type);
1271 }
1272
1273 // Traverse the arrays and structures underneath each Block, and
1274 // mark them as needing layout.
1275 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1276 StructTypesNeedingBlock.end());
1277 while (!work_list.empty()) {
1278 Type *type = work_list.back();
1279 work_list.pop_back();
1280 TypesNeedingLayout.insert(type);
1281 switch (type->getTypeID()) {
1282 case Type::ArrayTyID:
1283 work_list.push_back(type->getArrayElementType());
1284 if (!Hack_generate_runtime_array_stride_early) {
1285 // Remember this array type for deferred decoration.
1286 TypesNeedingArrayStride.insert(type);
1287 }
1288 break;
1289 case Type::StructTyID:
1290 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1291 work_list.push_back(elem_ty);
1292 }
1293 default:
1294 // This type and its contained types don't get layout.
1295 break;
1296 }
1297 }
1298}
1299
Alan Baker202c8c72018-08-13 13:47:44 -04001300void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1301 // The SpecId assignment for pointer-to-local arguments is recorded in
1302 // module-level metadata. Translate that information into local argument
1303 // information.
1304 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001305 if (!nmd)
1306 return;
Alan Baker202c8c72018-08-13 13:47:44 -04001307 for (auto operand : nmd->operands()) {
1308 MDTuple *tuple = cast<MDTuple>(operand);
1309 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1310 Function *func = cast<Function>(fn_md->getValue());
alan-bakerb6b09dc2018-11-08 16:59:28 -05001311 ConstantAsMetadata *arg_index_md =
1312 cast<ConstantAsMetadata>(tuple->getOperand(1));
1313 int arg_index = static_cast<int>(
1314 cast<ConstantInt>(arg_index_md->getValue())->getSExtValue());
1315 Argument *arg = &*(func->arg_begin() + arg_index);
Alan Baker202c8c72018-08-13 13:47:44 -04001316
1317 ConstantAsMetadata *spec_id_md =
1318 cast<ConstantAsMetadata>(tuple->getOperand(2));
alan-bakerb6b09dc2018-11-08 16:59:28 -05001319 int spec_id = static_cast<int>(
1320 cast<ConstantInt>(spec_id_md->getValue())->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04001321
1322 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1323 LocalArgSpecIds[arg] = spec_id;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001324 if (LocalSpecIdInfoMap.count(spec_id))
1325 continue;
Alan Baker202c8c72018-08-13 13:47:44 -04001326
1327 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1328 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1329 nextID + 1, nextID + 2,
1330 nextID + 3, spec_id};
1331 LocalSpecIdInfoMap[spec_id] = info;
1332 nextID += 4;
1333
1334 // Ensure the types necessary for this argument get generated.
1335 Type *IdxTy = Type::getInt32Ty(M.getContext());
1336 FindConstant(ConstantInt::get(IdxTy, 0));
1337 FindType(IdxTy);
1338 FindType(arg->getType());
1339 }
1340}
1341
David Neto22f144c2017-06-12 14:26:21 -04001342void SPIRVProducerPass::FindType(Type *Ty) {
1343 TypeList &TyList = getTypeList();
1344
1345 if (0 != TyList.idFor(Ty)) {
1346 return;
1347 }
1348
1349 if (Ty->isPointerTy()) {
1350 auto AddrSpace = Ty->getPointerAddressSpace();
1351 if ((AddressSpace::Constant == AddrSpace) ||
1352 (AddressSpace::Global == AddrSpace)) {
1353 auto PointeeTy = Ty->getPointerElementType();
1354
1355 if (PointeeTy->isStructTy() &&
1356 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1357 FindType(PointeeTy);
1358 auto ActualPointerTy =
1359 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1360 FindType(ActualPointerTy);
1361 return;
1362 }
1363 }
1364 }
1365
David Neto862b7d82018-06-14 18:48:37 -04001366 // By convention, LLVM array type with 0 elements will map to
1367 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1368 // has a constant number of elements. We need to support type of the
1369 // constant.
1370 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1371 if (arrayTy->getNumElements() > 0) {
1372 LLVMContext &Context = Ty->getContext();
1373 FindType(Type::getInt32Ty(Context));
1374 }
David Neto22f144c2017-06-12 14:26:21 -04001375 }
1376
1377 for (Type *SubTy : Ty->subtypes()) {
1378 FindType(SubTy);
1379 }
1380
1381 TyList.insert(Ty);
1382}
1383
1384void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1385 // If the global variable has a (non undef) initializer.
1386 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001387 // Generate the constant if it's not the initializer to a module scope
1388 // constant that we will expect in a storage buffer.
1389 const bool module_scope_constant_external_init =
1390 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1391 clspv::Option::ModuleConstantsInStorageBuffer();
1392 if (!module_scope_constant_external_init) {
1393 FindConstant(GV.getInitializer());
1394 }
David Neto22f144c2017-06-12 14:26:21 -04001395 }
1396}
1397
1398void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1399 // Investigate constants in function body.
1400 for (BasicBlock &BB : F) {
1401 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001402 if (auto *call = dyn_cast<CallInst>(&I)) {
1403 auto name = call->getCalledFunction()->getName();
Kévin Petitdf71de32019-04-09 14:09:50 +01001404 if (name == clspv::LiteralSamplerFunction()) {
David Neto862b7d82018-06-14 18:48:37 -04001405 // We've handled these constants elsewhere, so skip it.
1406 continue;
1407 }
Alan Baker202c8c72018-08-13 13:47:44 -04001408 if (name.startswith(clspv::ResourceAccessorFunction())) {
1409 continue;
1410 }
1411 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001412 continue;
1413 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001414 if (name.startswith(clspv::SPIRVOpIntrinsicFunction())) {
1415 // Skip the first operand that has the SPIR-V Opcode
1416 for (unsigned i = 1; i < I.getNumOperands(); i++) {
1417 if (isa<Constant>(I.getOperand(i)) &&
1418 !isa<GlobalValue>(I.getOperand(i))) {
1419 FindConstant(I.getOperand(i));
1420 }
1421 }
1422 continue;
1423 }
David Neto22f144c2017-06-12 14:26:21 -04001424 }
1425
1426 if (isa<AllocaInst>(I)) {
1427 // Alloca instruction has constant for the number of element. Ignore it.
1428 continue;
1429 } else if (isa<ShuffleVectorInst>(I)) {
1430 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1431 // Ignore constant for mask of shuffle vector instruction.
1432 if (i == 2) {
1433 continue;
1434 }
1435
1436 if (isa<Constant>(I.getOperand(i)) &&
1437 !isa<GlobalValue>(I.getOperand(i))) {
1438 FindConstant(I.getOperand(i));
1439 }
1440 }
1441
1442 continue;
1443 } else if (isa<InsertElementInst>(I)) {
1444 // Handle InsertElement with <4 x i8> specially.
1445 Type *CompositeTy = I.getOperand(0)->getType();
1446 if (is4xi8vec(CompositeTy)) {
1447 LLVMContext &Context = CompositeTy->getContext();
1448 if (isa<Constant>(I.getOperand(0))) {
1449 FindConstant(I.getOperand(0));
1450 }
1451
1452 if (isa<Constant>(I.getOperand(1))) {
1453 FindConstant(I.getOperand(1));
1454 }
1455
1456 // Add mask constant 0xFF.
1457 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1458 FindConstant(CstFF);
1459
1460 // Add shift amount constant.
1461 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1462 uint64_t Idx = CI->getZExtValue();
1463 Constant *CstShiftAmount =
1464 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1465 FindConstant(CstShiftAmount);
1466 }
1467
1468 continue;
1469 }
1470
1471 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1472 // Ignore constant for index of InsertElement instruction.
1473 if (i == 2) {
1474 continue;
1475 }
1476
1477 if (isa<Constant>(I.getOperand(i)) &&
1478 !isa<GlobalValue>(I.getOperand(i))) {
1479 FindConstant(I.getOperand(i));
1480 }
1481 }
1482
1483 continue;
1484 } else if (isa<ExtractElementInst>(I)) {
1485 // Handle ExtractElement with <4 x i8> specially.
1486 Type *CompositeTy = I.getOperand(0)->getType();
1487 if (is4xi8vec(CompositeTy)) {
1488 LLVMContext &Context = CompositeTy->getContext();
1489 if (isa<Constant>(I.getOperand(0))) {
1490 FindConstant(I.getOperand(0));
1491 }
1492
1493 // Add mask constant 0xFF.
1494 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1495 FindConstant(CstFF);
1496
1497 // Add shift amount constant.
1498 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1499 uint64_t Idx = CI->getZExtValue();
1500 Constant *CstShiftAmount =
1501 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1502 FindConstant(CstShiftAmount);
1503 } else {
1504 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1505 FindConstant(Cst8);
1506 }
1507
1508 continue;
1509 }
1510
1511 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1512 // Ignore constant for index of ExtractElement instruction.
1513 if (i == 1) {
1514 continue;
1515 }
1516
1517 if (isa<Constant>(I.getOperand(i)) &&
1518 !isa<GlobalValue>(I.getOperand(i))) {
1519 FindConstant(I.getOperand(i));
1520 }
1521 }
1522
1523 continue;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001524 } else if ((Instruction::Xor == I.getOpcode()) &&
1525 I.getType()->isIntegerTy(1)) {
1526 // We special case for Xor where the type is i1 and one of the arguments
1527 // is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we
1528 // don't need the constant
David Neto22f144c2017-06-12 14:26:21 -04001529 bool foundConstantTrue = false;
1530 for (Use &Op : I.operands()) {
1531 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1532 auto CI = cast<ConstantInt>(Op);
1533
1534 if (CI->isZero() || foundConstantTrue) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05001535 // If we already found the true constant, we might (probably only
1536 // on -O0) have an OpLogicalNot which is taking a constant
1537 // argument, so discover it anyway.
David Neto22f144c2017-06-12 14:26:21 -04001538 FindConstant(Op);
1539 } else {
1540 foundConstantTrue = true;
1541 }
1542 }
1543 }
1544
1545 continue;
David Netod2de94a2017-08-28 17:27:47 -04001546 } else if (isa<TruncInst>(I)) {
alan-bakerb39c8262019-03-08 14:03:37 -05001547 // Special case if i8 is not generally handled.
1548 if (!clspv::Option::Int8Support()) {
1549 // For truncation to i8 we mask against 255.
1550 Type *ToTy = I.getType();
1551 if (8u == ToTy->getPrimitiveSizeInBits()) {
1552 LLVMContext &Context = ToTy->getContext();
1553 Constant *Cst255 =
1554 ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1555 FindConstant(Cst255);
1556 }
David Netod2de94a2017-08-28 17:27:47 -04001557 }
Neil Henning39672102017-09-29 14:33:13 +01001558 } else if (isa<AtomicRMWInst>(I)) {
1559 LLVMContext &Context = I.getContext();
1560
1561 FindConstant(
1562 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1563 FindConstant(ConstantInt::get(
1564 Type::getInt32Ty(Context),
1565 spv::MemorySemanticsUniformMemoryMask |
1566 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001567 }
1568
1569 for (Use &Op : I.operands()) {
1570 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1571 FindConstant(Op);
1572 }
1573 }
1574 }
1575 }
1576}
1577
1578void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001579 ValueList &CstList = getConstantList();
1580
David Netofb9a7972017-08-25 17:08:24 -04001581 // If V is already tracked, ignore it.
1582 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001583 return;
1584 }
1585
David Neto862b7d82018-06-14 18:48:37 -04001586 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1587 return;
1588 }
1589
David Neto22f144c2017-06-12 14:26:21 -04001590 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001591 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001592
1593 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001594 if (is4xi8vec(CstTy)) {
1595 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001596 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001597 }
1598 }
1599
1600 if (Cst->getNumOperands()) {
1601 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1602 ++I) {
1603 FindConstant(*I);
1604 }
1605
David Netofb9a7972017-08-25 17:08:24 -04001606 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001607 return;
1608 } else if (const ConstantDataSequential *CDS =
1609 dyn_cast<ConstantDataSequential>(Cst)) {
1610 // Add constants for each element to constant list.
1611 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1612 Constant *EleCst = CDS->getElementAsConstant(i);
1613 FindConstant(EleCst);
1614 }
1615 }
1616
1617 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001618 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001619 }
1620}
1621
1622spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1623 switch (AddrSpace) {
1624 default:
1625 llvm_unreachable("Unsupported OpenCL address space");
1626 case AddressSpace::Private:
1627 return spv::StorageClassFunction;
1628 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001629 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001630 case AddressSpace::Constant:
1631 return clspv::Option::ConstantArgsInUniformBuffer()
1632 ? spv::StorageClassUniform
1633 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001634 case AddressSpace::Input:
1635 return spv::StorageClassInput;
1636 case AddressSpace::Local:
1637 return spv::StorageClassWorkgroup;
1638 case AddressSpace::UniformConstant:
1639 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001640 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001641 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001642 case AddressSpace::ModuleScopePrivate:
1643 return spv::StorageClassPrivate;
1644 }
1645}
1646
David Neto862b7d82018-06-14 18:48:37 -04001647spv::StorageClass
1648SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1649 switch (arg_kind) {
1650 case clspv::ArgKind::Buffer:
1651 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001652 case clspv::ArgKind::BufferUBO:
1653 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001654 case clspv::ArgKind::Pod:
1655 return clspv::Option::PodArgsInUniformBuffer()
1656 ? spv::StorageClassUniform
1657 : spv::StorageClassStorageBuffer;
1658 case clspv::ArgKind::Local:
1659 return spv::StorageClassWorkgroup;
1660 case clspv::ArgKind::ReadOnlyImage:
1661 case clspv::ArgKind::WriteOnlyImage:
1662 case clspv::ArgKind::Sampler:
1663 return spv::StorageClassUniformConstant;
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01001664 default:
1665 llvm_unreachable("Unsupported storage class for argument kind");
David Neto862b7d82018-06-14 18:48:37 -04001666 }
1667}
1668
David Neto22f144c2017-06-12 14:26:21 -04001669spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1670 return StringSwitch<spv::BuiltIn>(Name)
1671 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1672 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1673 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1674 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1675 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1676 .Default(spv::BuiltInMax);
1677}
1678
1679void SPIRVProducerPass::GenerateExtInstImport() {
1680 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1681 uint32_t &ExtInstImportID = getOpExtInstImportID();
1682
1683 //
1684 // Generate OpExtInstImport.
1685 //
1686 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001687 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001688 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1689 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001690}
1691
alan-bakerb6b09dc2018-11-08 16:59:28 -05001692void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext &Context,
1693 Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001694 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1695 ValueMapType &VMap = getValueMap();
1696 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001697 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001698
1699 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1700 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1701 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1702
1703 for (Type *Ty : getTypeList()) {
1704 // Update TypeMap with nextID for reference later.
1705 TypeMap[Ty] = nextID;
1706
1707 switch (Ty->getTypeID()) {
1708 default: {
1709 Ty->print(errs());
1710 llvm_unreachable("Unsupported type???");
1711 break;
1712 }
1713 case Type::MetadataTyID:
1714 case Type::LabelTyID: {
1715 // Ignore these types.
1716 break;
1717 }
1718 case Type::PointerTyID: {
1719 PointerType *PTy = cast<PointerType>(Ty);
1720 unsigned AddrSpace = PTy->getAddressSpace();
1721
1722 // For the purposes of our Vulkan SPIR-V type system, constant and global
1723 // are conflated.
1724 bool UseExistingOpTypePointer = false;
1725 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001726 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1727 AddrSpace = AddressSpace::Global;
alan-bakerb6b09dc2018-11-08 16:59:28 -05001728 // Check to see if we already created this type (for instance, if we
1729 // had a constant <type>* and a global <type>*, the type would be
1730 // created by one of these types, and shared by both).
Alan Bakerfcda9482018-10-02 17:09:59 -04001731 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1732 if (0 < TypeMap.count(GlobalTy)) {
1733 TypeMap[PTy] = TypeMap[GlobalTy];
1734 UseExistingOpTypePointer = true;
1735 break;
1736 }
David Neto22f144c2017-06-12 14:26:21 -04001737 }
1738 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001739 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1740 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001741
alan-bakerb6b09dc2018-11-08 16:59:28 -05001742 // Check to see if we already created this type (for instance, if we
1743 // had a constant <type>* and a global <type>*, the type would be
1744 // created by one of these types, and shared by both).
1745 auto ConstantTy =
1746 PTy->getPointerElementType()->getPointerTo(AddrSpace);
Alan Bakerfcda9482018-10-02 17:09:59 -04001747 if (0 < TypeMap.count(ConstantTy)) {
1748 TypeMap[PTy] = TypeMap[ConstantTy];
1749 UseExistingOpTypePointer = true;
1750 }
David Neto22f144c2017-06-12 14:26:21 -04001751 }
1752 }
1753
David Neto862b7d82018-06-14 18:48:37 -04001754 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001755
David Neto862b7d82018-06-14 18:48:37 -04001756 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001757 //
1758 // Generate OpTypePointer.
1759 //
1760
1761 // OpTypePointer
1762 // Ops[0] = Storage Class
1763 // Ops[1] = Element Type ID
1764 SPIRVOperandList Ops;
1765
David Neto257c3892018-04-11 13:19:45 -04001766 Ops << MkNum(GetStorageClass(AddrSpace))
1767 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001768
David Neto87846742018-04-11 17:36:22 -04001769 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001770 SPIRVInstList.push_back(Inst);
1771 }
David Neto22f144c2017-06-12 14:26:21 -04001772 break;
1773 }
1774 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001775 StructType *STy = cast<StructType>(Ty);
1776
1777 // Handle sampler type.
1778 if (STy->isOpaque()) {
1779 if (STy->getName().equals("opencl.sampler_t")) {
1780 //
1781 // Generate OpTypeSampler
1782 //
1783 // Empty Ops.
1784 SPIRVOperandList Ops;
1785
David Neto87846742018-04-11 17:36:22 -04001786 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001787 SPIRVInstList.push_back(Inst);
1788 break;
1789 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1790 STy->getName().equals("opencl.image2d_wo_t") ||
1791 STy->getName().equals("opencl.image3d_ro_t") ||
1792 STy->getName().equals("opencl.image3d_wo_t")) {
1793 //
1794 // Generate OpTypeImage
1795 //
1796 // Ops[0] = Sampled Type ID
1797 // Ops[1] = Dim ID
1798 // Ops[2] = Depth (Literal Number)
1799 // Ops[3] = Arrayed (Literal Number)
1800 // Ops[4] = MS (Literal Number)
1801 // Ops[5] = Sampled (Literal Number)
1802 // Ops[6] = Image Format ID
1803 //
1804 SPIRVOperandList Ops;
1805
1806 // TODO: Changed Sampled Type according to situations.
1807 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001808 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001809
1810 spv::Dim DimID = spv::Dim2D;
1811 if (STy->getName().equals("opencl.image3d_ro_t") ||
1812 STy->getName().equals("opencl.image3d_wo_t")) {
1813 DimID = spv::Dim3D;
1814 }
David Neto257c3892018-04-11 13:19:45 -04001815 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001816
1817 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001818 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001819
1820 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001821 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001822
1823 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001824 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001825
1826 // TODO: Set up Sampled.
1827 //
1828 // From Spec
1829 //
1830 // 0 indicates this is only known at run time, not at compile time
1831 // 1 indicates will be used with sampler
1832 // 2 indicates will be used without a sampler (a storage image)
1833 uint32_t Sampled = 1;
1834 if (STy->getName().equals("opencl.image2d_wo_t") ||
1835 STy->getName().equals("opencl.image3d_wo_t")) {
1836 Sampled = 2;
1837 }
David Neto257c3892018-04-11 13:19:45 -04001838 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001839
1840 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001841 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001842
David Neto87846742018-04-11 17:36:22 -04001843 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001844 SPIRVInstList.push_back(Inst);
1845 break;
1846 }
1847 }
1848
1849 //
1850 // Generate OpTypeStruct
1851 //
1852 // Ops[0] ... Ops[n] = Member IDs
1853 SPIRVOperandList Ops;
1854
1855 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001856 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001857 }
1858
David Neto22f144c2017-06-12 14:26:21 -04001859 uint32_t STyID = nextID;
1860
alan-bakerb6b09dc2018-11-08 16:59:28 -05001861 auto *Inst = new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001862 SPIRVInstList.push_back(Inst);
1863
1864 // Generate OpMemberDecorate.
1865 auto DecoInsertPoint =
1866 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1867 [](SPIRVInstruction *Inst) -> bool {
1868 return Inst->getOpcode() != spv::OpDecorate &&
1869 Inst->getOpcode() != spv::OpMemberDecorate &&
1870 Inst->getOpcode() != spv::OpExtInstImport;
1871 });
1872
David Netoc463b372017-08-10 15:32:21 -04001873 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001874 // Search for the correct offsets if this type was remapped.
1875 std::vector<uint32_t> *offsets = nullptr;
1876 auto iter = RemappedUBOTypeOffsets.find(STy);
1877 if (iter != RemappedUBOTypeOffsets.end()) {
1878 offsets = &iter->second;
1879 }
David Netoc463b372017-08-10 15:32:21 -04001880
David Neto862b7d82018-06-14 18:48:37 -04001881 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001882 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1883 MemberIdx++) {
1884 // Ops[0] = Structure Type ID
1885 // Ops[1] = Member Index(Literal Number)
1886 // Ops[2] = Decoration (Offset)
1887 // Ops[3] = Byte Offset (Literal Number)
1888 Ops.clear();
1889
David Neto257c3892018-04-11 13:19:45 -04001890 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001891
alan-bakerb6b09dc2018-11-08 16:59:28 -05001892 auto ByteOffset =
1893 static_cast<uint32_t>(StructLayout->getElementOffset(MemberIdx));
Alan Bakerfcda9482018-10-02 17:09:59 -04001894 if (offsets) {
1895 ByteOffset = (*offsets)[MemberIdx];
1896 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05001897 // const auto ByteOffset =
Alan Bakerfcda9482018-10-02 17:09:59 -04001898 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001899 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001900
David Neto87846742018-04-11 17:36:22 -04001901 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001902 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001903 }
1904
1905 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001906 if (StructTypesNeedingBlock.idFor(STy)) {
1907 Ops.clear();
1908 // Use Block decorations with StorageBuffer storage class.
1909 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001910
David Neto862b7d82018-06-14 18:48:37 -04001911 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1912 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001913 }
1914 break;
1915 }
1916 case Type::IntegerTyID: {
1917 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1918
1919 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001920 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001921 SPIRVInstList.push_back(Inst);
1922 } else {
alan-bakerb39c8262019-03-08 14:03:37 -05001923 if (!clspv::Option::Int8Support()) {
1924 // i8 is added to TypeMap as i32.
1925 // No matter what LLVM type is requested first, always alias the
1926 // second one's SPIR-V type to be the same as the one we generated
1927 // first.
1928 unsigned aliasToWidth = 0;
1929 if (BitWidth == 8) {
1930 aliasToWidth = 32;
1931 BitWidth = 32;
1932 } else if (BitWidth == 32) {
1933 aliasToWidth = 8;
1934 }
1935 if (aliasToWidth) {
1936 Type *otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1937 auto where = TypeMap.find(otherType);
1938 if (where == TypeMap.end()) {
1939 // Go ahead and make it, but also map the other type to it.
1940 TypeMap[otherType] = nextID;
1941 } else {
1942 // Alias this SPIR-V type the existing type.
1943 TypeMap[Ty] = where->second;
1944 break;
1945 }
David Neto391aeb12017-08-26 15:51:58 -04001946 }
David Neto22f144c2017-06-12 14:26:21 -04001947 }
1948
David Neto257c3892018-04-11 13:19:45 -04001949 SPIRVOperandList Ops;
1950 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04001951
1952 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001953 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001954 }
1955 break;
1956 }
1957 case Type::HalfTyID:
1958 case Type::FloatTyID:
1959 case Type::DoubleTyID: {
1960 SPIRVOperand *WidthOp = new SPIRVOperand(
1961 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1962
1963 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04001964 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04001965 break;
1966 }
1967 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001968 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04001969 const uint64_t Length = ArrTy->getArrayNumElements();
1970 if (Length == 0) {
1971 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04001972
David Neto862b7d82018-06-14 18:48:37 -04001973 // Only generate the type once.
1974 // TODO(dneto): Can it ever be generated more than once?
1975 // Doesn't LLVM type uniqueness guarantee we'll only see this
1976 // once?
1977 Type *EleTy = ArrTy->getArrayElementType();
1978 if (OpRuntimeTyMap.count(EleTy) == 0) {
1979 uint32_t OpTypeRuntimeArrayID = nextID;
1980 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04001981
David Neto862b7d82018-06-14 18:48:37 -04001982 //
1983 // Generate OpTypeRuntimeArray.
1984 //
David Neto22f144c2017-06-12 14:26:21 -04001985
David Neto862b7d82018-06-14 18:48:37 -04001986 // OpTypeRuntimeArray
1987 // Ops[0] = Element Type ID
1988 SPIRVOperandList Ops;
1989 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001990
David Neto862b7d82018-06-14 18:48:37 -04001991 SPIRVInstList.push_back(
1992 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04001993
David Neto862b7d82018-06-14 18:48:37 -04001994 if (Hack_generate_runtime_array_stride_early) {
1995 // Generate OpDecorate.
1996 auto DecoInsertPoint = std::find_if(
1997 SPIRVInstList.begin(), SPIRVInstList.end(),
1998 [](SPIRVInstruction *Inst) -> bool {
1999 return Inst->getOpcode() != spv::OpDecorate &&
2000 Inst->getOpcode() != spv::OpMemberDecorate &&
2001 Inst->getOpcode() != spv::OpExtInstImport;
2002 });
David Neto22f144c2017-06-12 14:26:21 -04002003
David Neto862b7d82018-06-14 18:48:37 -04002004 // Ops[0] = Target ID
2005 // Ops[1] = Decoration (ArrayStride)
2006 // Ops[2] = Stride Number(Literal Number)
2007 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002008
David Neto862b7d82018-06-14 18:48:37 -04002009 Ops << MkId(OpTypeRuntimeArrayID)
2010 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002011 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002012
David Neto862b7d82018-06-14 18:48:37 -04002013 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2014 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2015 }
2016 }
David Neto22f144c2017-06-12 14:26:21 -04002017
David Neto862b7d82018-06-14 18:48:37 -04002018 } else {
David Neto22f144c2017-06-12 14:26:21 -04002019
David Neto862b7d82018-06-14 18:48:37 -04002020 //
2021 // Generate OpConstant and OpTypeArray.
2022 //
2023
2024 //
2025 // Generate OpConstant for array length.
2026 //
2027 // Ops[0] = Result Type ID
2028 // Ops[1] .. Ops[n] = Values LiteralNumber
2029 SPIRVOperandList Ops;
2030
2031 Type *LengthTy = Type::getInt32Ty(Context);
2032 uint32_t ResTyID = lookupType(LengthTy);
2033 Ops << MkId(ResTyID);
2034
2035 assert(Length < UINT32_MAX);
2036 Ops << MkNum(static_cast<uint32_t>(Length));
2037
2038 // Add constant for length to constant list.
2039 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2040 AllocatedVMap[CstLength] = nextID;
2041 VMap[CstLength] = nextID;
2042 uint32_t LengthID = nextID;
2043
2044 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2045 SPIRVInstList.push_back(CstInst);
2046
2047 // Remember to generate ArrayStride later
2048 getTypesNeedingArrayStride().insert(Ty);
2049
2050 //
2051 // Generate OpTypeArray.
2052 //
2053 // Ops[0] = Element Type ID
2054 // Ops[1] = Array Length Constant ID
2055 Ops.clear();
2056
2057 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2058 Ops << MkId(EleTyID) << MkId(LengthID);
2059
2060 // Update TypeMap with nextID.
2061 TypeMap[Ty] = nextID;
2062
2063 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2064 SPIRVInstList.push_back(ArrayInst);
2065 }
David Neto22f144c2017-06-12 14:26:21 -04002066 break;
2067 }
2068 case Type::VectorTyID: {
alan-bakerb39c8262019-03-08 14:03:37 -05002069 // <4 x i8> is changed to i32 if i8 is not generally supported.
2070 if (!clspv::Option::Int8Support() &&
2071 Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
David Neto22f144c2017-06-12 14:26:21 -04002072 if (Ty->getVectorNumElements() == 4) {
2073 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2074 break;
2075 } else {
2076 Ty->print(errs());
2077 llvm_unreachable("Support above i8 vector type");
2078 }
2079 }
2080
2081 // Ops[0] = Component Type ID
2082 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002083 SPIRVOperandList Ops;
2084 Ops << MkId(lookupType(Ty->getVectorElementType()))
2085 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002086
alan-bakerb6b09dc2018-11-08 16:59:28 -05002087 SPIRVInstruction *inst =
2088 new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002089 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002090 break;
2091 }
2092 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002093 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002094 SPIRVInstList.push_back(Inst);
2095 break;
2096 }
2097 case Type::FunctionTyID: {
2098 // Generate SPIRV instruction for function type.
2099 FunctionType *FTy = cast<FunctionType>(Ty);
2100
2101 // Ops[0] = Return Type ID
2102 // Ops[1] ... Ops[n] = Parameter Type IDs
2103 SPIRVOperandList Ops;
2104
2105 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002106 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002107
2108 // Find SPIRV instructions for parameter types
2109 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2110 // Find SPIRV instruction for parameter type.
2111 auto ParamTy = FTy->getParamType(k);
2112 if (ParamTy->isPointerTy()) {
2113 auto PointeeTy = ParamTy->getPointerElementType();
2114 if (PointeeTy->isStructTy() &&
2115 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2116 ParamTy = PointeeTy;
2117 }
2118 }
2119
David Netoc6f3ab22018-04-06 18:02:31 -04002120 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002121 }
2122
David Neto87846742018-04-11 17:36:22 -04002123 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002124 SPIRVInstList.push_back(Inst);
2125 break;
2126 }
2127 }
2128 }
2129
2130 // Generate OpTypeSampledImage.
2131 TypeMapType &OpImageTypeMap = getImageTypeMap();
2132 for (auto &ImageType : OpImageTypeMap) {
2133 //
2134 // Generate OpTypeSampledImage.
2135 //
2136 // Ops[0] = Image Type ID
2137 //
2138 SPIRVOperandList Ops;
2139
2140 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002141 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002142
2143 // Update OpImageTypeMap.
2144 ImageType.second = nextID;
2145
David Neto87846742018-04-11 17:36:22 -04002146 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002147 SPIRVInstList.push_back(Inst);
2148 }
David Netoc6f3ab22018-04-06 18:02:31 -04002149
2150 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002151 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2152 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002153 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002154
2155 // Generate the spec constant.
2156 SPIRVOperandList Ops;
2157 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002158 SPIRVInstList.push_back(
2159 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002160
2161 // Generate the array type.
2162 Ops.clear();
2163 // The element type must have been created.
2164 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2165 assert(elem_ty_id);
2166 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2167
2168 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002169 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002170
2171 Ops.clear();
2172 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002173 SPIRVInstList.push_back(new SPIRVInstruction(
2174 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002175 }
David Neto22f144c2017-06-12 14:26:21 -04002176}
2177
2178void SPIRVProducerPass::GenerateSPIRVConstants() {
2179 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2180 ValueMapType &VMap = getValueMap();
2181 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2182 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002183 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002184
2185 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002186 // UniqueVector ids are 1-based.
alan-bakerb6b09dc2018-11-08 16:59:28 -05002187 Constant *Cst = cast<Constant>(CstList[i + 1]);
David Neto22f144c2017-06-12 14:26:21 -04002188
2189 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002190 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002191 continue;
2192 }
2193
David Netofb9a7972017-08-25 17:08:24 -04002194 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002195 VMap[Cst] = nextID;
2196
2197 //
2198 // Generate OpConstant.
2199 //
2200
2201 // Ops[0] = Result Type ID
2202 // Ops[1] .. Ops[n] = Values LiteralNumber
2203 SPIRVOperandList Ops;
2204
David Neto257c3892018-04-11 13:19:45 -04002205 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002206
2207 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002208 spv::Op Opcode = spv::OpNop;
2209
2210 if (isa<UndefValue>(Cst)) {
2211 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002212 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002213 if (hack_undef && IsTypeNullable(Cst->getType())) {
2214 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002215 }
David Neto22f144c2017-06-12 14:26:21 -04002216 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2217 unsigned BitWidth = CI->getBitWidth();
2218 if (BitWidth == 1) {
2219 // If the bitwidth of constant is 1, generate OpConstantTrue or
2220 // OpConstantFalse.
2221 if (CI->getZExtValue()) {
2222 // Ops[0] = Result Type ID
2223 Opcode = spv::OpConstantTrue;
2224 } else {
2225 // Ops[0] = Result Type ID
2226 Opcode = spv::OpConstantFalse;
2227 }
David Neto22f144c2017-06-12 14:26:21 -04002228 } else {
2229 auto V = CI->getZExtValue();
2230 LiteralNum.push_back(V & 0xFFFFFFFF);
2231
2232 if (BitWidth > 32) {
2233 LiteralNum.push_back(V >> 32);
2234 }
2235
2236 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002237
David Neto257c3892018-04-11 13:19:45 -04002238 Ops << MkInteger(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002239 }
2240 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2241 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2242 Type *CFPTy = CFP->getType();
2243 if (CFPTy->isFloatTy()) {
2244 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
Kévin Petit02ee34e2019-04-04 19:03:22 +01002245 } else if (CFPTy->isDoubleTy()) {
2246 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2247 LiteralNum.push_back(FPVal >> 32);
David Neto22f144c2017-06-12 14:26:21 -04002248 } else {
2249 CFPTy->print(errs());
2250 llvm_unreachable("Implement this ConstantFP Type");
2251 }
2252
2253 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002254
David Neto257c3892018-04-11 13:19:45 -04002255 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002256 } else if (isa<ConstantDataSequential>(Cst) &&
2257 cast<ConstantDataSequential>(Cst)->isString()) {
2258 Cst->print(errs());
2259 llvm_unreachable("Implement this Constant");
2260
2261 } else if (const ConstantDataSequential *CDS =
2262 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002263 // Let's convert <4 x i8> constant to int constant specially.
2264 // This case occurs when all the values are specified as constant
2265 // ints.
2266 Type *CstTy = Cst->getType();
2267 if (is4xi8vec(CstTy)) {
2268 LLVMContext &Context = CstTy->getContext();
2269
2270 //
2271 // Generate OpConstant with OpTypeInt 32 0.
2272 //
Neil Henning39672102017-09-29 14:33:13 +01002273 uint32_t IntValue = 0;
2274 for (unsigned k = 0; k < 4; k++) {
2275 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002276 IntValue = (IntValue << 8) | (Val & 0xffu);
2277 }
2278
2279 Type *i32 = Type::getInt32Ty(Context);
2280 Constant *CstInt = ConstantInt::get(i32, IntValue);
2281 // If this constant is already registered on VMap, use it.
2282 if (VMap.count(CstInt)) {
2283 uint32_t CstID = VMap[CstInt];
2284 VMap[Cst] = CstID;
2285 continue;
2286 }
2287
David Neto257c3892018-04-11 13:19:45 -04002288 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002289
David Neto87846742018-04-11 17:36:22 -04002290 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002291 SPIRVInstList.push_back(CstInst);
2292
2293 continue;
2294 }
2295
2296 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002297 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2298 Constant *EleCst = CDS->getElementAsConstant(k);
2299 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002300 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002301 }
2302
2303 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002304 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2305 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002306 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002307 Type *CstTy = Cst->getType();
2308 if (is4xi8vec(CstTy)) {
2309 LLVMContext &Context = CstTy->getContext();
2310
2311 //
2312 // Generate OpConstant with OpTypeInt 32 0.
2313 //
Neil Henning39672102017-09-29 14:33:13 +01002314 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002315 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2316 I != E; ++I) {
2317 uint64_t Val = 0;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002318 const Value *CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002319 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2320 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002321 }
David Neto49351ac2017-08-26 17:32:20 -04002322 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002323 }
2324
David Neto49351ac2017-08-26 17:32:20 -04002325 Type *i32 = Type::getInt32Ty(Context);
2326 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002327 // If this constant is already registered on VMap, use it.
2328 if (VMap.count(CstInt)) {
2329 uint32_t CstID = VMap[CstInt];
2330 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002331 continue;
David Neto22f144c2017-06-12 14:26:21 -04002332 }
2333
David Neto257c3892018-04-11 13:19:45 -04002334 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002335
David Neto87846742018-04-11 17:36:22 -04002336 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002337 SPIRVInstList.push_back(CstInst);
2338
David Neto19a1bad2017-08-25 15:01:41 -04002339 continue;
David Neto22f144c2017-06-12 14:26:21 -04002340 }
2341
2342 // We use a constant composite in SPIR-V for our constant aggregate in
2343 // LLVM.
2344 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002345
2346 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2347 // Look up the ID of the element of this aggregate (which we will
2348 // previously have created a constant for).
2349 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2350
2351 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002352 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002353 }
2354 } else if (Cst->isNullValue()) {
2355 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002356 } else {
2357 Cst->print(errs());
2358 llvm_unreachable("Unsupported Constant???");
2359 }
2360
alan-baker5b86ed72019-02-15 08:26:50 -05002361 if (Opcode == spv::OpConstantNull && Cst->getType()->isPointerTy()) {
2362 // Null pointer requires variable pointers.
2363 setVariablePointersCapabilities(Cst->getType()->getPointerAddressSpace());
2364 }
2365
David Neto87846742018-04-11 17:36:22 -04002366 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002367 SPIRVInstList.push_back(CstInst);
2368 }
2369}
2370
2371void SPIRVProducerPass::GenerateSamplers(Module &M) {
2372 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto22f144c2017-06-12 14:26:21 -04002373
alan-bakerb6b09dc2018-11-08 16:59:28 -05002374 auto &sampler_map = getSamplerMap();
David Neto862b7d82018-06-14 18:48:37 -04002375 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002376 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002377 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2378 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002379
David Neto862b7d82018-06-14 18:48:37 -04002380 // We might have samplers in the sampler map that are not used
2381 // in the translation unit. We need to allocate variables
2382 // for them and bindings too.
2383 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002384
Kévin Petitdf71de32019-04-09 14:09:50 +01002385 auto *var_fn = M.getFunction(clspv::LiteralSamplerFunction());
alan-bakerb6b09dc2018-11-08 16:59:28 -05002386 if (!var_fn)
2387 return;
David Neto862b7d82018-06-14 18:48:37 -04002388 for (auto user : var_fn->users()) {
2389 // Populate SamplerLiteralToDescriptorSetMap and
2390 // SamplerLiteralToBindingMap.
2391 //
2392 // Look for calls like
2393 // call %opencl.sampler_t addrspace(2)*
2394 // @clspv.sampler.var.literal(
2395 // i32 descriptor,
2396 // i32 binding,
2397 // i32 index-into-sampler-map)
alan-bakerb6b09dc2018-11-08 16:59:28 -05002398 if (auto *call = dyn_cast<CallInst>(user)) {
2399 const size_t index_into_sampler_map = static_cast<size_t>(
2400 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002401 if (index_into_sampler_map >= sampler_map.size()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002402 errs() << "Out of bounds index to sampler map: "
2403 << index_into_sampler_map;
David Neto862b7d82018-06-14 18:48:37 -04002404 llvm_unreachable("bad sampler init: out of bounds");
2405 }
2406
2407 auto sampler_value = sampler_map[index_into_sampler_map].first;
2408 const auto descriptor_set = static_cast<unsigned>(
2409 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2410 const auto binding = static_cast<unsigned>(
2411 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2412
2413 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2414 SamplerLiteralToBindingMap[sampler_value] = binding;
2415 used_bindings.insert(binding);
2416 }
2417 }
2418
2419 unsigned index = 0;
2420 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002421 // Generate OpVariable.
2422 //
2423 // GIDOps[0] : Result Type ID
2424 // GIDOps[1] : Storage Class
2425 SPIRVOperandList Ops;
2426
David Neto257c3892018-04-11 13:19:45 -04002427 Ops << MkId(lookupType(SamplerTy))
2428 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002429
David Neto862b7d82018-06-14 18:48:37 -04002430 auto sampler_var_id = nextID++;
2431 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002432 SPIRVInstList.push_back(Inst);
2433
David Neto862b7d82018-06-14 18:48:37 -04002434 SamplerMapIndexToIDMap[index] = sampler_var_id;
2435 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002436
2437 // Find Insert Point for OpDecorate.
2438 auto DecoInsertPoint =
2439 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2440 [](SPIRVInstruction *Inst) -> bool {
2441 return Inst->getOpcode() != spv::OpDecorate &&
2442 Inst->getOpcode() != spv::OpMemberDecorate &&
2443 Inst->getOpcode() != spv::OpExtInstImport;
2444 });
2445
2446 // Ops[0] = Target ID
2447 // Ops[1] = Decoration (DescriptorSet)
2448 // Ops[2] = LiteralNumber according to Decoration
2449 Ops.clear();
2450
David Neto862b7d82018-06-14 18:48:37 -04002451 unsigned descriptor_set;
2452 unsigned binding;
alan-bakerb6b09dc2018-11-08 16:59:28 -05002453 if (SamplerLiteralToBindingMap.find(SamplerLiteral.first) ==
2454 SamplerLiteralToBindingMap.end()) {
David Neto862b7d82018-06-14 18:48:37 -04002455 // This sampler is not actually used. Find the next one.
2456 for (binding = 0; used_bindings.count(binding); binding++)
2457 ;
2458 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2459 used_bindings.insert(binding);
2460 } else {
2461 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2462 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
alan-bakercff80152019-06-15 00:38:00 -04002463
2464 version0::DescriptorMapEntry::SamplerData sampler_data = {
2465 SamplerLiteral.first};
2466 descriptorMapEntries->emplace_back(std::move(sampler_data),
2467 descriptor_set, binding);
David Neto862b7d82018-06-14 18:48:37 -04002468 }
2469
2470 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2471 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002472
David Neto87846742018-04-11 17:36:22 -04002473 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002474 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2475
2476 // Ops[0] = Target ID
2477 // Ops[1] = Decoration (Binding)
2478 // Ops[2] = LiteralNumber according to Decoration
2479 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002480 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2481 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002482
David Neto87846742018-04-11 17:36:22 -04002483 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002484 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002485
2486 index++;
David Neto22f144c2017-06-12 14:26:21 -04002487 }
David Neto862b7d82018-06-14 18:48:37 -04002488}
David Neto22f144c2017-06-12 14:26:21 -04002489
Radek Szymanskibe4b0c42018-10-04 22:20:53 +01002490void SPIRVProducerPass::GenerateResourceVars(Module &) {
David Neto862b7d82018-06-14 18:48:37 -04002491 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2492 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002493
David Neto862b7d82018-06-14 18:48:37 -04002494 // Generate variables. Make one for each of resource var info object.
2495 for (auto *info : ModuleOrderedResourceVars) {
2496 Type *type = info->var_fn->getReturnType();
2497 // Remap the address space for opaque types.
2498 switch (info->arg_kind) {
2499 case clspv::ArgKind::Sampler:
2500 case clspv::ArgKind::ReadOnlyImage:
2501 case clspv::ArgKind::WriteOnlyImage:
2502 type = PointerType::get(type->getPointerElementType(),
2503 clspv::AddressSpace::UniformConstant);
2504 break;
2505 default:
2506 break;
2507 }
David Neto22f144c2017-06-12 14:26:21 -04002508
David Neto862b7d82018-06-14 18:48:37 -04002509 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002510
David Neto862b7d82018-06-14 18:48:37 -04002511 const auto type_id = lookupType(type);
2512 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2513 SPIRVOperandList Ops;
2514 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto862b7d82018-06-14 18:48:37 -04002516 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2517 SPIRVInstList.push_back(Inst);
2518
2519 // Map calls to the variable-builtin-function.
2520 for (auto &U : info->var_fn->uses()) {
2521 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2522 const auto set = unsigned(
2523 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2524 const auto binding = unsigned(
2525 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2526 if (set == info->descriptor_set && binding == info->binding) {
2527 switch (info->arg_kind) {
2528 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002529 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002530 case clspv::ArgKind::Pod:
2531 // The call maps to the variable directly.
2532 VMap[call] = info->var_id;
2533 break;
2534 case clspv::ArgKind::Sampler:
2535 case clspv::ArgKind::ReadOnlyImage:
2536 case clspv::ArgKind::WriteOnlyImage:
2537 // The call maps to a load we generate later.
2538 ResourceVarDeferredLoadCalls[call] = info->var_id;
2539 break;
2540 default:
2541 llvm_unreachable("Unhandled arg kind");
2542 }
2543 }
David Neto22f144c2017-06-12 14:26:21 -04002544 }
David Neto862b7d82018-06-14 18:48:37 -04002545 }
2546 }
David Neto22f144c2017-06-12 14:26:21 -04002547
David Neto862b7d82018-06-14 18:48:37 -04002548 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002549
David Neto862b7d82018-06-14 18:48:37 -04002550 // Find Insert Point for OpDecorate.
2551 auto DecoInsertPoint =
2552 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2553 [](SPIRVInstruction *Inst) -> bool {
2554 return Inst->getOpcode() != spv::OpDecorate &&
2555 Inst->getOpcode() != spv::OpMemberDecorate &&
2556 Inst->getOpcode() != spv::OpExtInstImport;
2557 });
2558
2559 SPIRVOperandList Ops;
2560 for (auto *info : ModuleOrderedResourceVars) {
2561 // Decorate with DescriptorSet and Binding.
2562 Ops.clear();
2563 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2564 << MkNum(info->descriptor_set);
2565 SPIRVInstList.insert(DecoInsertPoint,
2566 new SPIRVInstruction(spv::OpDecorate, Ops));
2567
2568 Ops.clear();
2569 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2570 << MkNum(info->binding);
2571 SPIRVInstList.insert(DecoInsertPoint,
2572 new SPIRVInstruction(spv::OpDecorate, Ops));
2573
alan-bakere9308012019-03-15 10:25:13 -04002574 if (info->coherent) {
2575 // Decorate with Coherent if required for the variable.
2576 Ops.clear();
2577 Ops << MkId(info->var_id) << MkNum(spv::DecorationCoherent);
2578 SPIRVInstList.insert(DecoInsertPoint,
2579 new SPIRVInstruction(spv::OpDecorate, Ops));
2580 }
2581
David Neto862b7d82018-06-14 18:48:37 -04002582 // Generate NonWritable and NonReadable
2583 switch (info->arg_kind) {
2584 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002585 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002586 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2587 clspv::AddressSpace::Constant) {
2588 Ops.clear();
2589 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2590 SPIRVInstList.insert(DecoInsertPoint,
2591 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002592 }
David Neto862b7d82018-06-14 18:48:37 -04002593 break;
David Neto862b7d82018-06-14 18:48:37 -04002594 case clspv::ArgKind::WriteOnlyImage:
2595 Ops.clear();
2596 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2597 SPIRVInstList.insert(DecoInsertPoint,
2598 new SPIRVInstruction(spv::OpDecorate, Ops));
2599 break;
2600 default:
2601 break;
David Neto22f144c2017-06-12 14:26:21 -04002602 }
2603 }
2604}
2605
2606void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002607 Module &M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002608 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2609 ValueMapType &VMap = getValueMap();
2610 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002611 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002612
2613 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2614 Type *Ty = GV.getType();
2615 PointerType *PTy = cast<PointerType>(Ty);
2616
2617 uint32_t InitializerID = 0;
2618
2619 // Workgroup size is handled differently (it goes into a constant)
2620 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2621 std::vector<bool> HasMDVec;
2622 uint32_t PrevXDimCst = 0xFFFFFFFF;
2623 uint32_t PrevYDimCst = 0xFFFFFFFF;
2624 uint32_t PrevZDimCst = 0xFFFFFFFF;
2625 for (Function &Func : *GV.getParent()) {
2626 if (Func.isDeclaration()) {
2627 continue;
2628 }
2629
2630 // We only need to check kernels.
2631 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2632 continue;
2633 }
2634
2635 if (const MDNode *MD =
2636 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2637 uint32_t CurXDimCst = static_cast<uint32_t>(
2638 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2639 uint32_t CurYDimCst = static_cast<uint32_t>(
2640 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2641 uint32_t CurZDimCst = static_cast<uint32_t>(
2642 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2643
2644 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2645 PrevZDimCst == 0xFFFFFFFF) {
2646 PrevXDimCst = CurXDimCst;
2647 PrevYDimCst = CurYDimCst;
2648 PrevZDimCst = CurZDimCst;
2649 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2650 CurZDimCst != PrevZDimCst) {
2651 llvm_unreachable(
2652 "reqd_work_group_size must be the same across all kernels");
2653 } else {
2654 continue;
2655 }
2656
2657 //
2658 // Generate OpConstantComposite.
2659 //
2660 // Ops[0] : Result Type ID
2661 // Ops[1] : Constant size for x dimension.
2662 // Ops[2] : Constant size for y dimension.
2663 // Ops[3] : Constant size for z dimension.
2664 SPIRVOperandList Ops;
2665
2666 uint32_t XDimCstID =
2667 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2668 uint32_t YDimCstID =
2669 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2670 uint32_t ZDimCstID =
2671 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2672
2673 InitializerID = nextID;
2674
David Neto257c3892018-04-11 13:19:45 -04002675 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2676 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002677
David Neto87846742018-04-11 17:36:22 -04002678 auto *Inst =
2679 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002680 SPIRVInstList.push_back(Inst);
2681
2682 HasMDVec.push_back(true);
2683 } else {
2684 HasMDVec.push_back(false);
2685 }
2686 }
2687
2688 // Check all kernels have same definitions for work_group_size.
2689 bool HasMD = false;
2690 if (!HasMDVec.empty()) {
2691 HasMD = HasMDVec[0];
2692 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2693 if (HasMD != HasMDVec[i]) {
2694 llvm_unreachable(
2695 "Kernels should have consistent work group size definition");
2696 }
2697 }
2698 }
2699
2700 // If all kernels do not have metadata for reqd_work_group_size, generate
2701 // OpSpecConstants for x/y/z dimension.
2702 if (!HasMD) {
2703 //
2704 // Generate OpSpecConstants for x/y/z dimension.
2705 //
2706 // Ops[0] : Result Type ID
2707 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2708 uint32_t XDimCstID = 0;
2709 uint32_t YDimCstID = 0;
2710 uint32_t ZDimCstID = 0;
2711
David Neto22f144c2017-06-12 14:26:21 -04002712 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002713 uint32_t result_type_id =
2714 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002715
David Neto257c3892018-04-11 13:19:45 -04002716 // X Dimension
2717 Ops << MkId(result_type_id) << MkNum(1);
2718 XDimCstID = nextID++;
2719 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002720 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002721
2722 // Y Dimension
2723 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002724 Ops << MkId(result_type_id) << MkNum(1);
2725 YDimCstID = nextID++;
2726 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002727 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002728
2729 // Z Dimension
2730 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002731 Ops << MkId(result_type_id) << MkNum(1);
2732 ZDimCstID = nextID++;
2733 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002734 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002735
David Neto257c3892018-04-11 13:19:45 -04002736 BuiltinDimVec.push_back(XDimCstID);
2737 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002738 BuiltinDimVec.push_back(ZDimCstID);
2739
David Neto22f144c2017-06-12 14:26:21 -04002740 //
2741 // Generate OpSpecConstantComposite.
2742 //
2743 // Ops[0] : Result Type ID
2744 // Ops[1] : Constant size for x dimension.
2745 // Ops[2] : Constant size for y dimension.
2746 // Ops[3] : Constant size for z dimension.
2747 InitializerID = nextID;
2748
2749 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002750 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2751 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002752
David Neto87846742018-04-11 17:36:22 -04002753 auto *Inst =
2754 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVInstList.push_back(Inst);
2756 }
2757 }
2758
David Neto22f144c2017-06-12 14:26:21 -04002759 VMap[&GV] = nextID;
2760
2761 //
2762 // Generate OpVariable.
2763 //
2764 // GIDOps[0] : Result Type ID
2765 // GIDOps[1] : Storage Class
2766 SPIRVOperandList Ops;
2767
David Neto85082642018-03-24 06:55:20 -07002768 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002769 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002770
David Neto85082642018-03-24 06:55:20 -07002771 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002772 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002773 clspv::Option::ModuleConstantsInStorageBuffer();
2774
Kévin Petit23d5f182019-08-13 16:21:29 +01002775 if (GV.hasInitializer()) {
2776 auto GVInit = GV.getInitializer();
2777 if (!isa<UndefValue>(GVInit) && !module_scope_constant_external_init) {
2778 assert(VMap.count(GVInit) == 1);
2779 InitializerID = VMap[GVInit];
David Neto85082642018-03-24 06:55:20 -07002780 }
2781 }
Kévin Petit23d5f182019-08-13 16:21:29 +01002782
2783 if (0 != InitializerID) {
2784 // Emit the ID of the intiializer as part of the variable definition.
2785 Ops << MkId(InitializerID);
2786 }
David Neto85082642018-03-24 06:55:20 -07002787 const uint32_t var_id = nextID++;
2788
David Neto87846742018-04-11 17:36:22 -04002789 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002790 SPIRVInstList.push_back(Inst);
2791
2792 // If we have a builtin.
2793 if (spv::BuiltInMax != BuiltinType) {
2794 // Find Insert Point for OpDecorate.
2795 auto DecoInsertPoint =
2796 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2797 [](SPIRVInstruction *Inst) -> bool {
2798 return Inst->getOpcode() != spv::OpDecorate &&
2799 Inst->getOpcode() != spv::OpMemberDecorate &&
2800 Inst->getOpcode() != spv::OpExtInstImport;
2801 });
2802 //
2803 // Generate OpDecorate.
2804 //
2805 // DOps[0] = Target ID
2806 // DOps[1] = Decoration (Builtin)
2807 // DOps[2] = BuiltIn ID
2808 uint32_t ResultID;
2809
2810 // WorkgroupSize is different, we decorate the constant composite that has
2811 // its value, rather than the variable that we use to access the value.
2812 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2813 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002814 // Save both the value and variable IDs for later.
2815 WorkgroupSizeValueID = InitializerID;
2816 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002817 } else {
2818 ResultID = VMap[&GV];
2819 }
2820
2821 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002822 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2823 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002824
David Neto87846742018-04-11 17:36:22 -04002825 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002826 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002827 } else if (module_scope_constant_external_init) {
2828 // This module scope constant is initialized from a storage buffer with data
2829 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002830 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002831
David Neto862b7d82018-06-14 18:48:37 -04002832 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002833 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2834 // that later to other types, like uniform buffer.
alan-bakerf5e5f692018-11-27 08:33:24 -05002835 std::string hexbytes;
2836 llvm::raw_string_ostream str(hexbytes);
2837 clspv::ConstantEmitter(DL, str).Emit(GV.getInitializer());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002838 version0::DescriptorMapEntry::ConstantData constant_data = {ArgKind::Buffer,
2839 str.str()};
2840 descriptorMapEntries->emplace_back(std::move(constant_data), descriptor_set,
2841 0);
David Neto85082642018-03-24 06:55:20 -07002842
2843 // Find Insert Point for OpDecorate.
2844 auto DecoInsertPoint =
2845 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2846 [](SPIRVInstruction *Inst) -> bool {
2847 return Inst->getOpcode() != spv::OpDecorate &&
2848 Inst->getOpcode() != spv::OpMemberDecorate &&
2849 Inst->getOpcode() != spv::OpExtInstImport;
2850 });
2851
David Neto257c3892018-04-11 13:19:45 -04002852 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002853 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002854 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2855 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002856 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002857
2858 // OpDecorate %var DescriptorSet <descriptor_set>
2859 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002860 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2861 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002862 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002863 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002864 }
2865}
2866
David Netoc6f3ab22018-04-06 18:02:31 -04002867void SPIRVProducerPass::GenerateWorkgroupVars() {
2868 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002869 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2870 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002871 LocalArgInfo &info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002872
2873 // Generate OpVariable.
2874 //
2875 // GIDOps[0] : Result Type ID
2876 // GIDOps[1] : Storage Class
2877 SPIRVOperandList Ops;
2878 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2879
2880 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002881 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002882 }
2883}
2884
David Neto862b7d82018-06-14 18:48:37 -04002885void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2886 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002887 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2888 return;
2889 }
David Neto862b7d82018-06-14 18:48:37 -04002890 // Gather the list of resources that are used by this function's arguments.
2891 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2892
alan-bakerf5e5f692018-11-27 08:33:24 -05002893 // TODO(alan-baker): This should become unnecessary by fixing the rest of the
2894 // flow to generate pod_ubo arguments earlier.
David Neto862b7d82018-06-14 18:48:37 -04002895 auto remap_arg_kind = [](StringRef argKind) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002896 std::string kind =
2897 clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2898 ? "pod_ubo"
2899 : argKind;
2900 return GetArgKindFromName(kind);
David Neto862b7d82018-06-14 18:48:37 -04002901 };
2902
2903 auto *fty = F.getType()->getPointerElementType();
2904 auto *func_ty = dyn_cast<FunctionType>(fty);
2905
alan-baker038e9242019-04-19 22:14:41 -04002906 // If we've clustered POD arguments, then argument details are in metadata.
David Neto862b7d82018-06-14 18:48:37 -04002907 // If an argument maps to a resource variable, then get descriptor set and
2908 // binding from the resoure variable. Other info comes from the metadata.
2909 const auto *arg_map = F.getMetadata("kernel_arg_map");
2910 if (arg_map) {
2911 for (const auto &arg : arg_map->operands()) {
2912 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002913 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002914 const auto name =
2915 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2916 const auto old_index =
2917 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2918 // Remapped argument index
alan-bakerb6b09dc2018-11-08 16:59:28 -05002919 const size_t new_index = static_cast<size_t>(
2920 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue());
David Neto862b7d82018-06-14 18:48:37 -04002921 const auto offset =
2922 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002923 const auto arg_size =
2924 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002925 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002926 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002927 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002928 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
alan-bakerf5e5f692018-11-27 08:33:24 -05002929
2930 uint32_t descriptor_set = 0;
2931 uint32_t binding = 0;
2932 version0::DescriptorMapEntry::KernelArgData kernel_data = {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002933 F.getName(), name, static_cast<uint32_t>(old_index), argKind,
alan-bakerf5e5f692018-11-27 08:33:24 -05002934 static_cast<uint32_t>(spec_id),
2935 // This will be set below for pointer-to-local args.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002936 0, static_cast<uint32_t>(offset), static_cast<uint32_t>(arg_size)};
David Neto862b7d82018-06-14 18:48:37 -04002937 if (spec_id > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05002938 kernel_data.local_element_size = static_cast<uint32_t>(GetTypeAllocSize(
2939 func_ty->getParamType(unsigned(new_index))->getPointerElementType(),
2940 DL));
David Neto862b7d82018-06-14 18:48:37 -04002941 } else {
2942 auto *info = resource_var_at_index[new_index];
2943 assert(info);
alan-bakerf5e5f692018-11-27 08:33:24 -05002944 descriptor_set = info->descriptor_set;
2945 binding = info->binding;
David Neto862b7d82018-06-14 18:48:37 -04002946 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002947 descriptorMapEntries->emplace_back(std::move(kernel_data), descriptor_set,
2948 binding);
David Neto862b7d82018-06-14 18:48:37 -04002949 }
2950 } else {
2951 // There is no argument map.
2952 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002953 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002954
2955 SmallVector<Argument *, 4> arguments;
2956 for (auto &arg : F.args()) {
2957 arguments.push_back(&arg);
2958 }
2959
2960 unsigned arg_index = 0;
2961 for (auto *info : resource_var_at_index) {
2962 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00002963 auto arg = arguments[arg_index];
alan-bakerb6b09dc2018-11-08 16:59:28 -05002964 unsigned arg_size = 0;
Kévin PETITa353c832018-03-20 23:21:21 +00002965 if (info->arg_kind == clspv::ArgKind::Pod) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05002966 arg_size = static_cast<uint32_t>(DL.getTypeStoreSize(arg->getType()));
Kévin PETITa353c832018-03-20 23:21:21 +00002967 }
2968
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002969 // Local pointer arguments are unused in this case. Offset is always
2970 // zero.
alan-bakerf5e5f692018-11-27 08:33:24 -05002971 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2972 F.getName(), arg->getName(),
2973 arg_index, remap_arg_kind(clspv::GetArgKindName(info->arg_kind)),
2974 0, 0,
2975 0, arg_size};
2976 descriptorMapEntries->emplace_back(std::move(kernel_data),
2977 info->descriptor_set, info->binding);
David Neto862b7d82018-06-14 18:48:37 -04002978 }
2979 arg_index++;
2980 }
2981 // Generate mappings for pointer-to-local arguments.
2982 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
2983 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04002984 auto where = LocalArgSpecIds.find(arg);
2985 if (where != LocalArgSpecIds.end()) {
2986 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
alan-bakerf5e5f692018-11-27 08:33:24 -05002987 // Pod arguments members are unused in this case.
2988 version0::DescriptorMapEntry::KernelArgData kernel_data = {
2989 F.getName(),
2990 arg->getName(),
2991 arg_index,
2992 ArgKind::Local,
2993 static_cast<uint32_t>(local_arg_info.spec_id),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002994 static_cast<uint32_t>(
2995 GetTypeAllocSize(local_arg_info.elem_type, DL)),
alan-bakerf5e5f692018-11-27 08:33:24 -05002996 0,
2997 0};
2998 // Pointer-to-local arguments do not utilize descriptor set and binding.
2999 descriptorMapEntries->emplace_back(std::move(kernel_data), 0, 0);
David Neto862b7d82018-06-14 18:48:37 -04003000 }
3001 }
3002 }
3003}
3004
David Neto22f144c2017-06-12 14:26:21 -04003005void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
3006 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3007 ValueMapType &VMap = getValueMap();
3008 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003009 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3010 auto &GlobalConstArgSet = getGlobalConstArgSet();
3011
3012 FunctionType *FTy = F.getFunctionType();
3013
3014 //
David Neto22f144c2017-06-12 14:26:21 -04003015 // Generate OPFunction.
3016 //
3017
3018 // FOps[0] : Result Type ID
3019 // FOps[1] : Function Control
3020 // FOps[2] : Function Type ID
3021 SPIRVOperandList FOps;
3022
3023 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003024 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003025
3026 // Check function attributes for SPIRV Function Control.
3027 uint32_t FuncControl = spv::FunctionControlMaskNone;
3028 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3029 FuncControl |= spv::FunctionControlInlineMask;
3030 }
3031 if (F.hasFnAttribute(Attribute::NoInline)) {
3032 FuncControl |= spv::FunctionControlDontInlineMask;
3033 }
3034 // TODO: Check llvm attribute for Function Control Pure.
3035 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3036 FuncControl |= spv::FunctionControlPureMask;
3037 }
3038 // TODO: Check llvm attribute for Function Control Const.
3039 if (F.hasFnAttribute(Attribute::ReadNone)) {
3040 FuncControl |= spv::FunctionControlConstMask;
3041 }
3042
David Neto257c3892018-04-11 13:19:45 -04003043 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003044
3045 uint32_t FTyID;
3046 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3047 SmallVector<Type *, 4> NewFuncParamTys;
3048 FunctionType *NewFTy =
3049 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3050 FTyID = lookupType(NewFTy);
3051 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003052 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003053 if (GlobalConstFuncTyMap.count(FTy)) {
3054 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3055 } else {
3056 FTyID = lookupType(FTy);
3057 }
3058 }
3059
David Neto257c3892018-04-11 13:19:45 -04003060 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003061
3062 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3063 EntryPoints.push_back(std::make_pair(&F, nextID));
3064 }
3065
3066 VMap[&F] = nextID;
3067
David Neto482550a2018-03-24 05:21:07 -07003068 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003069 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3070 }
David Neto22f144c2017-06-12 14:26:21 -04003071 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003072 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003073 SPIRVInstList.push_back(FuncInst);
3074
3075 //
3076 // Generate OpFunctionParameter for Normal function.
3077 //
3078
3079 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
alan-bakere9308012019-03-15 10:25:13 -04003080
3081 // Find Insert Point for OpDecorate.
3082 auto DecoInsertPoint =
3083 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
3084 [](SPIRVInstruction *Inst) -> bool {
3085 return Inst->getOpcode() != spv::OpDecorate &&
3086 Inst->getOpcode() != spv::OpMemberDecorate &&
3087 Inst->getOpcode() != spv::OpExtInstImport;
3088 });
3089
David Neto22f144c2017-06-12 14:26:21 -04003090 // Iterate Argument for name instead of param type from function type.
3091 unsigned ArgIdx = 0;
3092 for (Argument &Arg : F.args()) {
alan-bakere9308012019-03-15 10:25:13 -04003093 uint32_t param_id = nextID++;
3094 VMap[&Arg] = param_id;
3095
3096 if (CalledWithCoherentResource(Arg)) {
3097 // If the arg is passed a coherent resource ever, then decorate this
3098 // parameter with Coherent too.
3099 SPIRVOperandList decoration_ops;
3100 decoration_ops << MkId(param_id) << MkNum(spv::DecorationCoherent);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003101 SPIRVInstList.insert(
3102 DecoInsertPoint,
3103 new SPIRVInstruction(spv::OpDecorate, decoration_ops));
alan-bakere9308012019-03-15 10:25:13 -04003104 }
David Neto22f144c2017-06-12 14:26:21 -04003105
3106 // ParamOps[0] : Result Type ID
3107 SPIRVOperandList ParamOps;
3108
3109 // Find SPIRV instruction for parameter type.
3110 uint32_t ParamTyID = lookupType(Arg.getType());
3111 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3112 if (GlobalConstFuncTyMap.count(FTy)) {
3113 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3114 Type *EleTy = PTy->getPointerElementType();
3115 Type *ArgTy =
3116 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3117 ParamTyID = lookupType(ArgTy);
3118 GlobalConstArgSet.insert(&Arg);
3119 }
3120 }
3121 }
David Neto257c3892018-04-11 13:19:45 -04003122 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003123
3124 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003125 auto *ParamInst =
alan-bakere9308012019-03-15 10:25:13 -04003126 new SPIRVInstruction(spv::OpFunctionParameter, param_id, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003127 SPIRVInstList.push_back(ParamInst);
3128
3129 ArgIdx++;
3130 }
3131 }
3132}
3133
alan-bakerb6b09dc2018-11-08 16:59:28 -05003134void SPIRVProducerPass::GenerateModuleInfo(Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04003135 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3136 EntryPointVecType &EntryPoints = getEntryPointVec();
3137 ValueMapType &VMap = getValueMap();
3138 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3139 uint32_t &ExtInstImportID = getOpExtInstImportID();
3140 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3141
3142 // Set up insert point.
3143 auto InsertPoint = SPIRVInstList.begin();
3144
3145 //
3146 // Generate OpCapability
3147 //
3148 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3149
3150 // Ops[0] = Capability
3151 SPIRVOperandList Ops;
3152
David Neto87846742018-04-11 17:36:22 -04003153 auto *CapInst =
3154 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003155 SPIRVInstList.insert(InsertPoint, CapInst);
3156
3157 for (Type *Ty : getTypeList()) {
alan-bakerb39c8262019-03-08 14:03:37 -05003158 if (clspv::Option::Int8Support() && Ty->isIntegerTy(8)) {
3159 // Generate OpCapability for i8 type.
3160 SPIRVInstList.insert(InsertPoint,
3161 new SPIRVInstruction(spv::OpCapability,
3162 {MkNum(spv::CapabilityInt8)}));
3163 } else if (Ty->isIntegerTy(16)) {
David Neto22f144c2017-06-12 14:26:21 -04003164 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003165 SPIRVInstList.insert(InsertPoint,
3166 new SPIRVInstruction(spv::OpCapability,
3167 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003168 } else if (Ty->isIntegerTy(64)) {
3169 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003170 SPIRVInstList.insert(InsertPoint,
3171 new SPIRVInstruction(spv::OpCapability,
3172 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003173 } else if (Ty->isHalfTy()) {
3174 // Generate OpCapability for half type.
3175 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003176 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3177 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003178 } else if (Ty->isDoubleTy()) {
3179 // Generate OpCapability for double type.
3180 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003181 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3182 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003183 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3184 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003185 if (STy->getName().equals("opencl.image2d_wo_t") ||
3186 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003187 // Generate OpCapability for write only image type.
3188 SPIRVInstList.insert(
3189 InsertPoint,
3190 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003191 spv::OpCapability,
3192 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003193 }
3194 }
3195 }
3196 }
3197
David Neto5c22a252018-03-15 16:07:41 -04003198 { // OpCapability ImageQuery
3199 bool hasImageQuery = false;
3200 for (const char *imageQuery : {
3201 "_Z15get_image_width14ocl_image2d_ro",
3202 "_Z15get_image_width14ocl_image2d_wo",
3203 "_Z16get_image_height14ocl_image2d_ro",
3204 "_Z16get_image_height14ocl_image2d_wo",
3205 }) {
3206 if (module.getFunction(imageQuery)) {
3207 hasImageQuery = true;
3208 break;
3209 }
3210 }
3211 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003212 auto *ImageQueryCapInst = new SPIRVInstruction(
3213 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003214 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3215 }
3216 }
3217
David Neto22f144c2017-06-12 14:26:21 -04003218 if (hasVariablePointers()) {
3219 //
David Neto22f144c2017-06-12 14:26:21 -04003220 // Generate OpCapability.
3221 //
3222 // Ops[0] = Capability
3223 //
3224 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003225 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003226
David Neto87846742018-04-11 17:36:22 -04003227 SPIRVInstList.insert(InsertPoint,
3228 new SPIRVInstruction(spv::OpCapability, Ops));
alan-baker5b86ed72019-02-15 08:26:50 -05003229 } else if (hasVariablePointersStorageBuffer()) {
3230 //
3231 // Generate OpCapability.
3232 //
3233 // Ops[0] = Capability
3234 //
3235 Ops.clear();
3236 Ops << MkNum(spv::CapabilityVariablePointersStorageBuffer);
David Neto22f144c2017-06-12 14:26:21 -04003237
alan-baker5b86ed72019-02-15 08:26:50 -05003238 SPIRVInstList.insert(InsertPoint,
3239 new SPIRVInstruction(spv::OpCapability, Ops));
3240 }
3241
3242 // Always add the storage buffer extension
3243 {
David Neto22f144c2017-06-12 14:26:21 -04003244 //
3245 // Generate OpExtension.
3246 //
3247 // Ops[0] = Name (Literal String)
3248 //
alan-baker5b86ed72019-02-15 08:26:50 -05003249 auto *ExtensionInst = new SPIRVInstruction(
3250 spv::OpExtension, {MkString("SPV_KHR_storage_buffer_storage_class")});
3251 SPIRVInstList.insert(InsertPoint, ExtensionInst);
3252 }
David Neto22f144c2017-06-12 14:26:21 -04003253
alan-baker5b86ed72019-02-15 08:26:50 -05003254 if (hasVariablePointers() || hasVariablePointersStorageBuffer()) {
3255 //
3256 // Generate OpExtension.
3257 //
3258 // Ops[0] = Name (Literal String)
3259 //
3260 auto *ExtensionInst = new SPIRVInstruction(
3261 spv::OpExtension, {MkString("SPV_KHR_variable_pointers")});
3262 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003263 }
3264
3265 if (ExtInstImportID) {
3266 ++InsertPoint;
3267 }
3268
3269 //
3270 // Generate OpMemoryModel
3271 //
3272 // Memory model for Vulkan will always be GLSL450.
3273
3274 // Ops[0] = Addressing Model
3275 // Ops[1] = Memory Model
3276 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003277 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003278
David Neto87846742018-04-11 17:36:22 -04003279 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003280 SPIRVInstList.insert(InsertPoint, MemModelInst);
3281
3282 //
3283 // Generate OpEntryPoint
3284 //
3285 for (auto EntryPoint : EntryPoints) {
3286 // Ops[0] = Execution Model
3287 // Ops[1] = EntryPoint ID
3288 // Ops[2] = Name (Literal String)
3289 // ...
3290 //
3291 // TODO: Do we need to consider Interface ID for forward references???
3292 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003293 const StringRef &name = EntryPoint.first->getName();
David Neto257c3892018-04-11 13:19:45 -04003294 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3295 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003296
David Neto22f144c2017-06-12 14:26:21 -04003297 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003298 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003299 }
3300
David Neto87846742018-04-11 17:36:22 -04003301 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003302 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3303 }
3304
3305 for (auto EntryPoint : EntryPoints) {
3306 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3307 ->getMetadata("reqd_work_group_size")) {
3308
3309 if (!BuiltinDimVec.empty()) {
3310 llvm_unreachable(
3311 "Kernels should have consistent work group size definition");
3312 }
3313
3314 //
3315 // Generate OpExecutionMode
3316 //
3317
3318 // Ops[0] = Entry Point ID
3319 // Ops[1] = Execution Mode
3320 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3321 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003322 Ops << MkId(EntryPoint.second) << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003323
3324 uint32_t XDim = static_cast<uint32_t>(
3325 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3326 uint32_t YDim = static_cast<uint32_t>(
3327 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3328 uint32_t ZDim = static_cast<uint32_t>(
3329 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3330
David Neto257c3892018-04-11 13:19:45 -04003331 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003332
David Neto87846742018-04-11 17:36:22 -04003333 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003334 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3335 }
3336 }
3337
3338 //
3339 // Generate OpSource.
3340 //
3341 // Ops[0] = SourceLanguage ID
3342 // Ops[1] = Version (LiteralNum)
3343 //
3344 Ops.clear();
Kévin Petit0fc88042019-04-09 23:25:02 +01003345 if (clspv::Option::CPlusPlus()) {
3346 Ops << MkNum(spv::SourceLanguageOpenCL_CPP) << MkNum(100);
3347 } else {
3348 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
3349 }
David Neto22f144c2017-06-12 14:26:21 -04003350
David Neto87846742018-04-11 17:36:22 -04003351 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003352 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3353
3354 if (!BuiltinDimVec.empty()) {
3355 //
3356 // Generate OpDecorates for x/y/z dimension.
3357 //
3358 // Ops[0] = Target ID
3359 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003360 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003361
3362 // X Dimension
3363 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003364 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003365 SPIRVInstList.insert(InsertPoint,
3366 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003367
3368 // Y Dimension
3369 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003370 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003371 SPIRVInstList.insert(InsertPoint,
3372 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003373
3374 // Z Dimension
3375 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003376 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003377 SPIRVInstList.insert(InsertPoint,
3378 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003379 }
3380}
3381
David Netob6e2e062018-04-25 10:32:06 -04003382void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3383 // Work around a driver bug. Initializers on Private variables might not
3384 // work. So the start of the kernel should store the initializer value to the
3385 // variables. Yes, *every* entry point pays this cost if *any* entry point
3386 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3387 // of complexity vs. runtime, for a broken driver.
alan-bakerb6b09dc2018-11-08 16:59:28 -05003388 // TODO(dneto): Remove this at some point once fixed drivers are widely
3389 // available.
David Netob6e2e062018-04-25 10:32:06 -04003390 if (WorkgroupSizeVarID) {
3391 assert(WorkgroupSizeValueID);
3392
3393 SPIRVOperandList Ops;
3394 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3395
3396 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3397 getSPIRVInstList().push_back(Inst);
3398 }
3399}
3400
David Neto22f144c2017-06-12 14:26:21 -04003401void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3402 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3403 ValueMapType &VMap = getValueMap();
3404
David Netob6e2e062018-04-25 10:32:06 -04003405 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003406
3407 for (BasicBlock &BB : F) {
3408 // Register BasicBlock to ValueMap.
3409 VMap[&BB] = nextID;
3410
3411 //
3412 // Generate OpLabel for Basic Block.
3413 //
3414 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003415 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003416 SPIRVInstList.push_back(Inst);
3417
David Neto6dcd4712017-06-23 11:06:47 -04003418 // OpVariable instructions must come first.
3419 for (Instruction &I : BB) {
alan-baker5b86ed72019-02-15 08:26:50 -05003420 if (auto *alloca = dyn_cast<AllocaInst>(&I)) {
3421 // Allocating a pointer requires variable pointers.
3422 if (alloca->getAllocatedType()->isPointerTy()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04003423 setVariablePointersCapabilities(
3424 alloca->getAllocatedType()->getPointerAddressSpace());
alan-baker5b86ed72019-02-15 08:26:50 -05003425 }
David Neto6dcd4712017-06-23 11:06:47 -04003426 GenerateInstruction(I);
3427 }
3428 }
3429
David Neto22f144c2017-06-12 14:26:21 -04003430 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003431 if (clspv::Option::HackInitializers()) {
3432 GenerateEntryPointInitialStores();
3433 }
David Neto22f144c2017-06-12 14:26:21 -04003434 }
3435
3436 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003437 if (!isa<AllocaInst>(I)) {
3438 GenerateInstruction(I);
3439 }
David Neto22f144c2017-06-12 14:26:21 -04003440 }
3441 }
3442}
3443
3444spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3445 const std::map<CmpInst::Predicate, spv::Op> Map = {
3446 {CmpInst::ICMP_EQ, spv::OpIEqual},
3447 {CmpInst::ICMP_NE, spv::OpINotEqual},
3448 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3449 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3450 {CmpInst::ICMP_ULT, spv::OpULessThan},
3451 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3452 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3453 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3454 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3455 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3456 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3457 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3458 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3459 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3460 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3461 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3462 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3463 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3464 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3465 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3466 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3467 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3468
3469 assert(0 != Map.count(I->getPredicate()));
3470
3471 return Map.at(I->getPredicate());
3472}
3473
3474spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3475 const std::map<unsigned, spv::Op> Map{
3476 {Instruction::Trunc, spv::OpUConvert},
3477 {Instruction::ZExt, spv::OpUConvert},
3478 {Instruction::SExt, spv::OpSConvert},
3479 {Instruction::FPToUI, spv::OpConvertFToU},
3480 {Instruction::FPToSI, spv::OpConvertFToS},
3481 {Instruction::UIToFP, spv::OpConvertUToF},
3482 {Instruction::SIToFP, spv::OpConvertSToF},
3483 {Instruction::FPTrunc, spv::OpFConvert},
3484 {Instruction::FPExt, spv::OpFConvert},
3485 {Instruction::BitCast, spv::OpBitcast}};
3486
3487 assert(0 != Map.count(I.getOpcode()));
3488
3489 return Map.at(I.getOpcode());
3490}
3491
3492spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003493 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003494 switch (I.getOpcode()) {
3495 default:
3496 break;
3497 case Instruction::Or:
3498 return spv::OpLogicalOr;
3499 case Instruction::And:
3500 return spv::OpLogicalAnd;
3501 case Instruction::Xor:
3502 return spv::OpLogicalNotEqual;
3503 }
3504 }
3505
alan-bakerb6b09dc2018-11-08 16:59:28 -05003506 const std::map<unsigned, spv::Op> Map{
David Neto22f144c2017-06-12 14:26:21 -04003507 {Instruction::Add, spv::OpIAdd},
3508 {Instruction::FAdd, spv::OpFAdd},
3509 {Instruction::Sub, spv::OpISub},
3510 {Instruction::FSub, spv::OpFSub},
3511 {Instruction::Mul, spv::OpIMul},
3512 {Instruction::FMul, spv::OpFMul},
3513 {Instruction::UDiv, spv::OpUDiv},
3514 {Instruction::SDiv, spv::OpSDiv},
3515 {Instruction::FDiv, spv::OpFDiv},
3516 {Instruction::URem, spv::OpUMod},
3517 {Instruction::SRem, spv::OpSRem},
3518 {Instruction::FRem, spv::OpFRem},
3519 {Instruction::Or, spv::OpBitwiseOr},
3520 {Instruction::Xor, spv::OpBitwiseXor},
3521 {Instruction::And, spv::OpBitwiseAnd},
3522 {Instruction::Shl, spv::OpShiftLeftLogical},
3523 {Instruction::LShr, spv::OpShiftRightLogical},
3524 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3525
3526 assert(0 != Map.count(I.getOpcode()));
3527
3528 return Map.at(I.getOpcode());
3529}
3530
3531void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3532 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3533 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003534 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3535 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3536
3537 // Register Instruction to ValueMap.
3538 if (0 == VMap[&I]) {
3539 VMap[&I] = nextID;
3540 }
3541
3542 switch (I.getOpcode()) {
3543 default: {
3544 if (Instruction::isCast(I.getOpcode())) {
3545 //
3546 // Generate SPIRV instructions for cast operators.
3547 //
3548
David Netod2de94a2017-08-28 17:27:47 -04003549 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003550 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003551 auto toI8 = Ty == Type::getInt8Ty(Context);
3552 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003553 // Handle zext, sext and uitofp with i1 type specially.
3554 if ((I.getOpcode() == Instruction::ZExt ||
3555 I.getOpcode() == Instruction::SExt ||
3556 I.getOpcode() == Instruction::UIToFP) &&
alan-bakerb6b09dc2018-11-08 16:59:28 -05003557 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003558 //
3559 // Generate OpSelect.
3560 //
3561
3562 // Ops[0] = Result Type ID
3563 // Ops[1] = Condition ID
3564 // Ops[2] = True Constant ID
3565 // Ops[3] = False Constant ID
3566 SPIRVOperandList Ops;
3567
David Neto257c3892018-04-11 13:19:45 -04003568 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003569
David Neto22f144c2017-06-12 14:26:21 -04003570 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003571 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003572
3573 uint32_t TrueID = 0;
3574 if (I.getOpcode() == Instruction::ZExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003575 TrueID = VMap[ConstantInt::get(I.getType(), 1)];
David Neto22f144c2017-06-12 14:26:21 -04003576 } else if (I.getOpcode() == Instruction::SExt) {
Kévin Petit7bfb8992019-02-26 13:45:08 +00003577 TrueID = VMap[ConstantInt::getSigned(I.getType(), -1)];
David Neto22f144c2017-06-12 14:26:21 -04003578 } else {
3579 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3580 }
David Neto257c3892018-04-11 13:19:45 -04003581 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003582
3583 uint32_t FalseID = 0;
3584 if (I.getOpcode() == Instruction::ZExt) {
3585 FalseID = VMap[Constant::getNullValue(I.getType())];
3586 } else if (I.getOpcode() == Instruction::SExt) {
3587 FalseID = VMap[Constant::getNullValue(I.getType())];
3588 } else {
3589 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3590 }
David Neto257c3892018-04-11 13:19:45 -04003591 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003592
David Neto87846742018-04-11 17:36:22 -04003593 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003594 SPIRVInstList.push_back(Inst);
alan-bakerb39c8262019-03-08 14:03:37 -05003595 } else if (!clspv::Option::Int8Support() &&
3596 I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
David Netod2de94a2017-08-28 17:27:47 -04003597 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3598 // 8 bits.
3599 // Before:
3600 // %result = trunc i32 %a to i8
3601 // After
3602 // %result = OpBitwiseAnd %uint %a %uint_255
3603
3604 SPIRVOperandList Ops;
3605
David Neto257c3892018-04-11 13:19:45 -04003606 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003607
3608 Type *UintTy = Type::getInt32Ty(Context);
3609 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003610 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003611
David Neto87846742018-04-11 17:36:22 -04003612 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003613 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003614 } else {
3615 // Ops[0] = Result Type ID
3616 // Ops[1] = Source Value ID
3617 SPIRVOperandList Ops;
3618
David Neto257c3892018-04-11 13:19:45 -04003619 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003620
David Neto87846742018-04-11 17:36:22 -04003621 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003622 SPIRVInstList.push_back(Inst);
3623 }
3624 } else if (isa<BinaryOperator>(I)) {
3625 //
3626 // Generate SPIRV instructions for binary operators.
3627 //
3628
3629 // Handle xor with i1 type specially.
3630 if (I.getOpcode() == Instruction::Xor &&
3631 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003632 ((isa<ConstantInt>(I.getOperand(0)) &&
3633 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3634 (isa<ConstantInt>(I.getOperand(1)) &&
3635 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003636 //
3637 // Generate OpLogicalNot.
3638 //
3639 // Ops[0] = Result Type ID
3640 // Ops[1] = Operand
3641 SPIRVOperandList Ops;
3642
David Neto257c3892018-04-11 13:19:45 -04003643 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003644
3645 Value *CondV = I.getOperand(0);
3646 if (isa<Constant>(I.getOperand(0))) {
3647 CondV = I.getOperand(1);
3648 }
David Neto257c3892018-04-11 13:19:45 -04003649 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003650
David Neto87846742018-04-11 17:36:22 -04003651 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003652 SPIRVInstList.push_back(Inst);
3653 } else {
3654 // Ops[0] = Result Type ID
3655 // Ops[1] = Operand 0
3656 // Ops[2] = Operand 1
3657 SPIRVOperandList Ops;
3658
David Neto257c3892018-04-11 13:19:45 -04003659 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3660 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003661
David Neto87846742018-04-11 17:36:22 -04003662 auto *Inst =
3663 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003664 SPIRVInstList.push_back(Inst);
3665 }
3666 } else {
3667 I.print(errs());
3668 llvm_unreachable("Unsupported instruction???");
3669 }
3670 break;
3671 }
3672 case Instruction::GetElementPtr: {
3673 auto &GlobalConstArgSet = getGlobalConstArgSet();
3674
3675 //
3676 // Generate OpAccessChain.
3677 //
3678 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3679
3680 //
3681 // Generate OpAccessChain.
3682 //
3683
3684 // Ops[0] = Result Type ID
3685 // Ops[1] = Base ID
3686 // Ops[2] ... Ops[n] = Indexes ID
3687 SPIRVOperandList Ops;
3688
alan-bakerb6b09dc2018-11-08 16:59:28 -05003689 PointerType *ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003690 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3691 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3692 // Use pointer type with private address space for global constant.
3693 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003694 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003695 }
David Neto257c3892018-04-11 13:19:45 -04003696
3697 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003698
David Neto862b7d82018-06-14 18:48:37 -04003699 // Generate the base pointer.
3700 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003701
David Neto862b7d82018-06-14 18:48:37 -04003702 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003703
3704 //
3705 // Follows below rules for gep.
3706 //
David Neto862b7d82018-06-14 18:48:37 -04003707 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3708 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003709 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3710 // first index.
3711 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3712 // use gep's first index.
3713 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3714 // gep's first index.
3715 //
3716 spv::Op Opcode = spv::OpAccessChain;
3717 unsigned offset = 0;
3718 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003719 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003720 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003721 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003722 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003723 }
David Neto862b7d82018-06-14 18:48:37 -04003724 } else {
David Neto22f144c2017-06-12 14:26:21 -04003725 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003726 }
3727
3728 if (Opcode == spv::OpPtrAccessChain) {
David Neto1a1a0582017-07-07 12:01:44 -04003729 // Do we need to generate ArrayStride? Check against the GEP result type
3730 // rather than the pointer type of the base because when indexing into
3731 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3732 // for something else in the SPIR-V.
3733 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
alan-baker5b86ed72019-02-15 08:26:50 -05003734 auto address_space = ResultType->getAddressSpace();
3735 setVariablePointersCapabilities(address_space);
3736 switch (GetStorageClass(address_space)) {
Alan Bakerfcda9482018-10-02 17:09:59 -04003737 case spv::StorageClassStorageBuffer:
3738 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003739 // Save the need to generate an ArrayStride decoration. But defer
3740 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003741 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003742 break;
3743 default:
3744 break;
David Neto1a1a0582017-07-07 12:01:44 -04003745 }
David Neto22f144c2017-06-12 14:26:21 -04003746 }
3747
3748 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003749 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003750 }
3751
David Neto87846742018-04-11 17:36:22 -04003752 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003753 SPIRVInstList.push_back(Inst);
3754 break;
3755 }
3756 case Instruction::ExtractValue: {
3757 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3758 // Ops[0] = Result Type ID
3759 // Ops[1] = Composite ID
3760 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3761 SPIRVOperandList Ops;
3762
David Neto257c3892018-04-11 13:19:45 -04003763 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003764
3765 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003767
3768 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003769 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003770 }
3771
David Neto87846742018-04-11 17:36:22 -04003772 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003773 SPIRVInstList.push_back(Inst);
3774 break;
3775 }
3776 case Instruction::InsertValue: {
3777 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3778 // Ops[0] = Result Type ID
3779 // Ops[1] = Object ID
3780 // Ops[2] = Composite ID
3781 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3782 SPIRVOperandList Ops;
3783
3784 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003785 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003786
3787 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003788 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003789
3790 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003791 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003792
3793 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003794 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003795 }
3796
David Neto87846742018-04-11 17:36:22 -04003797 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003798 SPIRVInstList.push_back(Inst);
3799 break;
3800 }
3801 case Instruction::Select: {
3802 //
3803 // Generate OpSelect.
3804 //
3805
3806 // Ops[0] = Result Type ID
3807 // Ops[1] = Condition ID
3808 // Ops[2] = True Constant ID
3809 // Ops[3] = False Constant ID
3810 SPIRVOperandList Ops;
3811
3812 // Find SPIRV instruction for parameter type.
3813 auto Ty = I.getType();
3814 if (Ty->isPointerTy()) {
3815 auto PointeeTy = Ty->getPointerElementType();
3816 if (PointeeTy->isStructTy() &&
3817 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3818 Ty = PointeeTy;
alan-baker5b86ed72019-02-15 08:26:50 -05003819 } else {
3820 // Selecting between pointers requires variable pointers.
3821 setVariablePointersCapabilities(Ty->getPointerAddressSpace());
3822 if (!hasVariablePointers() && !selectFromSameObject(&I)) {
3823 setVariablePointers(true);
3824 }
David Neto22f144c2017-06-12 14:26:21 -04003825 }
3826 }
3827
David Neto257c3892018-04-11 13:19:45 -04003828 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3829 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003830
David Neto87846742018-04-11 17:36:22 -04003831 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003832 SPIRVInstList.push_back(Inst);
3833 break;
3834 }
3835 case Instruction::ExtractElement: {
3836 // Handle <4 x i8> type manually.
3837 Type *CompositeTy = I.getOperand(0)->getType();
3838 if (is4xi8vec(CompositeTy)) {
3839 //
3840 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3841 // <4 x i8>.
3842 //
3843
3844 //
3845 // Generate OpShiftRightLogical
3846 //
3847 // Ops[0] = Result Type ID
3848 // Ops[1] = Operand 0
3849 // Ops[2] = Operand 1
3850 //
3851 SPIRVOperandList Ops;
3852
David Neto257c3892018-04-11 13:19:45 -04003853 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003854
3855 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003856 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003857
3858 uint32_t Op1ID = 0;
3859 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3860 // Handle constant index.
3861 uint64_t Idx = CI->getZExtValue();
3862 Value *ShiftAmount =
3863 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3864 Op1ID = VMap[ShiftAmount];
3865 } else {
3866 // Handle variable index.
3867 SPIRVOperandList TmpOps;
3868
David Neto257c3892018-04-11 13:19:45 -04003869 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3870 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003871
3872 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003873 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003874
3875 Op1ID = nextID;
3876
David Neto87846742018-04-11 17:36:22 -04003877 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003878 SPIRVInstList.push_back(TmpInst);
3879 }
David Neto257c3892018-04-11 13:19:45 -04003880 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003881
3882 uint32_t ShiftID = nextID;
3883
David Neto87846742018-04-11 17:36:22 -04003884 auto *Inst =
3885 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003886 SPIRVInstList.push_back(Inst);
3887
3888 //
3889 // Generate OpBitwiseAnd
3890 //
3891 // Ops[0] = Result Type ID
3892 // Ops[1] = Operand 0
3893 // Ops[2] = Operand 1
3894 //
3895 Ops.clear();
3896
David Neto257c3892018-04-11 13:19:45 -04003897 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003898
3899 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003900 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003901
David Neto9b2d6252017-09-06 15:47:37 -04003902 // Reset mapping for this value to the result of the bitwise and.
3903 VMap[&I] = nextID;
3904
David Neto87846742018-04-11 17:36:22 -04003905 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003906 SPIRVInstList.push_back(Inst);
3907 break;
3908 }
3909
3910 // Ops[0] = Result Type ID
3911 // Ops[1] = Composite ID
3912 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3913 SPIRVOperandList Ops;
3914
David Neto257c3892018-04-11 13:19:45 -04003915 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003916
3917 spv::Op Opcode = spv::OpCompositeExtract;
3918 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003919 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003920 } else {
David Neto257c3892018-04-11 13:19:45 -04003921 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003922 Opcode = spv::OpVectorExtractDynamic;
3923 }
3924
David Neto87846742018-04-11 17:36:22 -04003925 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003926 SPIRVInstList.push_back(Inst);
3927 break;
3928 }
3929 case Instruction::InsertElement: {
3930 // Handle <4 x i8> type manually.
3931 Type *CompositeTy = I.getOperand(0)->getType();
3932 if (is4xi8vec(CompositeTy)) {
3933 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3934 uint32_t CstFFID = VMap[CstFF];
3935
3936 uint32_t ShiftAmountID = 0;
3937 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3938 // Handle constant index.
3939 uint64_t Idx = CI->getZExtValue();
3940 Value *ShiftAmount =
3941 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3942 ShiftAmountID = VMap[ShiftAmount];
3943 } else {
3944 // Handle variable index.
3945 SPIRVOperandList TmpOps;
3946
David Neto257c3892018-04-11 13:19:45 -04003947 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3948 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003949
3950 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003951 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003952
3953 ShiftAmountID = nextID;
3954
David Neto87846742018-04-11 17:36:22 -04003955 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003956 SPIRVInstList.push_back(TmpInst);
3957 }
3958
3959 //
3960 // Generate mask operations.
3961 //
3962
3963 // ShiftLeft mask according to index of insertelement.
3964 SPIRVOperandList Ops;
3965
David Neto257c3892018-04-11 13:19:45 -04003966 const uint32_t ResTyID = lookupType(CompositeTy);
3967 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003968
3969 uint32_t MaskID = nextID;
3970
David Neto87846742018-04-11 17:36:22 -04003971 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003972 SPIRVInstList.push_back(Inst);
3973
3974 // Inverse mask.
3975 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003976 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003977
3978 uint32_t InvMaskID = nextID;
3979
David Neto87846742018-04-11 17:36:22 -04003980 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003981 SPIRVInstList.push_back(Inst);
3982
3983 // Apply mask.
3984 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003985 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003986
3987 uint32_t OrgValID = nextID;
3988
David Neto87846742018-04-11 17:36:22 -04003989 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003990 SPIRVInstList.push_back(Inst);
3991
3992 // Create correct value according to index of insertelement.
3993 Ops.clear();
alan-bakerb6b09dc2018-11-08 16:59:28 -05003994 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)])
3995 << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003996
3997 uint32_t InsertValID = nextID;
3998
David Neto87846742018-04-11 17:36:22 -04003999 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004000 SPIRVInstList.push_back(Inst);
4001
4002 // Insert value to original value.
4003 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004004 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004005
David Netoa394f392017-08-26 20:45:29 -04004006 VMap[&I] = nextID;
4007
David Neto87846742018-04-11 17:36:22 -04004008 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004009 SPIRVInstList.push_back(Inst);
4010
4011 break;
4012 }
4013
David Neto22f144c2017-06-12 14:26:21 -04004014 SPIRVOperandList Ops;
4015
James Priced26efea2018-06-09 23:28:32 +01004016 // Ops[0] = Result Type ID
4017 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004018
4019 spv::Op Opcode = spv::OpCompositeInsert;
4020 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004021 const auto value = CI->getZExtValue();
4022 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004023 // Ops[1] = Object ID
4024 // Ops[2] = Composite ID
4025 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004026 Ops << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(0)])
James Priced26efea2018-06-09 23:28:32 +01004027 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004028 } else {
James Priced26efea2018-06-09 23:28:32 +01004029 // Ops[1] = Composite ID
4030 // Ops[2] = Object ID
4031 // Ops[3] ... Ops[n] = Indexes (Literal Number)
alan-bakerb6b09dc2018-11-08 16:59:28 -05004032 Ops << MkId(VMap[I.getOperand(0)]) << MkId(VMap[I.getOperand(1)])
James Priced26efea2018-06-09 23:28:32 +01004033 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004034 Opcode = spv::OpVectorInsertDynamic;
4035 }
4036
David Neto87846742018-04-11 17:36:22 -04004037 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004038 SPIRVInstList.push_back(Inst);
4039 break;
4040 }
4041 case Instruction::ShuffleVector: {
4042 // Ops[0] = Result Type ID
4043 // Ops[1] = Vector 1 ID
4044 // Ops[2] = Vector 2 ID
4045 // Ops[3] ... Ops[n] = Components (Literal Number)
4046 SPIRVOperandList Ops;
4047
David Neto257c3892018-04-11 13:19:45 -04004048 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4049 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004050
4051 uint64_t NumElements = 0;
4052 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4053 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4054
4055 if (Cst->isNullValue()) {
4056 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004057 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004058 }
4059 } else if (const ConstantDataSequential *CDS =
4060 dyn_cast<ConstantDataSequential>(Cst)) {
4061 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4062 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004063 const auto value = CDS->getElementAsInteger(i);
4064 assert(value <= UINT32_MAX);
4065 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004066 }
4067 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4068 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4069 auto Op = CV->getOperand(i);
4070
4071 uint32_t literal = 0;
4072
4073 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4074 literal = static_cast<uint32_t>(CI->getZExtValue());
4075 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4076 literal = 0xFFFFFFFFu;
4077 } else {
4078 Op->print(errs());
4079 llvm_unreachable("Unsupported element in ConstantVector!");
4080 }
4081
David Neto257c3892018-04-11 13:19:45 -04004082 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004083 }
4084 } else {
4085 Cst->print(errs());
4086 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4087 }
4088 }
4089
David Neto87846742018-04-11 17:36:22 -04004090 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004091 SPIRVInstList.push_back(Inst);
4092 break;
4093 }
4094 case Instruction::ICmp:
4095 case Instruction::FCmp: {
4096 CmpInst *CmpI = cast<CmpInst>(&I);
4097
David Netod4ca2e62017-07-06 18:47:35 -04004098 // Pointer equality is invalid.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004099 Type *ArgTy = CmpI->getOperand(0)->getType();
David Netod4ca2e62017-07-06 18:47:35 -04004100 if (isa<PointerType>(ArgTy)) {
4101 CmpI->print(errs());
4102 std::string name = I.getParent()->getParent()->getName();
4103 errs()
4104 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4105 << "in function " << name << "\n";
4106 llvm_unreachable("Pointer equality check is invalid");
4107 break;
4108 }
4109
David Neto257c3892018-04-11 13:19:45 -04004110 // Ops[0] = Result Type ID
4111 // Ops[1] = Operand 1 ID
4112 // Ops[2] = Operand 2 ID
4113 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004114
David Neto257c3892018-04-11 13:19:45 -04004115 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4116 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004117
4118 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004119 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004120 SPIRVInstList.push_back(Inst);
4121 break;
4122 }
4123 case Instruction::Br: {
4124 // Branch instrucion is deferred because it needs label's ID. Record slot's
4125 // location on SPIRVInstructionList.
4126 DeferredInsts.push_back(
4127 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4128 break;
4129 }
4130 case Instruction::Switch: {
4131 I.print(errs());
4132 llvm_unreachable("Unsupported instruction???");
4133 break;
4134 }
4135 case Instruction::IndirectBr: {
4136 I.print(errs());
4137 llvm_unreachable("Unsupported instruction???");
4138 break;
4139 }
4140 case Instruction::PHI: {
4141 // Branch instrucion is deferred because it needs label's ID. Record slot's
4142 // location on SPIRVInstructionList.
4143 DeferredInsts.push_back(
4144 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4145 break;
4146 }
4147 case Instruction::Alloca: {
4148 //
4149 // Generate OpVariable.
4150 //
4151 // Ops[0] : Result Type ID
4152 // Ops[1] : Storage Class
4153 SPIRVOperandList Ops;
4154
David Neto257c3892018-04-11 13:19:45 -04004155 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004156
David Neto87846742018-04-11 17:36:22 -04004157 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004158 SPIRVInstList.push_back(Inst);
4159 break;
4160 }
4161 case Instruction::Load: {
4162 LoadInst *LD = cast<LoadInst>(&I);
4163 //
4164 // Generate OpLoad.
4165 //
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04004166
alan-baker5b86ed72019-02-15 08:26:50 -05004167 if (LD->getType()->isPointerTy()) {
4168 // Loading a pointer requires variable pointers.
4169 setVariablePointersCapabilities(LD->getType()->getPointerAddressSpace());
4170 }
David Neto22f144c2017-06-12 14:26:21 -04004171
David Neto0a2f98d2017-09-15 19:38:40 -04004172 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004173 uint32_t PointerID = VMap[LD->getPointerOperand()];
4174
4175 // This is a hack to work around what looks like a driver bug.
4176 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004177 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4178 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004179 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004180 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004181 // Generate a bitwise-and of the original value with itself.
4182 // We should have been able to get away with just an OpCopyObject,
4183 // but we need something more complex to get past certain driver bugs.
4184 // This is ridiculous, but necessary.
4185 // TODO(dneto): Revisit this once drivers fix their bugs.
4186
4187 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004188 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4189 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004190
David Neto87846742018-04-11 17:36:22 -04004191 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004192 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004193 break;
4194 }
4195
4196 // This is the normal path. Generate a load.
4197
David Neto22f144c2017-06-12 14:26:21 -04004198 // Ops[0] = Result Type ID
4199 // Ops[1] = Pointer ID
4200 // Ops[2] ... Ops[n] = Optional Memory Access
4201 //
4202 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004203
David Neto22f144c2017-06-12 14:26:21 -04004204 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004205 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004206
David Neto87846742018-04-11 17:36:22 -04004207 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004208 SPIRVInstList.push_back(Inst);
4209 break;
4210 }
4211 case Instruction::Store: {
4212 StoreInst *ST = cast<StoreInst>(&I);
4213 //
4214 // Generate OpStore.
4215 //
4216
alan-baker5b86ed72019-02-15 08:26:50 -05004217 if (ST->getValueOperand()->getType()->isPointerTy()) {
4218 // Storing a pointer requires variable pointers.
4219 setVariablePointersCapabilities(
4220 ST->getValueOperand()->getType()->getPointerAddressSpace());
4221 }
4222
David Neto22f144c2017-06-12 14:26:21 -04004223 // Ops[0] = Pointer ID
4224 // Ops[1] = Object ID
4225 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4226 //
4227 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004228 SPIRVOperandList Ops;
4229 Ops << MkId(VMap[ST->getPointerOperand()])
4230 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004231
David Neto87846742018-04-11 17:36:22 -04004232 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004233 SPIRVInstList.push_back(Inst);
4234 break;
4235 }
4236 case Instruction::AtomicCmpXchg: {
4237 I.print(errs());
4238 llvm_unreachable("Unsupported instruction???");
4239 break;
4240 }
4241 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004242 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4243
4244 spv::Op opcode;
4245
4246 switch (AtomicRMW->getOperation()) {
4247 default:
4248 I.print(errs());
4249 llvm_unreachable("Unsupported instruction???");
4250 case llvm::AtomicRMWInst::Add:
4251 opcode = spv::OpAtomicIAdd;
4252 break;
4253 case llvm::AtomicRMWInst::Sub:
4254 opcode = spv::OpAtomicISub;
4255 break;
4256 case llvm::AtomicRMWInst::Xchg:
4257 opcode = spv::OpAtomicExchange;
4258 break;
4259 case llvm::AtomicRMWInst::Min:
4260 opcode = spv::OpAtomicSMin;
4261 break;
4262 case llvm::AtomicRMWInst::Max:
4263 opcode = spv::OpAtomicSMax;
4264 break;
4265 case llvm::AtomicRMWInst::UMin:
4266 opcode = spv::OpAtomicUMin;
4267 break;
4268 case llvm::AtomicRMWInst::UMax:
4269 opcode = spv::OpAtomicUMax;
4270 break;
4271 case llvm::AtomicRMWInst::And:
4272 opcode = spv::OpAtomicAnd;
4273 break;
4274 case llvm::AtomicRMWInst::Or:
4275 opcode = spv::OpAtomicOr;
4276 break;
4277 case llvm::AtomicRMWInst::Xor:
4278 opcode = spv::OpAtomicXor;
4279 break;
4280 }
4281
4282 //
4283 // Generate OpAtomic*.
4284 //
4285 SPIRVOperandList Ops;
4286
David Neto257c3892018-04-11 13:19:45 -04004287 Ops << MkId(lookupType(I.getType()))
4288 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004289
4290 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004291 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004292 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004293
4294 const auto ConstantMemorySemantics = ConstantInt::get(
4295 IntTy, spv::MemorySemanticsUniformMemoryMask |
4296 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004297 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004298
David Neto257c3892018-04-11 13:19:45 -04004299 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004300
4301 VMap[&I] = nextID;
4302
David Neto87846742018-04-11 17:36:22 -04004303 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004304 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004305 break;
4306 }
4307 case Instruction::Fence: {
4308 I.print(errs());
4309 llvm_unreachable("Unsupported instruction???");
4310 break;
4311 }
4312 case Instruction::Call: {
4313 CallInst *Call = dyn_cast<CallInst>(&I);
4314 Function *Callee = Call->getCalledFunction();
4315
Alan Baker202c8c72018-08-13 13:47:44 -04004316 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004317 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4318 // Generate an OpLoad
4319 SPIRVOperandList Ops;
4320 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004321
David Neto862b7d82018-06-14 18:48:37 -04004322 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4323 << MkId(ResourceVarDeferredLoadCalls[Call]);
4324
4325 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4326 SPIRVInstList.push_back(Inst);
4327 VMap[Call] = load_id;
4328 break;
4329
4330 } else {
4331 // This maps to an OpVariable we've already generated.
4332 // No code is generated for the call.
4333 }
4334 break;
alan-bakerb6b09dc2018-11-08 16:59:28 -05004335 } else if (Callee->getName().startswith(
4336 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -04004337 // Don't codegen an instruction here, but instead map this call directly
4338 // to the workgroup variable id.
alan-bakerb6b09dc2018-11-08 16:59:28 -05004339 int spec_id = static_cast<int>(
4340 cast<ConstantInt>(Call->getOperand(0))->getSExtValue());
Alan Baker202c8c72018-08-13 13:47:44 -04004341 const auto &info = LocalSpecIdInfoMap[spec_id];
4342 VMap[Call] = info.variable_id;
4343 break;
David Neto862b7d82018-06-14 18:48:37 -04004344 }
4345
4346 // Sampler initializers become a load of the corresponding sampler.
4347
Kévin Petitdf71de32019-04-09 14:09:50 +01004348 if (Callee->getName().equals(clspv::LiteralSamplerFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004349 // Map this to a load from the variable.
4350 const auto index_into_sampler_map =
4351 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4352
4353 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004354 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004355 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004356
David Neto257c3892018-04-11 13:19:45 -04004357 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
alan-bakerb6b09dc2018-11-08 16:59:28 -05004358 << MkId(SamplerMapIndexToIDMap[static_cast<unsigned>(
4359 index_into_sampler_map)]);
David Neto22f144c2017-06-12 14:26:21 -04004360
David Neto862b7d82018-06-14 18:48:37 -04004361 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004362 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004363 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004364 break;
4365 }
4366
Kévin Petit349c9502019-03-28 17:24:14 +00004367 // Handle SPIR-V intrinsics
Kévin Petit9b340262019-06-19 18:31:11 +01004368 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4369 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4370 .Default(spv::OpNop);
David Neto22f144c2017-06-12 14:26:21 -04004371
Kévin Petit617a76d2019-04-04 13:54:16 +01004372 // If the switch above didn't have an entry maybe the intrinsic
4373 // is using the name mangling logic.
4374 bool usesMangler = false;
4375 if (opcode == spv::OpNop) {
4376 if (Callee->getName().startswith(clspv::SPIRVOpIntrinsicFunction())) {
4377 auto OpCst = cast<ConstantInt>(Call->getOperand(0));
4378 opcode = static_cast<spv::Op>(OpCst->getZExtValue());
4379 usesMangler = true;
4380 }
4381 }
4382
Kévin Petit349c9502019-03-28 17:24:14 +00004383 if (opcode != spv::OpNop) {
4384
David Neto22f144c2017-06-12 14:26:21 -04004385 SPIRVOperandList Ops;
4386
Kévin Petit349c9502019-03-28 17:24:14 +00004387 if (!I.getType()->isVoidTy()) {
4388 Ops << MkId(lookupType(I.getType()));
4389 }
David Neto22f144c2017-06-12 14:26:21 -04004390
Kévin Petit617a76d2019-04-04 13:54:16 +01004391 unsigned firstOperand = usesMangler ? 1 : 0;
4392 for (unsigned i = firstOperand; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004393 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004394 }
4395
Kévin Petit349c9502019-03-28 17:24:14 +00004396 if (!I.getType()->isVoidTy()) {
4397 VMap[&I] = nextID;
Kévin Petit8a560882019-03-21 15:24:34 +00004398 }
4399
Kévin Petit349c9502019-03-28 17:24:14 +00004400 SPIRVInstruction *Inst;
4401 if (!I.getType()->isVoidTy()) {
4402 Inst = new SPIRVInstruction(opcode, nextID++, Ops);
4403 } else {
4404 Inst = new SPIRVInstruction(opcode, Ops);
4405 }
Kévin Petit8a560882019-03-21 15:24:34 +00004406 SPIRVInstList.push_back(Inst);
4407 break;
4408 }
4409
David Neto22f144c2017-06-12 14:26:21 -04004410 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4411 if (Callee->getName().startswith("spirv.copy_memory")) {
4412 //
4413 // Generate OpCopyMemory.
4414 //
4415
4416 // Ops[0] = Dst ID
4417 // Ops[1] = Src ID
4418 // Ops[2] = Memory Access
4419 // Ops[3] = Alignment
4420
4421 auto IsVolatile =
4422 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4423
4424 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4425 : spv::MemoryAccessMaskNone;
4426
4427 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4428
4429 auto Alignment =
4430 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4431
David Neto257c3892018-04-11 13:19:45 -04004432 SPIRVOperandList Ops;
4433 Ops << MkId(VMap[Call->getArgOperand(0)])
4434 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4435 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004436
David Neto87846742018-04-11 17:36:22 -04004437 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004438
4439 SPIRVInstList.push_back(Inst);
4440
4441 break;
4442 }
4443
David Neto22f144c2017-06-12 14:26:21 -04004444 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4445 // Additionally, OpTypeSampledImage is generated.
4446 if (Callee->getName().equals(
4447 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4448 Callee->getName().equals(
4449 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4450 //
4451 // Generate OpSampledImage.
4452 //
4453 // Ops[0] = Result Type ID
4454 // Ops[1] = Image ID
4455 // Ops[2] = Sampler ID
4456 //
4457 SPIRVOperandList Ops;
4458
4459 Value *Image = Call->getArgOperand(0);
4460 Value *Sampler = Call->getArgOperand(1);
4461 Value *Coordinate = Call->getArgOperand(2);
4462
4463 TypeMapType &OpImageTypeMap = getImageTypeMap();
4464 Type *ImageTy = Image->getType()->getPointerElementType();
4465 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004466 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004467 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004468
4469 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004470
4471 uint32_t SampledImageID = nextID;
4472
David Neto87846742018-04-11 17:36:22 -04004473 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004474 SPIRVInstList.push_back(Inst);
4475
4476 //
4477 // Generate OpImageSampleExplicitLod.
4478 //
4479 // Ops[0] = Result Type ID
4480 // Ops[1] = Sampled Image ID
4481 // Ops[2] = Coordinate ID
4482 // Ops[3] = Image Operands Type ID
4483 // Ops[4] ... Ops[n] = Operands ID
4484 //
4485 Ops.clear();
4486
David Neto257c3892018-04-11 13:19:45 -04004487 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4488 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004489
4490 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004491 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004492
4493 VMap[&I] = nextID;
4494
David Neto87846742018-04-11 17:36:22 -04004495 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004496 SPIRVInstList.push_back(Inst);
4497 break;
4498 }
4499
4500 // write_imagef is mapped to OpImageWrite.
4501 if (Callee->getName().equals(
4502 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4503 Callee->getName().equals(
4504 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4505 //
4506 // Generate OpImageWrite.
4507 //
4508 // Ops[0] = Image ID
4509 // Ops[1] = Coordinate ID
4510 // Ops[2] = Texel ID
4511 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4512 // Ops[4] ... Ops[n] = (Optional) Operands ID
4513 //
4514 SPIRVOperandList Ops;
4515
4516 Value *Image = Call->getArgOperand(0);
4517 Value *Coordinate = Call->getArgOperand(1);
4518 Value *Texel = Call->getArgOperand(2);
4519
4520 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004521 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004522 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004523 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004524
David Neto87846742018-04-11 17:36:22 -04004525 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004526 SPIRVInstList.push_back(Inst);
4527 break;
4528 }
4529
David Neto5c22a252018-03-15 16:07:41 -04004530 // get_image_width is mapped to OpImageQuerySize
4531 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4532 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4533 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4534 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4535 //
4536 // Generate OpImageQuerySize, then pull out the right component.
4537 // Assume 2D image for now.
4538 //
4539 // Ops[0] = Image ID
4540 //
4541 // %sizes = OpImageQuerySizes %uint2 %im
4542 // %result = OpCompositeExtract %uint %sizes 0-or-1
4543 SPIRVOperandList Ops;
4544
4545 // Implement:
4546 // %sizes = OpImageQuerySizes %uint2 %im
4547 uint32_t SizesTypeID =
4548 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004549 Value *Image = Call->getArgOperand(0);
4550 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004551 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004552
4553 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004554 auto *QueryInst =
4555 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004556 SPIRVInstList.push_back(QueryInst);
4557
4558 // Reset value map entry since we generated an intermediate instruction.
4559 VMap[&I] = nextID;
4560
4561 // Implement:
4562 // %result = OpCompositeExtract %uint %sizes 0-or-1
4563 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004564 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004565
4566 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004567 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004568
David Neto87846742018-04-11 17:36:22 -04004569 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004570 SPIRVInstList.push_back(Inst);
4571 break;
4572 }
4573
David Neto22f144c2017-06-12 14:26:21 -04004574 // Call instrucion is deferred because it needs function's ID. Record
4575 // slot's location on SPIRVInstructionList.
4576 DeferredInsts.push_back(
4577 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4578
David Neto3fbb4072017-10-16 11:28:14 -04004579 // Check whether the implementation of this call uses an extended
4580 // instruction plus one more value-producing instruction. If so, then
4581 // reserve the id for the extra value-producing slot.
4582 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4583 if (EInst != kGlslExtInstBad) {
4584 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004585 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004586 VMap[&I] = nextID;
4587 nextID++;
4588 }
4589 break;
4590 }
4591 case Instruction::Ret: {
4592 unsigned NumOps = I.getNumOperands();
4593 if (NumOps == 0) {
4594 //
4595 // Generate OpReturn.
4596 //
David Neto87846742018-04-11 17:36:22 -04004597 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004598 } else {
4599 //
4600 // Generate OpReturnValue.
4601 //
4602
4603 // Ops[0] = Return Value ID
4604 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004605
4606 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004607
David Neto87846742018-04-11 17:36:22 -04004608 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004609 SPIRVInstList.push_back(Inst);
4610 break;
4611 }
4612 break;
4613 }
4614 }
4615}
4616
4617void SPIRVProducerPass::GenerateFuncEpilogue() {
4618 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4619
4620 //
4621 // Generate OpFunctionEnd
4622 //
4623
David Neto87846742018-04-11 17:36:22 -04004624 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004625 SPIRVInstList.push_back(Inst);
4626}
4627
4628bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
alan-bakerb39c8262019-03-08 14:03:37 -05004629 // Don't specialize <4 x i8> if i8 is generally supported.
4630 if (clspv::Option::Int8Support())
4631 return false;
4632
David Neto22f144c2017-06-12 14:26:21 -04004633 LLVMContext &Context = Ty->getContext();
4634 if (Ty->isVectorTy()) {
4635 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4636 Ty->getVectorNumElements() == 4) {
4637 return true;
4638 }
4639 }
4640
4641 return false;
4642}
4643
4644void SPIRVProducerPass::HandleDeferredInstruction() {
4645 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4646 ValueMapType &VMap = getValueMap();
4647 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4648
4649 for (auto DeferredInst = DeferredInsts.rbegin();
4650 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4651 Value *Inst = std::get<0>(*DeferredInst);
4652 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4653 if (InsertPoint != SPIRVInstList.end()) {
4654 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4655 ++InsertPoint;
4656 }
4657 }
4658
4659 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4660 // Check whether basic block, which has this branch instruction, is loop
4661 // header or not. If it is loop header, generate OpLoopMerge and
4662 // OpBranchConditional.
4663 Function *Func = Br->getParent()->getParent();
4664 DominatorTree &DT =
4665 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4666 const LoopInfo &LI =
4667 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4668
4669 BasicBlock *BrBB = Br->getParent();
alan-baker49531082019-06-05 17:30:56 -04004670 Loop *L = LI.getLoopFor(BrBB);
David Neto22f144c2017-06-12 14:26:21 -04004671 if (LI.isLoopHeader(BrBB)) {
4672 Value *ContinueBB = nullptr;
4673 Value *MergeBB = nullptr;
4674
David Neto22f144c2017-06-12 14:26:21 -04004675 MergeBB = L->getExitBlock();
4676 if (!MergeBB) {
4677 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4678 // has regions with single entry/exit. As a result, loop should not
4679 // have multiple exits.
4680 llvm_unreachable("Loop has multiple exits???");
4681 }
4682
4683 if (L->isLoopLatch(BrBB)) {
4684 ContinueBB = BrBB;
4685 } else {
4686 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4687 // block.
4688 BasicBlock *Header = L->getHeader();
4689 BasicBlock *Latch = L->getLoopLatch();
4690 for (BasicBlock *BB : L->blocks()) {
4691 if (BB == Header) {
4692 continue;
4693 }
4694
4695 // Check whether block dominates block with back-edge.
4696 if (DT.dominates(BB, Latch)) {
4697 ContinueBB = BB;
4698 }
4699 }
4700
4701 if (!ContinueBB) {
4702 llvm_unreachable("Wrong continue block from loop");
4703 }
4704 }
4705
4706 //
4707 // Generate OpLoopMerge.
4708 //
4709 // Ops[0] = Merge Block ID
4710 // Ops[1] = Continue Target ID
4711 // Ops[2] = Selection Control
4712 SPIRVOperandList Ops;
4713
4714 // StructurizeCFG pass already manipulated CFG. Just use false block of
4715 // branch instruction as merge block.
4716 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004717 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004718 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4719 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004720
David Neto87846742018-04-11 17:36:22 -04004721 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004722 SPIRVInstList.insert(InsertPoint, MergeInst);
4723
4724 } else if (Br->isConditional()) {
alan-baker49531082019-06-05 17:30:56 -04004725 // Generate a selection merge unless this is a back-edge block.
4726 bool HasBackedge = false;
4727 while (L && !HasBackedge) {
4728 if (L->isLoopLatch(BrBB)) {
4729 HasBackedge = true;
David Neto22f144c2017-06-12 14:26:21 -04004730 }
alan-baker49531082019-06-05 17:30:56 -04004731 L = L->getParentLoop();
David Neto22f144c2017-06-12 14:26:21 -04004732 }
alan-baker49531082019-06-05 17:30:56 -04004733 if (!HasBackedge) {
David Neto22f144c2017-06-12 14:26:21 -04004734 //
4735 // Generate OpSelectionMerge.
4736 //
4737 // Ops[0] = Merge Block ID
4738 // Ops[1] = Selection Control
4739 SPIRVOperandList Ops;
4740
4741 // StructurizeCFG pass already manipulated CFG. Just use false block
4742 // of branch instruction as merge block.
4743 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004744 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004745
David Neto87846742018-04-11 17:36:22 -04004746 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004747 SPIRVInstList.insert(InsertPoint, MergeInst);
4748 }
4749 }
4750
4751 if (Br->isConditional()) {
4752 //
4753 // Generate OpBranchConditional.
4754 //
4755 // Ops[0] = Condition ID
4756 // Ops[1] = True Label ID
4757 // Ops[2] = False Label ID
4758 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4759 SPIRVOperandList Ops;
4760
4761 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004762 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004763 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004764
4765 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004766
David Neto87846742018-04-11 17:36:22 -04004767 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004768 SPIRVInstList.insert(InsertPoint, BrInst);
4769 } else {
4770 //
4771 // Generate OpBranch.
4772 //
4773 // Ops[0] = Target Label ID
4774 SPIRVOperandList Ops;
4775
4776 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004777 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004778
David Neto87846742018-04-11 17:36:22 -04004779 SPIRVInstList.insert(InsertPoint,
4780 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004781 }
4782 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
alan-baker5b86ed72019-02-15 08:26:50 -05004783 if (PHI->getType()->isPointerTy()) {
4784 // OpPhi on pointers requires variable pointers.
4785 setVariablePointersCapabilities(
4786 PHI->getType()->getPointerAddressSpace());
4787 if (!hasVariablePointers() && !selectFromSameObject(PHI)) {
4788 setVariablePointers(true);
4789 }
4790 }
4791
David Neto22f144c2017-06-12 14:26:21 -04004792 //
4793 // Generate OpPhi.
4794 //
4795 // Ops[0] = Result Type ID
4796 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4797 SPIRVOperandList Ops;
4798
David Neto257c3892018-04-11 13:19:45 -04004799 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004800
David Neto22f144c2017-06-12 14:26:21 -04004801 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4802 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004803 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004804 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004805 }
4806
4807 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004808 InsertPoint,
4809 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004810 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4811 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004812 auto callee_name = Callee->getName();
4813 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004814
4815 if (EInst) {
4816 uint32_t &ExtInstImportID = getOpExtInstImportID();
4817
4818 //
4819 // Generate OpExtInst.
4820 //
4821
4822 // Ops[0] = Result Type ID
4823 // Ops[1] = Set ID (OpExtInstImport ID)
4824 // Ops[2] = Instruction Number (Literal Number)
4825 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4826 SPIRVOperandList Ops;
4827
David Neto862b7d82018-06-14 18:48:37 -04004828 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
4829 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04004830
David Neto22f144c2017-06-12 14:26:21 -04004831 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4832 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004833 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004834 }
4835
David Neto87846742018-04-11 17:36:22 -04004836 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
4837 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004838 SPIRVInstList.insert(InsertPoint, ExtInst);
4839
David Neto3fbb4072017-10-16 11:28:14 -04004840 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
4841 if (IndirectExtInst != kGlslExtInstBad) {
4842 // Generate one more instruction that uses the result of the extended
4843 // instruction. Its result id is one more than the id of the
4844 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04004845 LLVMContext &Context =
4846 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04004847
David Neto3fbb4072017-10-16 11:28:14 -04004848 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
4849 &VMap, &SPIRVInstList, &InsertPoint](
4850 spv::Op opcode, Constant *constant) {
4851 //
4852 // Generate instruction like:
4853 // result = opcode constant <extinst-result>
4854 //
4855 // Ops[0] = Result Type ID
4856 // Ops[1] = Operand 0 ;; the constant, suitably splatted
4857 // Ops[2] = Operand 1 ;; the result of the extended instruction
4858 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004859
David Neto3fbb4072017-10-16 11:28:14 -04004860 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04004861 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04004862
4863 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
4864 constant = ConstantVector::getSplat(
4865 static_cast<unsigned>(vectorTy->getNumElements()), constant);
4866 }
David Neto257c3892018-04-11 13:19:45 -04004867 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04004868
4869 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004870 InsertPoint, new SPIRVInstruction(
4871 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04004872 };
4873
4874 switch (IndirectExtInst) {
4875 case glsl::ExtInstFindUMsb: // Implementing clz
4876 generate_extra_inst(
4877 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
4878 break;
4879 case glsl::ExtInstAcos: // Implementing acospi
4880 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01004881 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04004882 case glsl::ExtInstAtan2: // Implementing atan2pi
4883 generate_extra_inst(
4884 spv::OpFMul,
4885 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
4886 break;
4887
4888 default:
4889 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04004890 }
David Neto22f144c2017-06-12 14:26:21 -04004891 }
David Neto3fbb4072017-10-16 11:28:14 -04004892
alan-bakerb39c8262019-03-08 14:03:37 -05004893 } else if (callee_name.startswith("_Z8popcount")) {
David Neto22f144c2017-06-12 14:26:21 -04004894 //
4895 // Generate OpBitCount
4896 //
4897 // Ops[0] = Result Type ID
4898 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04004899 SPIRVOperandList Ops;
4900 Ops << MkId(lookupType(Call->getType()))
4901 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004902
4903 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004904 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04004905 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004906
David Neto862b7d82018-06-14 18:48:37 -04004907 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04004908
4909 // Generate an OpCompositeConstruct
4910 SPIRVOperandList Ops;
4911
4912 // The result type.
David Neto257c3892018-04-11 13:19:45 -04004913 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04004914
4915 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04004916 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04004917 }
4918
4919 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004920 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
4921 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04004922
Alan Baker202c8c72018-08-13 13:47:44 -04004923 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
4924
4925 // We have already mapped the call's result value to an ID.
4926 // Don't generate any code now.
4927
4928 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004929
4930 // We have already mapped the call's result value to an ID.
4931 // Don't generate any code now.
4932
David Neto22f144c2017-06-12 14:26:21 -04004933 } else {
alan-baker5b86ed72019-02-15 08:26:50 -05004934 if (Call->getType()->isPointerTy()) {
4935 // Functions returning pointers require variable pointers.
4936 setVariablePointersCapabilities(
4937 Call->getType()->getPointerAddressSpace());
4938 }
4939
David Neto22f144c2017-06-12 14:26:21 -04004940 //
4941 // Generate OpFunctionCall.
4942 //
4943
4944 // Ops[0] = Result Type ID
4945 // Ops[1] = Callee Function ID
4946 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
4947 SPIRVOperandList Ops;
4948
David Neto862b7d82018-06-14 18:48:37 -04004949 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004950
4951 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04004952 if (CalleeID == 0) {
4953 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04004954 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04004955 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
4956 // causes an infinite loop. Instead, go ahead and generate
4957 // the bad function call. A validator will catch the 0-Id.
4958 // llvm_unreachable("Can't translate function call");
4959 }
David Neto22f144c2017-06-12 14:26:21 -04004960
David Neto257c3892018-04-11 13:19:45 -04004961 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04004962
David Neto22f144c2017-06-12 14:26:21 -04004963 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
4964 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
alan-baker5b86ed72019-02-15 08:26:50 -05004965 auto *operand = Call->getOperand(i);
4966 if (operand->getType()->isPointerTy()) {
4967 auto sc =
4968 GetStorageClass(operand->getType()->getPointerAddressSpace());
4969 if (sc == spv::StorageClassStorageBuffer) {
4970 // Passing SSBO by reference requires variable pointers storage
4971 // buffer.
4972 setVariablePointersStorageBuffer(true);
4973 } else if (sc == spv::StorageClassWorkgroup) {
4974 // Workgroup references require variable pointers if they are not
4975 // memory object declarations.
4976 if (auto *operand_call = dyn_cast<CallInst>(operand)) {
4977 // Workgroup accessor represents a variable reference.
4978 if (!operand_call->getCalledFunction()->getName().startswith(
4979 clspv::WorkgroupAccessorFunction()))
4980 setVariablePointers(true);
4981 } else {
4982 // Arguments are function parameters.
4983 if (!isa<Argument>(operand))
4984 setVariablePointers(true);
4985 }
4986 }
4987 }
4988 Ops << MkId(VMap[operand]);
David Neto22f144c2017-06-12 14:26:21 -04004989 }
4990
David Neto87846742018-04-11 17:36:22 -04004991 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
4992 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04004993 SPIRVInstList.insert(InsertPoint, CallInst);
4994 }
4995 }
4996 }
4997}
4998
David Neto1a1a0582017-07-07 12:01:44 -04004999void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005000 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005001 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005002 }
David Neto1a1a0582017-07-07 12:01:44 -04005003
5004 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005005
5006 // Find an iterator pointing just past the last decoration.
5007 bool seen_decorations = false;
5008 auto DecoInsertPoint =
5009 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5010 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5011 const bool is_decoration =
5012 Inst->getOpcode() == spv::OpDecorate ||
5013 Inst->getOpcode() == spv::OpMemberDecorate;
5014 if (is_decoration) {
5015 seen_decorations = true;
5016 return false;
5017 } else {
5018 return seen_decorations;
5019 }
5020 });
5021
David Netoc6f3ab22018-04-06 18:02:31 -04005022 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5023 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005024 for (auto *type : getTypesNeedingArrayStride()) {
5025 Type *elemTy = nullptr;
5026 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5027 elemTy = ptrTy->getElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005028 } else if (auto *arrayTy = dyn_cast<ArrayType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005029 elemTy = arrayTy->getArrayElementType();
alan-bakerb6b09dc2018-11-08 16:59:28 -05005030 } else if (auto *seqTy = dyn_cast<SequentialType>(type)) {
David Neto85082642018-03-24 06:55:20 -07005031 elemTy = seqTy->getSequentialElementType();
5032 } else {
5033 errs() << "Unhandled strided type " << *type << "\n";
5034 llvm_unreachable("Unhandled strided type");
5035 }
David Neto1a1a0582017-07-07 12:01:44 -04005036
5037 // Ops[0] = Target ID
5038 // Ops[1] = Decoration (ArrayStride)
5039 // Ops[2] = Stride number (Literal Number)
5040 SPIRVOperandList Ops;
5041
David Neto85082642018-03-24 06:55:20 -07005042 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005043 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005044
5045 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5046 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005047
David Neto87846742018-04-11 17:36:22 -04005048 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005049 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5050 }
David Netoc6f3ab22018-04-06 18:02:31 -04005051
5052 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005053 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5054 ++spec_id) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005055 LocalArgInfo &arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005056 SPIRVOperandList Ops;
5057 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5058 << MkNum(arg_info.spec_id);
5059 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005060 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005061 }
David Neto1a1a0582017-07-07 12:01:44 -04005062}
5063
David Neto22f144c2017-06-12 14:26:21 -04005064glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5065 return StringSwitch<glsl::ExtInst>(Name)
alan-bakerb39c8262019-03-08 14:03:37 -05005066 .Case("_Z3absc", glsl::ExtInst::ExtInstSAbs)
5067 .Case("_Z3absDv2_c", glsl::ExtInst::ExtInstSAbs)
5068 .Case("_Z3absDv3_c", glsl::ExtInst::ExtInstSAbs)
5069 .Case("_Z3absDv4_c", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005070 .Case("_Z3abss", glsl::ExtInst::ExtInstSAbs)
5071 .Case("_Z3absDv2_s", glsl::ExtInst::ExtInstSAbs)
5072 .Case("_Z3absDv3_s", glsl::ExtInst::ExtInstSAbs)
5073 .Case("_Z3absDv4_s", glsl::ExtInst::ExtInstSAbs)
David Neto22f144c2017-06-12 14:26:21 -04005074 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5075 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5076 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5077 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
Kévin Petit2444e9b2018-11-09 14:14:37 +00005078 .Case("_Z3absl", glsl::ExtInst::ExtInstSAbs)
5079 .Case("_Z3absDv2_l", glsl::ExtInst::ExtInstSAbs)
5080 .Case("_Z3absDv3_l", glsl::ExtInst::ExtInstSAbs)
5081 .Case("_Z3absDv4_l", glsl::ExtInst::ExtInstSAbs)
alan-bakerb39c8262019-03-08 14:03:37 -05005082 .Case("_Z5clampccc", glsl::ExtInst::ExtInstSClamp)
5083 .Case("_Z5clampDv2_cS_S_", glsl::ExtInst::ExtInstSClamp)
5084 .Case("_Z5clampDv3_cS_S_", glsl::ExtInst::ExtInstSClamp)
5085 .Case("_Z5clampDv4_cS_S_", glsl::ExtInst::ExtInstSClamp)
5086 .Case("_Z5clamphhh", glsl::ExtInst::ExtInstUClamp)
5087 .Case("_Z5clampDv2_hS_S_", glsl::ExtInst::ExtInstUClamp)
5088 .Case("_Z5clampDv3_hS_S_", glsl::ExtInst::ExtInstUClamp)
5089 .Case("_Z5clampDv4_hS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005090 .Case("_Z5clampsss", glsl::ExtInst::ExtInstSClamp)
5091 .Case("_Z5clampDv2_sS_S_", glsl::ExtInst::ExtInstSClamp)
5092 .Case("_Z5clampDv3_sS_S_", glsl::ExtInst::ExtInstSClamp)
5093 .Case("_Z5clampDv4_sS_S_", glsl::ExtInst::ExtInstSClamp)
5094 .Case("_Z5clampttt", glsl::ExtInst::ExtInstUClamp)
5095 .Case("_Z5clampDv2_tS_S_", glsl::ExtInst::ExtInstUClamp)
5096 .Case("_Z5clampDv3_tS_S_", glsl::ExtInst::ExtInstUClamp)
5097 .Case("_Z5clampDv4_tS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005098 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5099 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5100 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5101 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5102 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5103 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5104 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5105 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
Kévin Petit495255d2019-03-06 13:56:48 +00005106 .Case("_Z5clamplll", glsl::ExtInst::ExtInstSClamp)
5107 .Case("_Z5clampDv2_lS_S_", glsl::ExtInst::ExtInstSClamp)
5108 .Case("_Z5clampDv3_lS_S_", glsl::ExtInst::ExtInstSClamp)
5109 .Case("_Z5clampDv4_lS_S_", glsl::ExtInst::ExtInstSClamp)
5110 .Case("_Z5clampmmm", glsl::ExtInst::ExtInstUClamp)
5111 .Case("_Z5clampDv2_mS_S_", glsl::ExtInst::ExtInstUClamp)
5112 .Case("_Z5clampDv3_mS_S_", glsl::ExtInst::ExtInstUClamp)
5113 .Case("_Z5clampDv4_mS_S_", glsl::ExtInst::ExtInstUClamp)
David Neto22f144c2017-06-12 14:26:21 -04005114 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5115 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5116 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5117 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
alan-bakerb39c8262019-03-08 14:03:37 -05005118 .Case("_Z3maxcc", glsl::ExtInst::ExtInstSMax)
5119 .Case("_Z3maxDv2_cS_", glsl::ExtInst::ExtInstSMax)
5120 .Case("_Z3maxDv3_cS_", glsl::ExtInst::ExtInstSMax)
5121 .Case("_Z3maxDv4_cS_", glsl::ExtInst::ExtInstSMax)
5122 .Case("_Z3maxhh", glsl::ExtInst::ExtInstUMax)
5123 .Case("_Z3maxDv2_hS_", glsl::ExtInst::ExtInstUMax)
5124 .Case("_Z3maxDv3_hS_", glsl::ExtInst::ExtInstUMax)
5125 .Case("_Z3maxDv4_hS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005126 .Case("_Z3maxss", glsl::ExtInst::ExtInstSMax)
5127 .Case("_Z3maxDv2_sS_", glsl::ExtInst::ExtInstSMax)
5128 .Case("_Z3maxDv3_sS_", glsl::ExtInst::ExtInstSMax)
5129 .Case("_Z3maxDv4_sS_", glsl::ExtInst::ExtInstSMax)
5130 .Case("_Z3maxtt", glsl::ExtInst::ExtInstUMax)
5131 .Case("_Z3maxDv2_tS_", glsl::ExtInst::ExtInstUMax)
5132 .Case("_Z3maxDv3_tS_", glsl::ExtInst::ExtInstUMax)
5133 .Case("_Z3maxDv4_tS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005134 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5135 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5136 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5137 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5138 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5139 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5140 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5141 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005142 .Case("_Z3maxll", glsl::ExtInst::ExtInstSMax)
5143 .Case("_Z3maxDv2_lS_", glsl::ExtInst::ExtInstSMax)
5144 .Case("_Z3maxDv3_lS_", glsl::ExtInst::ExtInstSMax)
5145 .Case("_Z3maxDv4_lS_", glsl::ExtInst::ExtInstSMax)
5146 .Case("_Z3maxmm", glsl::ExtInst::ExtInstUMax)
5147 .Case("_Z3maxDv2_mS_", glsl::ExtInst::ExtInstUMax)
5148 .Case("_Z3maxDv3_mS_", glsl::ExtInst::ExtInstUMax)
5149 .Case("_Z3maxDv4_mS_", glsl::ExtInst::ExtInstUMax)
David Neto22f144c2017-06-12 14:26:21 -04005150 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5151 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5152 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5153 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5154 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
alan-bakerb39c8262019-03-08 14:03:37 -05005155 .Case("_Z3mincc", glsl::ExtInst::ExtInstSMin)
5156 .Case("_Z3minDv2_cS_", glsl::ExtInst::ExtInstSMin)
5157 .Case("_Z3minDv3_cS_", glsl::ExtInst::ExtInstSMin)
5158 .Case("_Z3minDv4_cS_", glsl::ExtInst::ExtInstSMin)
5159 .Case("_Z3minhh", glsl::ExtInst::ExtInstUMin)
5160 .Case("_Z3minDv2_hS_", glsl::ExtInst::ExtInstUMin)
5161 .Case("_Z3minDv3_hS_", glsl::ExtInst::ExtInstUMin)
5162 .Case("_Z3minDv4_hS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005163 .Case("_Z3minss", glsl::ExtInst::ExtInstSMin)
5164 .Case("_Z3minDv2_sS_", glsl::ExtInst::ExtInstSMin)
5165 .Case("_Z3minDv3_sS_", glsl::ExtInst::ExtInstSMin)
5166 .Case("_Z3minDv4_sS_", glsl::ExtInst::ExtInstSMin)
5167 .Case("_Z3mintt", glsl::ExtInst::ExtInstUMin)
5168 .Case("_Z3minDv2_tS_", glsl::ExtInst::ExtInstUMin)
5169 .Case("_Z3minDv3_tS_", glsl::ExtInst::ExtInstUMin)
5170 .Case("_Z3minDv4_tS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005171 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5172 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5173 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5174 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5175 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5176 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5177 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5178 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
Kévin Petit9e1971c2018-11-09 14:17:18 +00005179 .Case("_Z3minll", glsl::ExtInst::ExtInstSMin)
5180 .Case("_Z3minDv2_lS_", glsl::ExtInst::ExtInstSMin)
5181 .Case("_Z3minDv3_lS_", glsl::ExtInst::ExtInstSMin)
5182 .Case("_Z3minDv4_lS_", glsl::ExtInst::ExtInstSMin)
5183 .Case("_Z3minmm", glsl::ExtInst::ExtInstUMin)
5184 .Case("_Z3minDv2_mS_", glsl::ExtInst::ExtInstUMin)
5185 .Case("_Z3minDv3_mS_", glsl::ExtInst::ExtInstUMin)
5186 .Case("_Z3minDv4_mS_", glsl::ExtInst::ExtInstUMin)
David Neto22f144c2017-06-12 14:26:21 -04005187 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5188 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5189 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5190 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5191 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5192 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5193 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5194 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5195 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5196 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5197 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5198 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5199 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5200 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5201 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5202 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5203 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5204 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5205 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5206 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5207 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5208 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5209 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5210 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5211 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5212 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5213 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5214 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5215 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5216 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5217 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5218 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5219 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5220 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5221 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5222 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5223 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5224 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5225 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5226 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5227 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005228 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005229 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5230 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5231 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5232 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5233 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5234 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5235 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5236 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5237 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5238 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5239 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5240 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5241 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5242 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5243 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5244 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5245 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005246 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005247 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005248 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005249 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005250 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005251 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5252 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005253 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005254 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5255 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5256 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005257 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5258 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5259 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5260 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005261 .Default(kGlslExtInstBad);
5262}
5263
5264glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5265 // Check indirect cases.
5266 return StringSwitch<glsl::ExtInst>(Name)
5267 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5268 // Use exact match on float arg because these need a multiply
5269 // of a constant of the right floating point type.
5270 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5271 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5272 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5273 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5274 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5275 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5276 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5277 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005278 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5279 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5280 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5281 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005282 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5283 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5284 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5285 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5286 .Default(kGlslExtInstBad);
5287}
5288
alan-bakerb6b09dc2018-11-08 16:59:28 -05005289glsl::ExtInst
5290SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
David Neto3fbb4072017-10-16 11:28:14 -04005291 auto direct = getExtInstEnum(Name);
5292 if (direct != kGlslExtInstBad)
5293 return direct;
5294 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005295}
5296
David Neto22f144c2017-06-12 14:26:21 -04005297void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005298 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005299}
5300
5301void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5302 WriteOneWord(Inst->getResultID());
5303}
5304
5305void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5306 // High 16 bit : Word Count
5307 // Low 16 bit : Opcode
5308 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005309 const uint32_t count = Inst->getWordCount();
5310 if (count > 65535) {
5311 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5312 llvm_unreachable("Word count too high");
5313 }
David Neto22f144c2017-06-12 14:26:21 -04005314 Word |= Inst->getWordCount() << 16;
5315 WriteOneWord(Word);
5316}
5317
5318void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5319 SPIRVOperandType OpTy = Op->getType();
5320 switch (OpTy) {
5321 default: {
5322 llvm_unreachable("Unsupported SPIRV Operand Type???");
5323 break;
5324 }
5325 case SPIRVOperandType::NUMBERID: {
5326 WriteOneWord(Op->getNumID());
5327 break;
5328 }
5329 case SPIRVOperandType::LITERAL_STRING: {
5330 std::string Str = Op->getLiteralStr();
5331 const char *Data = Str.c_str();
5332 size_t WordSize = Str.size() / 4;
5333 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5334 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5335 }
5336
5337 uint32_t Remainder = Str.size() % 4;
5338 uint32_t LastWord = 0;
5339 if (Remainder) {
5340 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5341 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5342 }
5343 }
5344
5345 WriteOneWord(LastWord);
5346 break;
5347 }
5348 case SPIRVOperandType::LITERAL_INTEGER:
5349 case SPIRVOperandType::LITERAL_FLOAT: {
5350 auto LiteralNum = Op->getLiteralNum();
5351 // TODO: Handle LiteranNum carefully.
5352 for (auto Word : LiteralNum) {
5353 WriteOneWord(Word);
5354 }
5355 break;
5356 }
5357 }
5358}
5359
5360void SPIRVProducerPass::WriteSPIRVBinary() {
5361 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5362
5363 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005364 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005365 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5366
5367 switch (Opcode) {
5368 default: {
David Neto5c22a252018-03-15 16:07:41 -04005369 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005370 llvm_unreachable("Unsupported SPIRV instruction");
5371 break;
5372 }
5373 case spv::OpCapability:
5374 case spv::OpExtension:
5375 case spv::OpMemoryModel:
5376 case spv::OpEntryPoint:
5377 case spv::OpExecutionMode:
5378 case spv::OpSource:
5379 case spv::OpDecorate:
5380 case spv::OpMemberDecorate:
5381 case spv::OpBranch:
5382 case spv::OpBranchConditional:
5383 case spv::OpSelectionMerge:
5384 case spv::OpLoopMerge:
5385 case spv::OpStore:
5386 case spv::OpImageWrite:
5387 case spv::OpReturnValue:
5388 case spv::OpControlBarrier:
5389 case spv::OpMemoryBarrier:
5390 case spv::OpReturn:
5391 case spv::OpFunctionEnd:
5392 case spv::OpCopyMemory: {
5393 WriteWordCountAndOpcode(Inst);
5394 for (uint32_t i = 0; i < Ops.size(); i++) {
5395 WriteOperand(Ops[i]);
5396 }
5397 break;
5398 }
5399 case spv::OpTypeBool:
5400 case spv::OpTypeVoid:
5401 case spv::OpTypeSampler:
5402 case spv::OpLabel:
5403 case spv::OpExtInstImport:
5404 case spv::OpTypePointer:
5405 case spv::OpTypeRuntimeArray:
5406 case spv::OpTypeStruct:
5407 case spv::OpTypeImage:
5408 case spv::OpTypeSampledImage:
5409 case spv::OpTypeInt:
5410 case spv::OpTypeFloat:
5411 case spv::OpTypeArray:
5412 case spv::OpTypeVector:
5413 case spv::OpTypeFunction: {
5414 WriteWordCountAndOpcode(Inst);
5415 WriteResultID(Inst);
5416 for (uint32_t i = 0; i < Ops.size(); i++) {
5417 WriteOperand(Ops[i]);
5418 }
5419 break;
5420 }
5421 case spv::OpFunction:
5422 case spv::OpFunctionParameter:
5423 case spv::OpAccessChain:
5424 case spv::OpPtrAccessChain:
5425 case spv::OpInBoundsAccessChain:
5426 case spv::OpUConvert:
5427 case spv::OpSConvert:
5428 case spv::OpConvertFToU:
5429 case spv::OpConvertFToS:
5430 case spv::OpConvertUToF:
5431 case spv::OpConvertSToF:
5432 case spv::OpFConvert:
5433 case spv::OpConvertPtrToU:
5434 case spv::OpConvertUToPtr:
5435 case spv::OpBitcast:
5436 case spv::OpIAdd:
5437 case spv::OpFAdd:
5438 case spv::OpISub:
5439 case spv::OpFSub:
5440 case spv::OpIMul:
5441 case spv::OpFMul:
5442 case spv::OpUDiv:
5443 case spv::OpSDiv:
5444 case spv::OpFDiv:
5445 case spv::OpUMod:
5446 case spv::OpSRem:
5447 case spv::OpFRem:
Kévin Petit8a560882019-03-21 15:24:34 +00005448 case spv::OpUMulExtended:
5449 case spv::OpSMulExtended:
David Neto22f144c2017-06-12 14:26:21 -04005450 case spv::OpBitwiseOr:
5451 case spv::OpBitwiseXor:
5452 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005453 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005454 case spv::OpShiftLeftLogical:
5455 case spv::OpShiftRightLogical:
5456 case spv::OpShiftRightArithmetic:
5457 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005458 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005459 case spv::OpCompositeExtract:
5460 case spv::OpVectorExtractDynamic:
5461 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005462 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005463 case spv::OpVectorInsertDynamic:
5464 case spv::OpVectorShuffle:
5465 case spv::OpIEqual:
5466 case spv::OpINotEqual:
5467 case spv::OpUGreaterThan:
5468 case spv::OpUGreaterThanEqual:
5469 case spv::OpULessThan:
5470 case spv::OpULessThanEqual:
5471 case spv::OpSGreaterThan:
5472 case spv::OpSGreaterThanEqual:
5473 case spv::OpSLessThan:
5474 case spv::OpSLessThanEqual:
5475 case spv::OpFOrdEqual:
5476 case spv::OpFOrdGreaterThan:
5477 case spv::OpFOrdGreaterThanEqual:
5478 case spv::OpFOrdLessThan:
5479 case spv::OpFOrdLessThanEqual:
5480 case spv::OpFOrdNotEqual:
5481 case spv::OpFUnordEqual:
5482 case spv::OpFUnordGreaterThan:
5483 case spv::OpFUnordGreaterThanEqual:
5484 case spv::OpFUnordLessThan:
5485 case spv::OpFUnordLessThanEqual:
5486 case spv::OpFUnordNotEqual:
5487 case spv::OpExtInst:
5488 case spv::OpIsInf:
5489 case spv::OpIsNan:
5490 case spv::OpAny:
5491 case spv::OpAll:
5492 case spv::OpUndef:
5493 case spv::OpConstantNull:
5494 case spv::OpLogicalOr:
5495 case spv::OpLogicalAnd:
5496 case spv::OpLogicalNot:
5497 case spv::OpLogicalNotEqual:
5498 case spv::OpConstantComposite:
5499 case spv::OpSpecConstantComposite:
5500 case spv::OpConstantTrue:
5501 case spv::OpConstantFalse:
5502 case spv::OpConstant:
5503 case spv::OpSpecConstant:
5504 case spv::OpVariable:
5505 case spv::OpFunctionCall:
5506 case spv::OpSampledImage:
5507 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04005508 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005509 case spv::OpSelect:
5510 case spv::OpPhi:
5511 case spv::OpLoad:
5512 case spv::OpAtomicIAdd:
5513 case spv::OpAtomicISub:
5514 case spv::OpAtomicExchange:
5515 case spv::OpAtomicIIncrement:
5516 case spv::OpAtomicIDecrement:
5517 case spv::OpAtomicCompareExchange:
5518 case spv::OpAtomicUMin:
5519 case spv::OpAtomicSMin:
5520 case spv::OpAtomicUMax:
5521 case spv::OpAtomicSMax:
5522 case spv::OpAtomicAnd:
5523 case spv::OpAtomicOr:
5524 case spv::OpAtomicXor:
5525 case spv::OpDot: {
5526 WriteWordCountAndOpcode(Inst);
5527 WriteOperand(Ops[0]);
5528 WriteResultID(Inst);
5529 for (uint32_t i = 1; i < Ops.size(); i++) {
5530 WriteOperand(Ops[i]);
5531 }
5532 break;
5533 }
5534 }
5535 }
5536}
Alan Baker9bf93fb2018-08-28 16:59:26 -04005537
alan-bakerb6b09dc2018-11-08 16:59:28 -05005538bool SPIRVProducerPass::IsTypeNullable(const Type *type) const {
Alan Baker9bf93fb2018-08-28 16:59:26 -04005539 switch (type->getTypeID()) {
alan-bakerb6b09dc2018-11-08 16:59:28 -05005540 case Type::HalfTyID:
5541 case Type::FloatTyID:
5542 case Type::DoubleTyID:
5543 case Type::IntegerTyID:
5544 case Type::VectorTyID:
5545 return true;
5546 case Type::PointerTyID: {
5547 const PointerType *pointer_type = cast<PointerType>(type);
5548 if (pointer_type->getPointerAddressSpace() !=
5549 AddressSpace::UniformConstant) {
5550 auto pointee_type = pointer_type->getPointerElementType();
5551 if (pointee_type->isStructTy() &&
5552 cast<StructType>(pointee_type)->isOpaque()) {
5553 // Images and samplers are not nullable.
5554 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005555 }
Alan Baker9bf93fb2018-08-28 16:59:26 -04005556 }
alan-bakerb6b09dc2018-11-08 16:59:28 -05005557 return true;
5558 }
5559 case Type::ArrayTyID:
5560 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
5561 case Type::StructTyID: {
5562 const StructType *struct_type = cast<StructType>(type);
5563 // Images and samplers are not nullable.
5564 if (struct_type->isOpaque())
Alan Baker9bf93fb2018-08-28 16:59:26 -04005565 return false;
alan-bakerb6b09dc2018-11-08 16:59:28 -05005566 for (const auto element : struct_type->elements()) {
5567 if (!IsTypeNullable(element))
5568 return false;
5569 }
5570 return true;
5571 }
5572 default:
5573 return false;
Alan Baker9bf93fb2018-08-28 16:59:26 -04005574 }
5575}
Alan Bakerfcda9482018-10-02 17:09:59 -04005576
5577void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
5578 if (auto *offsets_md =
5579 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
5580 // Metdata is stored as key-value pair operands. The first element of each
5581 // operand is the type and the second is a vector of offsets.
5582 for (const auto *operand : offsets_md->operands()) {
5583 const auto *pair = cast<MDTuple>(operand);
5584 auto *type =
5585 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5586 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
5587 std::vector<uint32_t> offsets;
5588 for (const Metadata *offset_md : offset_vector->operands()) {
5589 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
alan-bakerb6b09dc2018-11-08 16:59:28 -05005590 offsets.push_back(static_cast<uint32_t>(
5591 cast<ConstantInt>(constant_md->getValue())->getZExtValue()));
Alan Bakerfcda9482018-10-02 17:09:59 -04005592 }
5593 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
5594 }
5595 }
5596
5597 if (auto *sizes_md =
5598 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
5599 // Metadata is stored as key-value pair operands. The first element of each
5600 // operand is the type and the second is a triple of sizes: type size in
5601 // bits, store size and alloc size.
5602 for (const auto *operand : sizes_md->operands()) {
5603 const auto *pair = cast<MDTuple>(operand);
5604 auto *type =
5605 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
5606 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
5607 uint64_t type_size_in_bits =
5608 cast<ConstantInt>(
5609 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
5610 ->getZExtValue();
5611 uint64_t type_store_size =
5612 cast<ConstantInt>(
5613 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
5614 ->getZExtValue();
5615 uint64_t type_alloc_size =
5616 cast<ConstantInt>(
5617 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
5618 ->getZExtValue();
5619 RemappedUBOTypeSizes.insert(std::make_pair(
5620 type, std::make_tuple(type_size_in_bits, type_store_size,
5621 type_alloc_size)));
5622 }
5623 }
5624}
5625
5626uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
5627 const DataLayout &DL) {
5628 auto iter = RemappedUBOTypeSizes.find(type);
5629 if (iter != RemappedUBOTypeSizes.end()) {
5630 return std::get<0>(iter->second);
5631 }
5632
5633 return DL.getTypeSizeInBits(type);
5634}
5635
5636uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
5637 auto iter = RemappedUBOTypeSizes.find(type);
5638 if (iter != RemappedUBOTypeSizes.end()) {
5639 return std::get<1>(iter->second);
5640 }
5641
5642 return DL.getTypeStoreSize(type);
5643}
5644
5645uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
5646 auto iter = RemappedUBOTypeSizes.find(type);
5647 if (iter != RemappedUBOTypeSizes.end()) {
5648 return std::get<2>(iter->second);
5649 }
5650
5651 return DL.getTypeAllocSize(type);
5652}
alan-baker5b86ed72019-02-15 08:26:50 -05005653
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005654void SPIRVProducerPass::setVariablePointersCapabilities(
5655 unsigned address_space) {
alan-baker5b86ed72019-02-15 08:26:50 -05005656 if (GetStorageClass(address_space) == spv::StorageClassStorageBuffer) {
5657 setVariablePointersStorageBuffer(true);
5658 } else {
5659 setVariablePointers(true);
5660 }
5661}
5662
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04005663Value *SPIRVProducerPass::GetBasePointer(Value *v) {
alan-baker5b86ed72019-02-15 08:26:50 -05005664 if (auto *gep = dyn_cast<GetElementPtrInst>(v)) {
5665 return GetBasePointer(gep->getPointerOperand());
5666 }
5667
5668 // Conservatively return |v|.
5669 return v;
5670}
5671
5672bool SPIRVProducerPass::sameResource(Value *lhs, Value *rhs) const {
5673 if (auto *lhs_call = dyn_cast<CallInst>(lhs)) {
5674 if (auto *rhs_call = dyn_cast<CallInst>(rhs)) {
5675 if (lhs_call->getCalledFunction()->getName().startswith(
5676 clspv::ResourceAccessorFunction()) &&
5677 rhs_call->getCalledFunction()->getName().startswith(
5678 clspv::ResourceAccessorFunction())) {
5679 // For resource accessors, match descriptor set and binding.
5680 if (lhs_call->getOperand(0) == rhs_call->getOperand(0) &&
5681 lhs_call->getOperand(1) == rhs_call->getOperand(1))
5682 return true;
5683 } else if (lhs_call->getCalledFunction()->getName().startswith(
5684 clspv::WorkgroupAccessorFunction()) &&
5685 rhs_call->getCalledFunction()->getName().startswith(
5686 clspv::WorkgroupAccessorFunction())) {
5687 // For workgroup resources, match spec id.
5688 if (lhs_call->getOperand(0) == rhs_call->getOperand(0))
5689 return true;
5690 }
5691 }
5692 }
5693
5694 return false;
5695}
5696
5697bool SPIRVProducerPass::selectFromSameObject(Instruction *inst) {
5698 assert(inst->getType()->isPointerTy());
5699 assert(GetStorageClass(inst->getType()->getPointerAddressSpace()) ==
5700 spv::StorageClassStorageBuffer);
5701 const bool hack_undef = clspv::Option::HackUndef();
5702 if (auto *select = dyn_cast<SelectInst>(inst)) {
5703 auto *true_base = GetBasePointer(select->getTrueValue());
5704 auto *false_base = GetBasePointer(select->getFalseValue());
5705
5706 if (true_base == false_base)
5707 return true;
5708
5709 // If either the true or false operand is a null, then we satisfy the same
5710 // object constraint.
5711 if (auto *true_cst = dyn_cast<Constant>(true_base)) {
5712 if (true_cst->isNullValue() || (hack_undef && isa<UndefValue>(true_base)))
5713 return true;
5714 }
5715
5716 if (auto *false_cst = dyn_cast<Constant>(false_base)) {
5717 if (false_cst->isNullValue() ||
5718 (hack_undef && isa<UndefValue>(false_base)))
5719 return true;
5720 }
5721
5722 if (sameResource(true_base, false_base))
5723 return true;
5724 } else if (auto *phi = dyn_cast<PHINode>(inst)) {
5725 Value *value = nullptr;
5726 bool ok = true;
5727 for (unsigned i = 0; ok && i != phi->getNumIncomingValues(); ++i) {
5728 auto *base = GetBasePointer(phi->getIncomingValue(i));
5729 // Null values satisfy the constraint of selecting of selecting from the
5730 // same object.
5731 if (!value) {
5732 if (auto *cst = dyn_cast<Constant>(base)) {
5733 if (!cst->isNullValue() && !(hack_undef && isa<UndefValue>(base)))
5734 value = base;
5735 } else {
5736 value = base;
5737 }
5738 } else if (base != value) {
5739 if (auto *base_cst = dyn_cast<Constant>(base)) {
5740 if (base_cst->isNullValue() || (hack_undef && isa<UndefValue>(base)))
5741 continue;
5742 }
5743
5744 if (sameResource(value, base))
5745 continue;
5746
5747 // Values don't represent the same base.
5748 ok = false;
5749 }
5750 }
5751
5752 return ok;
5753 }
5754
5755 // Conservatively return false.
5756 return false;
5757}
alan-bakere9308012019-03-15 10:25:13 -04005758
5759bool SPIRVProducerPass::CalledWithCoherentResource(Argument &Arg) {
5760 if (!Arg.getType()->isPointerTy() ||
5761 Arg.getType()->getPointerAddressSpace() != clspv::AddressSpace::Global) {
5762 // Only SSBOs need to be annotated as coherent.
5763 return false;
5764 }
5765
5766 DenseSet<Value *> visited;
5767 std::vector<Value *> stack;
5768 for (auto *U : Arg.getParent()->users()) {
5769 if (auto *call = dyn_cast<CallInst>(U)) {
5770 stack.push_back(call->getOperand(Arg.getArgNo()));
5771 }
5772 }
5773
5774 while (!stack.empty()) {
5775 Value *v = stack.back();
5776 stack.pop_back();
5777
5778 if (!visited.insert(v).second)
5779 continue;
5780
5781 auto *resource_call = dyn_cast<CallInst>(v);
5782 if (resource_call &&
5783 resource_call->getCalledFunction()->getName().startswith(
5784 clspv::ResourceAccessorFunction())) {
5785 // If this is a resource accessor function, check if the coherent operand
5786 // is set.
5787 const auto coherent =
5788 unsigned(dyn_cast<ConstantInt>(resource_call->getArgOperand(5))
5789 ->getZExtValue());
5790 if (coherent == 1)
5791 return true;
5792 } else if (auto *arg = dyn_cast<Argument>(v)) {
5793 // If this is a function argument, trace through its callers.
alan-bakere98f3f92019-04-08 15:06:36 -04005794 for (auto U : arg->getParent()->users()) {
alan-bakere9308012019-03-15 10:25:13 -04005795 if (auto *call = dyn_cast<CallInst>(U)) {
5796 stack.push_back(call->getOperand(arg->getArgNo()));
5797 }
5798 }
5799 } else if (auto *user = dyn_cast<User>(v)) {
5800 // If this is a user, traverse all operands that could lead to resource
5801 // variables.
5802 for (unsigned i = 0; i != user->getNumOperands(); ++i) {
5803 Value *operand = user->getOperand(i);
5804 if (operand->getType()->isPointerTy() &&
5805 operand->getType()->getPointerAddressSpace() ==
5806 clspv::AddressSpace::Global) {
5807 stack.push_back(operand);
5808 }
5809 }
5810 }
5811 }
5812
5813 // No coherent resource variables encountered.
5814 return false;
5815}