blob: 90d4e1f5c9b4d40ad866ffeebae9344536205b98 [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 Neto22f144c2017-06-12 14:26:21 -040031
David Neto118188e2018-08-24 11:27:54 -040032#include "llvm/ADT/StringSwitch.h"
33#include "llvm/ADT/UniqueVector.h"
34#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
40#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040044
David Neto85082642018-03-24 06:55:20 -070045#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040046
David Neto85082642018-03-24 06:55:20 -070047#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
David Netoab03f432017-11-03 17:00:44 -040080const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
81
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
127 SPIRVOperandList(const SPIRVOperandList& other) = delete;
128 SPIRVOperandList(SPIRVOperandList&& other) {
129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
136 void clear() { contents_.clear();}
137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
145 SmallVector<SPIRVOperand *,8> contents_;
146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
153SPIRVOperand* MkNum(uint32_t num) {
154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
David Neto257c3892018-04-11 13:19:45 -0400156SPIRVOperand* MkInteger(ArrayRef<uint32_t> num_vec) {
157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
159SPIRVOperand* MkFloat(ArrayRef<uint32_t> num_vec) {
160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
David Netoc6f3ab22018-04-06 18:02:31 -0400162SPIRVOperand* MkId(uint32_t id) {
163 return new SPIRVOperand(NUMBERID, id);
164}
David Neto257c3892018-04-11 13:19:45 -0400165SPIRVOperand* MkString(StringRef str) {
166 return new SPIRVOperand(LITERAL_STRING, str);
167}
David Netoc6f3ab22018-04-06 18:02:31 -0400168
David Neto22f144c2017-06-12 14:26:21 -0400169struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400170 // Create an instruction with an opcode and no result ID, and with the given
171 // operands. This computes its own word count.
172 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
173 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
174 Operands(Ops.begin(), Ops.end()) {
175 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400176 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400177 }
178 }
179 // Create an instruction with an opcode and a no-zero result ID, and
180 // with the given operands. This computes its own word count.
181 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400182 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400183 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
184 Operands(Ops.begin(), Ops.end()) {
185 if (ResID == 0) {
186 llvm_unreachable("Result ID of 0 was provided");
187 }
188 for (auto *operand : Ops) {
189 WordCount += operand->GetNumWords();
190 }
191 }
David Neto22f144c2017-06-12 14:26:21 -0400192
David Netoee2660d2018-06-28 16:31:29 -0400193 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400194 uint16_t getOpcode() const { return Opcode; }
195 uint32_t getResultID() const { return ResultID; }
196 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
197
198private:
David Netoee2660d2018-06-28 16:31:29 -0400199 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400200 uint16_t Opcode;
201 uint32_t ResultID;
202 SmallVector<SPIRVOperand *, 4> Operands;
203};
204
205struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400206 typedef DenseMap<Type *, uint32_t> TypeMapType;
207 typedef UniqueVector<Type *> TypeList;
208 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400209 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400210 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
211 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400212 // A vector of tuples, each of which is:
213 // - the LLVM instruction that we will later generate SPIR-V code for
214 // - where the SPIR-V instruction should be inserted
215 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400216 typedef std::vector<
217 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
218 DeferredInstVecType;
219 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
220 GlobalConstFuncMapType;
221
David Neto44795152017-07-13 15:45:28 -0400222 explicit SPIRVProducerPass(
223 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
224 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
225 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400226 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400227 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400228 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400230 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
David Neto85082642018-03-24 06:55:20 -0700231 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0),
Alan Baker202c8c72018-08-13 13:47:44 -0400232 max_local_spec_id_(0), constant_i32_zero_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; };
280 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
281 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400282 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400283 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
284 return GlobalConstFuncTypeMap;
285 }
286 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
287 return GlobalConstArgumentSet;
288 }
David Neto85082642018-03-24 06:55:20 -0700289 TypeList &getTypesNeedingArrayStride() {
290 return TypesNeedingArrayStride;
David Neto1a1a0582017-07-07 12:01:44 -0400291 }
David Neto22f144c2017-06-12 14:26:21 -0400292
David Netoc6f3ab22018-04-06 18:02:31 -0400293 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
David Neto862b7d82018-06-14 18:48:37 -0400294 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will *not*
295 // be converted to a storage buffer, replace each such global variable with
296 // one in the storage class expecgted by SPIR-V.
297 void FindGlobalConstVars(Module &M, const DataLayout &DL);
298 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
299 // ModuleOrderedResourceVars.
300 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400301 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400302 bool FindExtInst(Module &M);
303 void FindTypePerGlobalVar(GlobalVariable &GV);
304 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindTypesForSamplerMap(Module &M);
306 void FindTypesForResourceVars(Module &M);
David Neto19a1bad2017-08-25 15:01:41 -0400307 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
308 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400309 void FindType(Type *Ty);
310 void FindConstantPerGlobalVar(GlobalVariable &GV);
311 void FindConstantPerFunc(Function &F);
312 void FindConstant(Value *V);
313 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400314 // Generates instructions for SPIR-V types corresponding to the LLVM types
315 // saved in the |Types| member. A type follows its subtypes. IDs are
316 // allocated sequentially starting with the current value of nextID, and
317 // with a type following its subtypes. Also updates nextID to just beyond
318 // the last generated ID.
David Netoc6f3ab22018-04-06 18:02:31 -0400319 void GenerateSPIRVTypes(LLVMContext& context, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400320 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400321 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400322 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400323 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400324 // Generate descriptor map entries for resource variables associated with
325 // arguments to F.
326 void GenerateDescriptorMapInfo(const DataLayout& DL, Function& F);
David Neto22f144c2017-06-12 14:26:21 -0400327 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400328 // Generate OpVariables for %clspv.resource.var.* calls.
329 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateFuncPrologue(Function &F);
331 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400332 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400333 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
334 spv::Op GetSPIRVCastOpcode(Instruction &I);
335 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
336 void GenerateInstruction(Instruction &I);
337 void GenerateFuncEpilogue();
338 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400339 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400340 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400341 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
342 // have been created.
343 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400344 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400345 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400346 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400347 // Returns the GLSL extended instruction enum that the given function
348 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400349 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400350 // Returns the GLSL extended instruction enum indirectly used by the given
351 // function. That is, to implement the given function, we use an extended
352 // instruction plus one more instruction. If none, then returns the 0 value,
353 // i.e. GLSLstd4580Bad.
354 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
355 // Returns the single GLSL extended instruction used directly or
356 // indirectly by the given function call.
357 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400358 void PrintResID(SPIRVInstruction *Inst);
359 void PrintOpcode(SPIRVInstruction *Inst);
360 void PrintOperand(SPIRVOperand *Op);
361 void PrintCapability(SPIRVOperand *Op);
362 void PrintExtInst(SPIRVOperand *Op);
363 void PrintAddrModel(SPIRVOperand *Op);
364 void PrintMemModel(SPIRVOperand *Op);
365 void PrintExecModel(SPIRVOperand *Op);
366 void PrintExecMode(SPIRVOperand *Op);
367 void PrintSourceLanguage(SPIRVOperand *Op);
368 void PrintFuncCtrl(SPIRVOperand *Op);
369 void PrintStorageClass(SPIRVOperand *Op);
370 void PrintDecoration(SPIRVOperand *Op);
371 void PrintBuiltIn(SPIRVOperand *Op);
372 void PrintSelectionControl(SPIRVOperand *Op);
373 void PrintLoopControl(SPIRVOperand *Op);
374 void PrintDimensionality(SPIRVOperand *Op);
375 void PrintImageFormat(SPIRVOperand *Op);
376 void PrintMemoryAccess(SPIRVOperand *Op);
377 void PrintImageOperandsType(SPIRVOperand *Op);
378 void WriteSPIRVAssembly();
379 void WriteOneWord(uint32_t Word);
380 void WriteResultID(SPIRVInstruction *Inst);
381 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
382 void WriteOperand(SPIRVOperand *Op);
383 void WriteSPIRVBinary();
384
Alan Baker9bf93fb2018-08-28 16:59:26 -0400385 // Returns true if |type| is compatible with OpConstantNull.
386 bool IsTypeNullable(const Type* type) const;
387
David Neto22f144c2017-06-12 14:26:21 -0400388private:
389 static char ID;
David Neto44795152017-07-13 15:45:28 -0400390 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400391 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400392
393 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
394 // convert to other formats on demand?
395
396 // When emitting a C initialization list, the WriteSPIRVBinary method
397 // will actually write its words to this vector via binaryTempOut.
398 SmallVector<char, 100> binaryTempUnderlyingVector;
399 raw_svector_ostream binaryTempOut;
400
401 // Binary output writes to this stream, which might be |out| or
402 // |binaryTempOut|. It's the latter when we really want to write a C
403 // initializer list.
404 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400405 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400406 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400407 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400408 uint64_t patchBoundOffset;
409 uint32_t nextID;
410
David Neto19a1bad2017-08-25 15:01:41 -0400411 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400412 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400413 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400414 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400415 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400416 TypeList Types;
417 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400418 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400419 ValueMapType ValueMap;
420 ValueMapType AllocatedValueMap;
421 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400422
David Neto22f144c2017-06-12 14:26:21 -0400423 EntryPointVecType EntryPointVec;
424 DeferredInstVecType DeferredInstVec;
425 ValueList EntryPointInterfacesVec;
426 uint32_t OpExtInstImportID;
427 std::vector<uint32_t> BuiltinDimensionVec;
428 bool HasVariablePointers;
429 Type *SamplerTy;
David Neto862b7d82018-06-14 18:48:37 -0400430 DenseMap<unsigned,uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700431
432 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700433 // will map F's type to (G, index of the parameter), where in a first phase
434 // G is F's type. During FindTypePerFunc, G will be changed to F's type
435 // but replacing the pointer-to-constant parameter with
436 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700437 // TODO(dneto): This doesn't seem general enough? A function might have
438 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400439 GlobalConstFuncMapType GlobalConstFuncTypeMap;
440 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400441 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700442 // or array types, and which point into transparent memory (StorageBuffer
443 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400444 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700445 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400446
447 // This is truly ugly, but works around what look like driver bugs.
448 // For get_local_size, an earlier part of the flow has created a module-scope
449 // variable in Private address space to hold the value for the workgroup
450 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
451 // When this is present, save the IDs of the initializer value and variable
452 // in these two variables. We only ever do a vector load from it, and
453 // when we see one of those, substitute just the value of the intializer.
454 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700455 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400456 uint32_t WorkgroupSizeValueID;
457 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400458
David Neto862b7d82018-06-14 18:48:37 -0400459 // Bookkeeping for mapping kernel arguments to resource variables.
460 struct ResourceVarInfo {
461 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
462 Function *fn, clspv::ArgKind arg_kind_arg)
463 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
464 var_fn(fn), arg_kind(arg_kind_arg),
465 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
466 const int index; // Index into ResourceVarInfoList
467 const unsigned descriptor_set;
468 const unsigned binding;
469 Function *const var_fn; // The @clspv.resource.var.* function.
470 const clspv::ArgKind arg_kind;
471 const unsigned addr_space; // The LLVM address space
472 // The SPIR-V ID of the OpVariable. Not populated at construction time.
473 uint32_t var_id = 0;
474 };
475 // A list of resource var info. Each one correponds to a module-scope
476 // resource variable we will have to create. Resource var indices are
477 // indices into this vector.
478 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
479 // This is a vector of pointers of all the resource vars, but ordered by
480 // kernel function, and then by argument.
481 UniqueVector<ResourceVarInfo*> ModuleOrderedResourceVars;
482 // Map a function to the ordered list of resource variables it uses, one for
483 // each argument. If an argument does not use a resource variable, it
484 // will have a null pointer entry.
485 using FunctionToResourceVarsMapType =
486 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
487 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
488
489 // What LLVM types map to SPIR-V types needing layout? These are the
490 // arrays and structures supporting storage buffers and uniform buffers.
491 TypeList TypesNeedingLayout;
492 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
493 UniqueVector<StructType *> StructTypesNeedingBlock;
494 // For a call that represents a load from an opaque type (samplers, images),
495 // map it to the variable id it should load from.
496 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700497
Alan Baker202c8c72018-08-13 13:47:44 -0400498 // One larger than the maximum used SpecId for pointer-to-local arguments.
499 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400500 // An ordered list of the kernel arguments of type pointer-to-local.
Alan Baker202c8c72018-08-13 13:47:44 -0400501 using LocalArgList = SmallVector<Argument*, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400502 LocalArgList LocalArgs;
503 // Information about a pointer-to-local argument.
504 struct LocalArgInfo {
505 // The SPIR-V ID of the array variable.
506 uint32_t variable_id;
507 // The element type of the
508 Type* elem_type;
509 // The ID of the array type.
510 uint32_t array_size_id;
511 // The ID of the array type.
512 uint32_t array_type_id;
513 // The ID of the pointer to the array type.
514 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400515 // The specialization constant ID of the array size.
516 int spec_id;
517 };
Alan Baker202c8c72018-08-13 13:47:44 -0400518 // A mapping from Argument to its assigned SpecId.
519 DenseMap<const Argument*, int> LocalArgSpecIds;
520 // A mapping from SpecId to its LocalArgInfo.
521 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
David Neto257c3892018-04-11 13:19:45 -0400522
523 // The ID of 32-bit integer zero constant. This is only valid after
524 // GenerateSPIRVConstants has run.
525 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400526};
527
528char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400529
David Neto22f144c2017-06-12 14:26:21 -0400530}
531
532namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400533ModulePass *
534createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
535 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
536 bool outputAsm, bool outputCInitList) {
537 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
538 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400539}
David Netoc2c368d2017-06-30 16:50:17 -0400540} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400541
542bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400543 binaryOut = outputCInitList ? &binaryTempOut : &out;
544
David Neto257c3892018-04-11 13:19:45 -0400545 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
546
David Neto22f144c2017-06-12 14:26:21 -0400547 // SPIR-V always begins with its header information
548 outputHeader();
549
David Netoc6f3ab22018-04-06 18:02:31 -0400550 const DataLayout &DL = module.getDataLayout();
551
David Neto22f144c2017-06-12 14:26:21 -0400552 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400553 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400554
David Neto22f144c2017-06-12 14:26:21 -0400555 // Collect information on global variables too.
556 for (GlobalVariable &GV : module.globals()) {
557 // If the GV is one of our special __spirv_* variables, remove the
558 // initializer as it was only placed there to force LLVM to not throw the
559 // value away.
560 if (GV.getName().startswith("__spirv_")) {
561 GV.setInitializer(nullptr);
562 }
563
564 // Collect types' information from global variable.
565 FindTypePerGlobalVar(GV);
566
567 // Collect constant information from global variable.
568 FindConstantPerGlobalVar(GV);
569
570 // If the variable is an input, entry points need to know about it.
571 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400572 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400573 }
574 }
575
576 // If there are extended instructions, generate OpExtInstImport.
577 if (FindExtInst(module)) {
578 GenerateExtInstImport();
579 }
580
581 // Generate SPIRV instructions for types.
David Netoc6f3ab22018-04-06 18:02:31 -0400582 GenerateSPIRVTypes(module.getContext(), DL);
David Neto22f144c2017-06-12 14:26:21 -0400583
584 // Generate SPIRV constants.
585 GenerateSPIRVConstants();
586
587 // If we have a sampler map, we might have literal samplers to generate.
588 if (0 < getSamplerMap().size()) {
589 GenerateSamplers(module);
590 }
591
592 // Generate SPIRV variables.
593 for (GlobalVariable &GV : module.globals()) {
594 GenerateGlobalVar(GV);
595 }
David Neto862b7d82018-06-14 18:48:37 -0400596 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400597 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400598
599 // Generate SPIRV instructions for each function.
600 for (Function &F : module) {
601 if (F.isDeclaration()) {
602 continue;
603 }
604
David Neto862b7d82018-06-14 18:48:37 -0400605 GenerateDescriptorMapInfo(DL, F);
606
David Neto22f144c2017-06-12 14:26:21 -0400607 // Generate Function Prologue.
608 GenerateFuncPrologue(F);
609
610 // Generate SPIRV instructions for function body.
611 GenerateFuncBody(F);
612
613 // Generate Function Epilogue.
614 GenerateFuncEpilogue();
615 }
616
617 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400618 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400619
620 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400621 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400622
623 if (outputAsm) {
624 WriteSPIRVAssembly();
625 } else {
626 WriteSPIRVBinary();
627 }
628
629 // We need to patch the SPIR-V header to set bound correctly.
630 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400631
632 if (outputCInitList) {
633 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400634 std::ostringstream os;
635
David Neto57fb0b92017-08-04 15:35:09 -0400636 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400637 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400638 os << ",\n";
639 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400640 first = false;
641 };
642
643 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400644 const std::string str(binaryTempOut.str());
645 for (unsigned i = 0; i < str.size(); i += 4) {
646 const uint32_t a = static_cast<unsigned char>(str[i]);
647 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
648 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
649 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
650 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400651 }
652 os << "}\n";
653 out << os.str();
654 }
655
David Neto22f144c2017-06-12 14:26:21 -0400656 return false;
657}
658
659void SPIRVProducerPass::outputHeader() {
660 if (outputAsm) {
661 // for ASM output the header goes into 5 comments at the beginning of the
662 // file
663 out << "; SPIR-V\n";
664
665 // the major version number is in the 2nd highest byte
666 const uint32_t major = (spv::Version >> 16) & 0xFF;
667
668 // the minor version number is in the 2nd lowest byte
669 const uint32_t minor = (spv::Version >> 8) & 0xFF;
670 out << "; Version: " << major << "." << minor << "\n";
671
672 // use Codeplay's vendor ID
673 out << "; Generator: Codeplay; 0\n";
674
675 out << "; Bound: ";
676
677 // we record where we need to come back to and patch in the bound value
678 patchBoundOffset = out.tell();
679
680 // output one space per digit for the max size of a 32 bit unsigned integer
681 // (which is the maximum ID we could possibly be using)
682 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
683 out << " ";
684 }
685
686 out << "\n";
687
688 out << "; Schema: 0\n";
689 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400690 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400691 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400692 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400693 sizeof(spv::Version));
694
695 // use Codeplay's vendor ID
696 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400697 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400698
699 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400700 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400701
702 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400703 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400704
705 // output the schema (reserved for use and must be 0)
706 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400707 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400708 }
709}
710
711void SPIRVProducerPass::patchHeader() {
712 if (outputAsm) {
713 // get the string representation of the max bound used (nextID will be the
714 // max ID used)
715 auto asString = std::to_string(nextID);
716 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
717 } else {
718 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400719 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
720 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400721 }
722}
723
David Netoc6f3ab22018-04-06 18:02:31 -0400724void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400725 // This function generates LLVM IR for function such as global variable for
726 // argument, constant and pointer type for argument access. These information
727 // is artificial one because we need Vulkan SPIR-V output. This function is
728 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400729 LLVMContext &Context = M.getContext();
730
David Neto862b7d82018-06-14 18:48:37 -0400731 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400732
David Neto862b7d82018-06-14 18:48:37 -0400733 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400734
735 bool HasWorkGroupBuiltin = false;
736 for (GlobalVariable &GV : M.globals()) {
737 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
738 if (spv::BuiltInWorkgroupSize == BuiltinType) {
739 HasWorkGroupBuiltin = true;
740 }
741 }
742
David Neto862b7d82018-06-14 18:48:37 -0400743 FindTypesForSamplerMap(M);
744 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400745 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400746
David Neto862b7d82018-06-14 18:48:37 -0400747 // TODO(dneto): Delete the next 3 vars.
748
749 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400750 // Map kernel functions to their ordinal number in the compilation unit.
751 UniqueVector<Function*> KernelOrdinal;
752
753 // Map the global variables created for kernel args to their creation
754 // order.
755 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
756
David Neto862b7d82018-06-14 18:48:37 -0400757 // For each kernel argument type, record the kernel arg global resource
758 // variables generated for that type, the function in which that variable
759 // was most recently used, and the binding number it took. For
760 // reproducibility, we track things by ordinal number (rather than pointer),
761 // and we use a std::set rather than DenseSet since std::set maintains an
762 // ordering. Each tuple is the ordinals of the kernel function, the binding
763 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400764 //
765 // This table lets us reuse module-scope StorageBuffer variables between
766 // different kernels.
767 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
768 GVarsForType;
769
David Neto862b7d82018-06-14 18:48:37 -0400770 // These function calls need a <2 x i32> as an intermediate result but not
771 // the final result.
772 std::unordered_set<std::string> NeedsIVec2{
773 "_Z15get_image_width14ocl_image2d_ro",
774 "_Z15get_image_width14ocl_image2d_wo",
775 "_Z16get_image_height14ocl_image2d_ro",
776 "_Z16get_image_height14ocl_image2d_wo",
777 };
778
David Neto22f144c2017-06-12 14:26:21 -0400779 for (Function &F : M) {
780 // Handle kernel function first.
781 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
782 continue;
783 }
David Neto26aaf622017-10-23 18:11:53 -0400784 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400785
786 for (BasicBlock &BB : F) {
787 for (Instruction &I : BB) {
788 if (I.getOpcode() == Instruction::ZExt ||
789 I.getOpcode() == Instruction::SExt ||
790 I.getOpcode() == Instruction::UIToFP) {
791 // If there is zext with i1 type, it will be changed to OpSelect. The
792 // OpSelect needs constant 0 and 1 so the constants are added here.
793
794 auto OpTy = I.getOperand(0)->getType();
795
Kévin Petit24272b62018-10-18 19:16:12 +0000796 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400797 if (I.getOpcode() == Instruction::ZExt) {
798 APInt One(32, 1);
799 FindConstant(Constant::getNullValue(I.getType()));
800 FindConstant(Constant::getIntegerValue(I.getType(), One));
801 } else if (I.getOpcode() == Instruction::SExt) {
802 APInt MinusOne(32, UINT64_MAX, true);
803 FindConstant(Constant::getNullValue(I.getType()));
804 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
805 } else {
806 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
807 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
808 }
809 }
810 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400811 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400812
813 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400814 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400815 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400816 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400817 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
818 TypeMapType &OpImageTypeMap = getImageTypeMap();
819 Type *ImageTy =
820 Call->getArgOperand(0)->getType()->getPointerElementType();
821 OpImageTypeMap[ImageTy] = 0;
822
823 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
824 }
David Neto5c22a252018-03-15 16:07:41 -0400825
David Neto862b7d82018-06-14 18:48:37 -0400826 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400827 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
828 }
David Neto22f144c2017-06-12 14:26:21 -0400829 }
830 }
831 }
832
David Neto22f144c2017-06-12 14:26:21 -0400833 if (const MDNode *MD =
834 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
835 // We generate constants if the WorkgroupSize builtin is being used.
836 if (HasWorkGroupBuiltin) {
837 // Collect constant information for work group size.
838 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
839 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
840 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
841 }
842 }
843
David Neto22f144c2017-06-12 14:26:21 -0400844 // Collect types' information from function.
845 FindTypePerFunc(F);
846
847 // Collect constant information from function.
848 FindConstantPerFunc(F);
849 }
850
851 for (Function &F : M) {
852 // Handle non-kernel functions.
853 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
854 continue;
855 }
856
857 for (BasicBlock &BB : F) {
858 for (Instruction &I : BB) {
859 if (I.getOpcode() == Instruction::ZExt ||
860 I.getOpcode() == Instruction::SExt ||
861 I.getOpcode() == Instruction::UIToFP) {
862 // If there is zext with i1 type, it will be changed to OpSelect. The
863 // OpSelect needs constant 0 and 1 so the constants are added here.
864
865 auto OpTy = I.getOperand(0)->getType();
866
Kévin Petit24272b62018-10-18 19:16:12 +0000867 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400868 if (I.getOpcode() == Instruction::ZExt) {
869 APInt One(32, 1);
870 FindConstant(Constant::getNullValue(I.getType()));
871 FindConstant(Constant::getIntegerValue(I.getType(), One));
872 } else if (I.getOpcode() == Instruction::SExt) {
873 APInt MinusOne(32, UINT64_MAX, true);
874 FindConstant(Constant::getNullValue(I.getType()));
875 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
876 } else {
877 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
878 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
879 }
880 }
881 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
882 Function *Callee = Call->getCalledFunction();
883
884 // Handle image type specially.
885 if (Callee->getName().equals(
886 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
887 Callee->getName().equals(
888 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
889 TypeMapType &OpImageTypeMap = getImageTypeMap();
890 Type *ImageTy =
891 Call->getArgOperand(0)->getType()->getPointerElementType();
892 OpImageTypeMap[ImageTy] = 0;
893
894 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
895 }
896 }
897 }
898 }
899
900 if (M.getTypeByName("opencl.image2d_ro_t") ||
901 M.getTypeByName("opencl.image2d_wo_t") ||
902 M.getTypeByName("opencl.image3d_ro_t") ||
903 M.getTypeByName("opencl.image3d_wo_t")) {
904 // Assume Image type's sampled type is float type.
905 FindType(Type::getFloatTy(Context));
906 }
907
908 // Collect types' information from function.
909 FindTypePerFunc(F);
910
911 // Collect constant information from function.
912 FindConstantPerFunc(F);
913 }
914}
915
David Neto862b7d82018-06-14 18:48:37 -0400916void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
917 SmallVector<GlobalVariable *, 8> GVList;
918 SmallVector<GlobalVariable *, 8> DeadGVList;
919 for (GlobalVariable &GV : M.globals()) {
920 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
921 if (GV.use_empty()) {
922 DeadGVList.push_back(&GV);
923 } else {
924 GVList.push_back(&GV);
925 }
926 }
927 }
928
929 // Remove dead global __constant variables.
930 for (auto GV : DeadGVList) {
931 GV->eraseFromParent();
932 }
933 DeadGVList.clear();
934
935 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
936 // For now, we only support a single storage buffer.
937 if (GVList.size() > 0) {
938 assert(GVList.size() == 1);
939 const auto *GV = GVList[0];
940 const auto constants_byte_size =
941 (DL.getTypeSizeInBits(GV->getInitializer()->getType())) / 8;
942 const size_t kConstantMaxSize = 65536;
943 if (constants_byte_size > kConstantMaxSize) {
944 outs() << "Max __constant capacity of " << kConstantMaxSize
945 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
946 llvm_unreachable("Max __constant capacity exceeded");
947 }
948 }
949 } else {
950 // Change global constant variable's address space to ModuleScopePrivate.
951 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
952 for (auto GV : GVList) {
953 // Create new gv with ModuleScopePrivate address space.
954 Type *NewGVTy = GV->getType()->getPointerElementType();
955 GlobalVariable *NewGV = new GlobalVariable(
956 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
957 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
958 NewGV->takeName(GV);
959
960 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
961 SmallVector<User *, 8> CandidateUsers;
962
963 auto record_called_function_type_as_user =
964 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
965 // Find argument index.
966 unsigned index = 0;
967 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
968 if (gv == call->getOperand(i)) {
969 // TODO(dneto): Should we break here?
970 index = i;
971 }
972 }
973
974 // Record function type with global constant.
975 GlobalConstFuncTyMap[call->getFunctionType()] =
976 std::make_pair(call->getFunctionType(), index);
977 };
978
979 for (User *GVU : GVUsers) {
980 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
981 record_called_function_type_as_user(GV, Call);
982 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
983 // Check GEP users.
984 for (User *GEPU : GEP->users()) {
985 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
986 record_called_function_type_as_user(GEP, GEPCall);
987 }
988 }
989 }
990
991 CandidateUsers.push_back(GVU);
992 }
993
994 for (User *U : CandidateUsers) {
995 // Update users of gv with new gv.
996 U->replaceUsesOfWith(GV, NewGV);
997 }
998
999 // Delete original gv.
1000 GV->eraseFromParent();
1001 }
1002 }
1003}
1004
1005void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &DL) {
1006 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1007 ValueMapType &VMap = getValueMap();
1008
1009 ResourceVarInfoList.clear();
1010 FunctionToResourceVarsMap.clear();
1011 ModuleOrderedResourceVars.reset();
1012 // Normally, there is one resource variable per clspv.resource.var.*
1013 // function, since that is unique'd by arg type and index. By design,
1014 // we can share these resource variables across kernels because all
1015 // kernels use the same descriptor set.
1016 //
1017 // But if the user requested distinct descriptor sets per kernel, then
1018 // the descriptor allocator has made different (set,binding) pairs for
1019 // the same (type,arg_index) pair. Since we can decorate a resource
1020 // variable with only exactly one DescriptorSet and Binding, we are
1021 // forced in this case to make distinct resource variables whenever
1022 // the same clspv.reource.var.X function is seen with disintct
1023 // (set,binding) values.
1024 const bool always_distinct_sets =
1025 clspv::Option::DistinctKernelDescriptorSets();
1026 for (Function &F : M) {
1027 // Rely on the fact the resource var functions have a stable ordering
1028 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001029 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001030 // Find all calls to this function with distinct set and binding pairs.
1031 // Save them in ResourceVarInfoList.
1032
1033 // Determine uniqueness of the (set,binding) pairs only withing this
1034 // one resource-var builtin function.
1035 using SetAndBinding = std::pair<unsigned, unsigned>;
1036 // Maps set and binding to the resource var info.
1037 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1038 bool first_use = true;
1039 for (auto &U : F.uses()) {
1040 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1041 const auto set = unsigned(
1042 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1043 const auto binding = unsigned(
1044 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1045 const auto arg_kind = clspv::ArgKind(
1046 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1047 const auto arg_index = unsigned(
1048 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1049
1050 // Find or make the resource var info for this combination.
1051 ResourceVarInfo *rv = nullptr;
1052 if (always_distinct_sets) {
1053 // Make a new resource var any time we see a different
1054 // (set,binding) pair.
1055 SetAndBinding key{set, binding};
1056 auto where = set_and_binding_map.find(key);
1057 if (where == set_and_binding_map.end()) {
1058 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1059 binding, &F, arg_kind);
1060 ResourceVarInfoList.emplace_back(rv);
1061 set_and_binding_map[key] = rv;
1062 } else {
1063 rv = where->second;
1064 }
1065 } else {
1066 // The default is to make exactly one resource for each
1067 // clspv.resource.var.* function.
1068 if (first_use) {
1069 first_use = false;
1070 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1071 binding, &F, arg_kind);
1072 ResourceVarInfoList.emplace_back(rv);
1073 } else {
1074 rv = ResourceVarInfoList.back().get();
1075 }
1076 }
1077
1078 // Now populate FunctionToResourceVarsMap.
1079 auto &mapping =
1080 FunctionToResourceVarsMap[call->getParent()->getParent()];
1081 while (mapping.size() <= arg_index) {
1082 mapping.push_back(nullptr);
1083 }
1084 mapping[arg_index] = rv;
1085 }
1086 }
1087 }
1088 }
1089
1090 // Populate ModuleOrderedResourceVars.
1091 for (Function &F : M) {
1092 auto where = FunctionToResourceVarsMap.find(&F);
1093 if (where != FunctionToResourceVarsMap.end()) {
1094 for (auto &rv : where->second) {
1095 if (rv != nullptr) {
1096 ModuleOrderedResourceVars.insert(rv);
1097 }
1098 }
1099 }
1100 }
1101 if (ShowResourceVars) {
1102 for (auto *info : ModuleOrderedResourceVars) {
1103 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1104 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1105 << "\n";
1106 }
1107 }
1108}
1109
David Neto22f144c2017-06-12 14:26:21 -04001110bool SPIRVProducerPass::FindExtInst(Module &M) {
1111 LLVMContext &Context = M.getContext();
1112 bool HasExtInst = false;
1113
1114 for (Function &F : M) {
1115 for (BasicBlock &BB : F) {
1116 for (Instruction &I : BB) {
1117 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1118 Function *Callee = Call->getCalledFunction();
1119 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001120 auto callee_name = Callee->getName();
1121 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1122 const glsl::ExtInst IndirectEInst =
1123 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001124
David Neto3fbb4072017-10-16 11:28:14 -04001125 HasExtInst |=
1126 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1127
1128 if (IndirectEInst) {
1129 // Register extra constants if needed.
1130
1131 // Registers a type and constant for computing the result of the
1132 // given instruction. If the result of the instruction is a vector,
1133 // then make a splat vector constant with the same number of
1134 // elements.
1135 auto register_constant = [this, &I](Constant *constant) {
1136 FindType(constant->getType());
1137 FindConstant(constant);
1138 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1139 // Register the splat vector of the value with the same
1140 // width as the result of the instruction.
1141 auto *vec_constant = ConstantVector::getSplat(
1142 static_cast<unsigned>(vectorTy->getNumElements()),
1143 constant);
1144 FindConstant(vec_constant);
1145 FindType(vec_constant->getType());
1146 }
1147 };
1148 switch (IndirectEInst) {
1149 case glsl::ExtInstFindUMsb:
1150 // clz needs OpExtInst and OpISub with constant 31, or splat
1151 // vector of 31. Add it to the constant list here.
1152 register_constant(
1153 ConstantInt::get(Type::getInt32Ty(Context), 31));
1154 break;
1155 case glsl::ExtInstAcos:
1156 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001157 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001158 case glsl::ExtInstAtan2:
1159 // We need 1/pi for acospi, asinpi, atan2pi.
1160 register_constant(
1161 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1162 break;
1163 default:
1164 assert(false && "internally inconsistent");
1165 }
David Neto22f144c2017-06-12 14:26:21 -04001166 }
1167 }
1168 }
1169 }
1170 }
1171
1172 return HasExtInst;
1173}
1174
1175void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1176 // Investigate global variable's type.
1177 FindType(GV.getType());
1178}
1179
1180void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1181 // Investigate function's type.
1182 FunctionType *FTy = F.getFunctionType();
1183
1184 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1185 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001186 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001187 if (GlobalConstFuncTyMap.count(FTy)) {
1188 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1189 SmallVector<Type *, 4> NewFuncParamTys;
1190 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1191 Type *ParamTy = FTy->getParamType(i);
1192 if (i == GVCstArgIdx) {
1193 Type *EleTy = ParamTy->getPointerElementType();
1194 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1195 }
1196
1197 NewFuncParamTys.push_back(ParamTy);
1198 }
1199
1200 FunctionType *NewFTy =
1201 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1202 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1203 FTy = NewFTy;
1204 }
1205
1206 FindType(FTy);
1207 } else {
1208 // As kernel functions do not have parameters, create new function type and
1209 // add it to type map.
1210 SmallVector<Type *, 4> NewFuncParamTys;
1211 FunctionType *NewFTy =
1212 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1213 FindType(NewFTy);
1214 }
1215
1216 // Investigate instructions' type in function body.
1217 for (BasicBlock &BB : F) {
1218 for (Instruction &I : BB) {
1219 if (isa<ShuffleVectorInst>(I)) {
1220 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1221 // Ignore type for mask of shuffle vector instruction.
1222 if (i == 2) {
1223 continue;
1224 }
1225
1226 Value *Op = I.getOperand(i);
1227 if (!isa<MetadataAsValue>(Op)) {
1228 FindType(Op->getType());
1229 }
1230 }
1231
1232 FindType(I.getType());
1233 continue;
1234 }
1235
David Neto862b7d82018-06-14 18:48:37 -04001236 CallInst *Call = dyn_cast<CallInst>(&I);
1237
1238 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001239 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001240 // This is a fake call representing access to a resource variable.
1241 // We handle that elsewhere.
1242 continue;
1243 }
1244
Alan Baker202c8c72018-08-13 13:47:44 -04001245 if (Call && Call->getCalledFunction()->getName().startswith(
1246 clspv::WorkgroupAccessorFunction())) {
1247 // This is a fake call representing access to a workgroup variable.
1248 // We handle that elsewhere.
1249 continue;
1250 }
1251
David Neto22f144c2017-06-12 14:26:21 -04001252 // Work through the operands of the instruction.
1253 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1254 Value *const Op = I.getOperand(i);
1255 // If any of the operands is a constant, find the type!
1256 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1257 FindType(Op->getType());
1258 }
1259 }
1260
1261 for (Use &Op : I.operands()) {
1262 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1263 // Avoid to check call instruction's type.
1264 break;
1265 }
Alan Baker202c8c72018-08-13 13:47:44 -04001266 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1267 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1268 clspv::WorkgroupAccessorFunction())) {
1269 // This is a fake call representing access to a workgroup variable.
1270 // We handle that elsewhere.
1271 continue;
1272 }
1273 }
David Neto22f144c2017-06-12 14:26:21 -04001274 if (!isa<MetadataAsValue>(&Op)) {
1275 FindType(Op->getType());
1276 continue;
1277 }
1278 }
1279
David Neto22f144c2017-06-12 14:26:21 -04001280 // We don't want to track the type of this call as we are going to replace
1281 // it.
David Neto862b7d82018-06-14 18:48:37 -04001282 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001283 Call->getCalledFunction()->getName())) {
1284 continue;
1285 }
1286
1287 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1288 // If gep's base operand has ModuleScopePrivate address space, make gep
1289 // return ModuleScopePrivate address space.
1290 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1291 // Add pointer type with private address space for global constant to
1292 // type list.
1293 Type *EleTy = I.getType()->getPointerElementType();
1294 Type *NewPTy =
1295 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1296
1297 FindType(NewPTy);
1298 continue;
1299 }
1300 }
1301
1302 FindType(I.getType());
1303 }
1304 }
1305}
1306
David Neto862b7d82018-06-14 18:48:37 -04001307void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1308 // If we are using a sampler map, find the type of the sampler.
1309 if (M.getFunction("clspv.sampler.var.literal") ||
1310 0 < getSamplerMap().size()) {
1311 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1312 if (!SamplerStructTy) {
1313 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1314 }
1315
1316 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1317
1318 FindType(SamplerTy);
1319 }
1320}
1321
1322void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1323 // Record types so they are generated.
1324 TypesNeedingLayout.reset();
1325 StructTypesNeedingBlock.reset();
1326
1327 // To match older clspv codegen, generate the float type first if required
1328 // for images.
1329 for (const auto *info : ModuleOrderedResourceVars) {
1330 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1331 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1332 // We need "float" for the sampled component type.
1333 FindType(Type::getFloatTy(M.getContext()));
1334 // We only need to find it once.
1335 break;
1336 }
1337 }
1338
1339 for (const auto *info : ModuleOrderedResourceVars) {
1340 Type *type = info->var_fn->getReturnType();
1341
1342 switch (info->arg_kind) {
1343 case clspv::ArgKind::Buffer:
1344 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1345 StructTypesNeedingBlock.insert(sty);
1346 } else {
1347 errs() << *type << "\n";
1348 llvm_unreachable("Buffer arguments must map to structures!");
1349 }
1350 break;
1351 case clspv::ArgKind::Pod:
1352 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1353 StructTypesNeedingBlock.insert(sty);
1354 } else {
1355 errs() << *type << "\n";
1356 llvm_unreachable("POD arguments must map to structures!");
1357 }
1358 break;
1359 case clspv::ArgKind::ReadOnlyImage:
1360 case clspv::ArgKind::WriteOnlyImage:
1361 case clspv::ArgKind::Sampler:
1362 // Sampler and image types map to the pointee type but
1363 // in the uniform constant address space.
1364 type = PointerType::get(type->getPointerElementType(),
1365 clspv::AddressSpace::UniformConstant);
1366 break;
1367 default:
1368 break;
1369 }
1370
1371 // The converted type is the type of the OpVariable we will generate.
1372 // If the pointee type is an array of size zero, FindType will convert it
1373 // to a runtime array.
1374 FindType(type);
1375 }
1376
1377 // Traverse the arrays and structures underneath each Block, and
1378 // mark them as needing layout.
1379 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1380 StructTypesNeedingBlock.end());
1381 while (!work_list.empty()) {
1382 Type *type = work_list.back();
1383 work_list.pop_back();
1384 TypesNeedingLayout.insert(type);
1385 switch (type->getTypeID()) {
1386 case Type::ArrayTyID:
1387 work_list.push_back(type->getArrayElementType());
1388 if (!Hack_generate_runtime_array_stride_early) {
1389 // Remember this array type for deferred decoration.
1390 TypesNeedingArrayStride.insert(type);
1391 }
1392 break;
1393 case Type::StructTyID:
1394 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1395 work_list.push_back(elem_ty);
1396 }
1397 default:
1398 // This type and its contained types don't get layout.
1399 break;
1400 }
1401 }
1402}
1403
Alan Baker202c8c72018-08-13 13:47:44 -04001404void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1405 // The SpecId assignment for pointer-to-local arguments is recorded in
1406 // module-level metadata. Translate that information into local argument
1407 // information.
1408 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
1409 if (!nmd) return;
1410 for (auto operand : nmd->operands()) {
1411 MDTuple *tuple = cast<MDTuple>(operand);
1412 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1413 Function *func = cast<Function>(fn_md->getValue());
1414 ConstantAsMetadata *arg_index_md = cast<ConstantAsMetadata>(tuple->getOperand(1));
1415 int arg_index = cast<ConstantInt>(arg_index_md->getValue())->getSExtValue();
1416 Argument* arg = &*(func->arg_begin() + arg_index);
1417
1418 ConstantAsMetadata *spec_id_md =
1419 cast<ConstantAsMetadata>(tuple->getOperand(2));
1420 int spec_id = cast<ConstantInt>(spec_id_md->getValue())->getSExtValue();
1421
1422 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1423 LocalArgSpecIds[arg] = spec_id;
1424 if (LocalSpecIdInfoMap.count(spec_id)) continue;
1425
1426 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1427 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1428 nextID + 1, nextID + 2,
1429 nextID + 3, spec_id};
1430 LocalSpecIdInfoMap[spec_id] = info;
1431 nextID += 4;
1432
1433 // Ensure the types necessary for this argument get generated.
1434 Type *IdxTy = Type::getInt32Ty(M.getContext());
1435 FindConstant(ConstantInt::get(IdxTy, 0));
1436 FindType(IdxTy);
1437 FindType(arg->getType());
1438 }
1439}
1440
David Neto22f144c2017-06-12 14:26:21 -04001441void SPIRVProducerPass::FindType(Type *Ty) {
1442 TypeList &TyList = getTypeList();
1443
1444 if (0 != TyList.idFor(Ty)) {
1445 return;
1446 }
1447
1448 if (Ty->isPointerTy()) {
1449 auto AddrSpace = Ty->getPointerAddressSpace();
1450 if ((AddressSpace::Constant == AddrSpace) ||
1451 (AddressSpace::Global == AddrSpace)) {
1452 auto PointeeTy = Ty->getPointerElementType();
1453
1454 if (PointeeTy->isStructTy() &&
1455 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1456 FindType(PointeeTy);
1457 auto ActualPointerTy =
1458 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1459 FindType(ActualPointerTy);
1460 return;
1461 }
1462 }
1463 }
1464
David Neto862b7d82018-06-14 18:48:37 -04001465 // By convention, LLVM array type with 0 elements will map to
1466 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1467 // has a constant number of elements. We need to support type of the
1468 // constant.
1469 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1470 if (arrayTy->getNumElements() > 0) {
1471 LLVMContext &Context = Ty->getContext();
1472 FindType(Type::getInt32Ty(Context));
1473 }
David Neto22f144c2017-06-12 14:26:21 -04001474 }
1475
1476 for (Type *SubTy : Ty->subtypes()) {
1477 FindType(SubTy);
1478 }
1479
1480 TyList.insert(Ty);
1481}
1482
1483void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1484 // If the global variable has a (non undef) initializer.
1485 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001486 // Generate the constant if it's not the initializer to a module scope
1487 // constant that we will expect in a storage buffer.
1488 const bool module_scope_constant_external_init =
1489 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1490 clspv::Option::ModuleConstantsInStorageBuffer();
1491 if (!module_scope_constant_external_init) {
1492 FindConstant(GV.getInitializer());
1493 }
David Neto22f144c2017-06-12 14:26:21 -04001494 }
1495}
1496
1497void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1498 // Investigate constants in function body.
1499 for (BasicBlock &BB : F) {
1500 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001501 if (auto *call = dyn_cast<CallInst>(&I)) {
1502 auto name = call->getCalledFunction()->getName();
1503 if (name == "clspv.sampler.var.literal") {
1504 // We've handled these constants elsewhere, so skip it.
1505 continue;
1506 }
Alan Baker202c8c72018-08-13 13:47:44 -04001507 if (name.startswith(clspv::ResourceAccessorFunction())) {
1508 continue;
1509 }
1510 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001511 continue;
1512 }
David Neto22f144c2017-06-12 14:26:21 -04001513 }
1514
1515 if (isa<AllocaInst>(I)) {
1516 // Alloca instruction has constant for the number of element. Ignore it.
1517 continue;
1518 } else if (isa<ShuffleVectorInst>(I)) {
1519 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1520 // Ignore constant for mask of shuffle vector instruction.
1521 if (i == 2) {
1522 continue;
1523 }
1524
1525 if (isa<Constant>(I.getOperand(i)) &&
1526 !isa<GlobalValue>(I.getOperand(i))) {
1527 FindConstant(I.getOperand(i));
1528 }
1529 }
1530
1531 continue;
1532 } else if (isa<InsertElementInst>(I)) {
1533 // Handle InsertElement with <4 x i8> specially.
1534 Type *CompositeTy = I.getOperand(0)->getType();
1535 if (is4xi8vec(CompositeTy)) {
1536 LLVMContext &Context = CompositeTy->getContext();
1537 if (isa<Constant>(I.getOperand(0))) {
1538 FindConstant(I.getOperand(0));
1539 }
1540
1541 if (isa<Constant>(I.getOperand(1))) {
1542 FindConstant(I.getOperand(1));
1543 }
1544
1545 // Add mask constant 0xFF.
1546 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1547 FindConstant(CstFF);
1548
1549 // Add shift amount constant.
1550 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1551 uint64_t Idx = CI->getZExtValue();
1552 Constant *CstShiftAmount =
1553 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1554 FindConstant(CstShiftAmount);
1555 }
1556
1557 continue;
1558 }
1559
1560 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1561 // Ignore constant for index of InsertElement instruction.
1562 if (i == 2) {
1563 continue;
1564 }
1565
1566 if (isa<Constant>(I.getOperand(i)) &&
1567 !isa<GlobalValue>(I.getOperand(i))) {
1568 FindConstant(I.getOperand(i));
1569 }
1570 }
1571
1572 continue;
1573 } else if (isa<ExtractElementInst>(I)) {
1574 // Handle ExtractElement with <4 x i8> specially.
1575 Type *CompositeTy = I.getOperand(0)->getType();
1576 if (is4xi8vec(CompositeTy)) {
1577 LLVMContext &Context = CompositeTy->getContext();
1578 if (isa<Constant>(I.getOperand(0))) {
1579 FindConstant(I.getOperand(0));
1580 }
1581
1582 // Add mask constant 0xFF.
1583 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1584 FindConstant(CstFF);
1585
1586 // Add shift amount constant.
1587 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1588 uint64_t Idx = CI->getZExtValue();
1589 Constant *CstShiftAmount =
1590 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1591 FindConstant(CstShiftAmount);
1592 } else {
1593 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1594 FindConstant(Cst8);
1595 }
1596
1597 continue;
1598 }
1599
1600 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1601 // Ignore constant for index of ExtractElement instruction.
1602 if (i == 1) {
1603 continue;
1604 }
1605
1606 if (isa<Constant>(I.getOperand(i)) &&
1607 !isa<GlobalValue>(I.getOperand(i))) {
1608 FindConstant(I.getOperand(i));
1609 }
1610 }
1611
1612 continue;
1613 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1614 // We special case for Xor where the type is i1 and one of the arguments is a constant 1 (true), this is an OpLogicalNot in SPIR-V, and we don't need the constant
1615 bool foundConstantTrue = false;
1616 for (Use &Op : I.operands()) {
1617 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1618 auto CI = cast<ConstantInt>(Op);
1619
1620 if (CI->isZero() || foundConstantTrue) {
1621 // If we already found the true constant, we might (probably only on -O0) have an OpLogicalNot which is taking a constant argument, so discover it anyway.
1622 FindConstant(Op);
1623 } else {
1624 foundConstantTrue = true;
1625 }
1626 }
1627 }
1628
1629 continue;
David Netod2de94a2017-08-28 17:27:47 -04001630 } else if (isa<TruncInst>(I)) {
1631 // For truncation to i8 we mask against 255.
1632 Type *ToTy = I.getType();
1633 if (8u == ToTy->getPrimitiveSizeInBits()) {
1634 LLVMContext &Context = ToTy->getContext();
1635 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1636 FindConstant(Cst255);
1637 }
1638 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001639 } else if (isa<AtomicRMWInst>(I)) {
1640 LLVMContext &Context = I.getContext();
1641
1642 FindConstant(
1643 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1644 FindConstant(ConstantInt::get(
1645 Type::getInt32Ty(Context),
1646 spv::MemorySemanticsUniformMemoryMask |
1647 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001648 }
1649
1650 for (Use &Op : I.operands()) {
1651 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1652 FindConstant(Op);
1653 }
1654 }
1655 }
1656 }
1657}
1658
1659void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001660 ValueList &CstList = getConstantList();
1661
David Netofb9a7972017-08-25 17:08:24 -04001662 // If V is already tracked, ignore it.
1663 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001664 return;
1665 }
1666
David Neto862b7d82018-06-14 18:48:37 -04001667 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1668 return;
1669 }
1670
David Neto22f144c2017-06-12 14:26:21 -04001671 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001672 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001673
1674 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001675 if (is4xi8vec(CstTy)) {
1676 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001677 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001678 }
1679 }
1680
1681 if (Cst->getNumOperands()) {
1682 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1683 ++I) {
1684 FindConstant(*I);
1685 }
1686
David Netofb9a7972017-08-25 17:08:24 -04001687 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001688 return;
1689 } else if (const ConstantDataSequential *CDS =
1690 dyn_cast<ConstantDataSequential>(Cst)) {
1691 // Add constants for each element to constant list.
1692 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1693 Constant *EleCst = CDS->getElementAsConstant(i);
1694 FindConstant(EleCst);
1695 }
1696 }
1697
1698 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001699 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001700 }
1701}
1702
1703spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1704 switch (AddrSpace) {
1705 default:
1706 llvm_unreachable("Unsupported OpenCL address space");
1707 case AddressSpace::Private:
1708 return spv::StorageClassFunction;
1709 case AddressSpace::Global:
1710 case AddressSpace::Constant:
1711 return spv::StorageClassStorageBuffer;
1712 case AddressSpace::Input:
1713 return spv::StorageClassInput;
1714 case AddressSpace::Local:
1715 return spv::StorageClassWorkgroup;
1716 case AddressSpace::UniformConstant:
1717 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001718 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001719 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001720 case AddressSpace::ModuleScopePrivate:
1721 return spv::StorageClassPrivate;
1722 }
1723}
1724
David Neto862b7d82018-06-14 18:48:37 -04001725spv::StorageClass
1726SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1727 switch (arg_kind) {
1728 case clspv::ArgKind::Buffer:
1729 return spv::StorageClassStorageBuffer;
1730 case clspv::ArgKind::Pod:
1731 return clspv::Option::PodArgsInUniformBuffer()
1732 ? spv::StorageClassUniform
1733 : spv::StorageClassStorageBuffer;
1734 case clspv::ArgKind::Local:
1735 return spv::StorageClassWorkgroup;
1736 case clspv::ArgKind::ReadOnlyImage:
1737 case clspv::ArgKind::WriteOnlyImage:
1738 case clspv::ArgKind::Sampler:
1739 return spv::StorageClassUniformConstant;
1740 }
1741}
1742
David Neto22f144c2017-06-12 14:26:21 -04001743spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1744 return StringSwitch<spv::BuiltIn>(Name)
1745 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1746 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1747 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1748 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1749 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1750 .Default(spv::BuiltInMax);
1751}
1752
1753void SPIRVProducerPass::GenerateExtInstImport() {
1754 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1755 uint32_t &ExtInstImportID = getOpExtInstImportID();
1756
1757 //
1758 // Generate OpExtInstImport.
1759 //
1760 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001761 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001762 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1763 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001764}
1765
David Netoc6f3ab22018-04-06 18:02:31 -04001766void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001767 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1768 ValueMapType &VMap = getValueMap();
1769 ValueMapType &AllocatedVMap = getAllocatedValueMap();
David Neto22f144c2017-06-12 14:26:21 -04001770
1771 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1772 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1773 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1774
1775 for (Type *Ty : getTypeList()) {
1776 // Update TypeMap with nextID for reference later.
1777 TypeMap[Ty] = nextID;
1778
1779 switch (Ty->getTypeID()) {
1780 default: {
1781 Ty->print(errs());
1782 llvm_unreachable("Unsupported type???");
1783 break;
1784 }
1785 case Type::MetadataTyID:
1786 case Type::LabelTyID: {
1787 // Ignore these types.
1788 break;
1789 }
1790 case Type::PointerTyID: {
1791 PointerType *PTy = cast<PointerType>(Ty);
1792 unsigned AddrSpace = PTy->getAddressSpace();
1793
1794 // For the purposes of our Vulkan SPIR-V type system, constant and global
1795 // are conflated.
1796 bool UseExistingOpTypePointer = false;
1797 if (AddressSpace::Constant == AddrSpace) {
1798 AddrSpace = AddressSpace::Global;
1799
1800 // Check to see if we already created this type (for instance, if we had
1801 // a constant <type>* and a global <type>*, the type would be created by
1802 // one of these types, and shared by both).
1803 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1804 if (0 < TypeMap.count(GlobalTy)) {
1805 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001806 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001807 break;
1808 }
1809 } else if (AddressSpace::Global == AddrSpace) {
1810 AddrSpace = AddressSpace::Constant;
1811
1812 // Check to see if we already created this type (for instance, if we had
1813 // a constant <type>* and a global <type>*, the type would be created by
1814 // one of these types, and shared by both).
1815 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1816 if (0 < TypeMap.count(ConstantTy)) {
1817 TypeMap[PTy] = TypeMap[ConstantTy];
1818 UseExistingOpTypePointer = true;
1819 }
1820 }
1821
David Neto862b7d82018-06-14 18:48:37 -04001822 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001823
David Neto862b7d82018-06-14 18:48:37 -04001824 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001825 //
1826 // Generate OpTypePointer.
1827 //
1828
1829 // OpTypePointer
1830 // Ops[0] = Storage Class
1831 // Ops[1] = Element Type ID
1832 SPIRVOperandList Ops;
1833
David Neto257c3892018-04-11 13:19:45 -04001834 Ops << MkNum(GetStorageClass(AddrSpace))
1835 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001836
David Neto87846742018-04-11 17:36:22 -04001837 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001838 SPIRVInstList.push_back(Inst);
1839 }
David Neto22f144c2017-06-12 14:26:21 -04001840 break;
1841 }
1842 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001843 StructType *STy = cast<StructType>(Ty);
1844
1845 // Handle sampler type.
1846 if (STy->isOpaque()) {
1847 if (STy->getName().equals("opencl.sampler_t")) {
1848 //
1849 // Generate OpTypeSampler
1850 //
1851 // Empty Ops.
1852 SPIRVOperandList Ops;
1853
David Neto87846742018-04-11 17:36:22 -04001854 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001855 SPIRVInstList.push_back(Inst);
1856 break;
1857 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1858 STy->getName().equals("opencl.image2d_wo_t") ||
1859 STy->getName().equals("opencl.image3d_ro_t") ||
1860 STy->getName().equals("opencl.image3d_wo_t")) {
1861 //
1862 // Generate OpTypeImage
1863 //
1864 // Ops[0] = Sampled Type ID
1865 // Ops[1] = Dim ID
1866 // Ops[2] = Depth (Literal Number)
1867 // Ops[3] = Arrayed (Literal Number)
1868 // Ops[4] = MS (Literal Number)
1869 // Ops[5] = Sampled (Literal Number)
1870 // Ops[6] = Image Format ID
1871 //
1872 SPIRVOperandList Ops;
1873
1874 // TODO: Changed Sampled Type according to situations.
1875 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001876 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001877
1878 spv::Dim DimID = spv::Dim2D;
1879 if (STy->getName().equals("opencl.image3d_ro_t") ||
1880 STy->getName().equals("opencl.image3d_wo_t")) {
1881 DimID = spv::Dim3D;
1882 }
David Neto257c3892018-04-11 13:19:45 -04001883 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001884
1885 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001886 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001887
1888 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001889 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001890
1891 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001892 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001893
1894 // TODO: Set up Sampled.
1895 //
1896 // From Spec
1897 //
1898 // 0 indicates this is only known at run time, not at compile time
1899 // 1 indicates will be used with sampler
1900 // 2 indicates will be used without a sampler (a storage image)
1901 uint32_t Sampled = 1;
1902 if (STy->getName().equals("opencl.image2d_wo_t") ||
1903 STy->getName().equals("opencl.image3d_wo_t")) {
1904 Sampled = 2;
1905 }
David Neto257c3892018-04-11 13:19:45 -04001906 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001907
1908 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001909 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001910
David Neto87846742018-04-11 17:36:22 -04001911 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001912 SPIRVInstList.push_back(Inst);
1913 break;
1914 }
1915 }
1916
1917 //
1918 // Generate OpTypeStruct
1919 //
1920 // Ops[0] ... Ops[n] = Member IDs
1921 SPIRVOperandList Ops;
1922
1923 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001924 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001925 }
1926
David Neto22f144c2017-06-12 14:26:21 -04001927 uint32_t STyID = nextID;
1928
David Neto87846742018-04-11 17:36:22 -04001929 auto *Inst =
1930 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001931 SPIRVInstList.push_back(Inst);
1932
1933 // Generate OpMemberDecorate.
1934 auto DecoInsertPoint =
1935 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1936 [](SPIRVInstruction *Inst) -> bool {
1937 return Inst->getOpcode() != spv::OpDecorate &&
1938 Inst->getOpcode() != spv::OpMemberDecorate &&
1939 Inst->getOpcode() != spv::OpExtInstImport;
1940 });
1941
David Netoc463b372017-08-10 15:32:21 -04001942 const auto StructLayout = DL.getStructLayout(STy);
1943
David Neto862b7d82018-06-14 18:48:37 -04001944 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001945 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1946 MemberIdx++) {
1947 // Ops[0] = Structure Type ID
1948 // Ops[1] = Member Index(Literal Number)
1949 // Ops[2] = Decoration (Offset)
1950 // Ops[3] = Byte Offset (Literal Number)
1951 Ops.clear();
1952
David Neto257c3892018-04-11 13:19:45 -04001953 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001954
David Netoc463b372017-08-10 15:32:21 -04001955 const auto ByteOffset =
1956 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001957 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001958
David Neto87846742018-04-11 17:36:22 -04001959 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001960 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001961 }
1962
1963 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001964 if (StructTypesNeedingBlock.idFor(STy)) {
1965 Ops.clear();
1966 // Use Block decorations with StorageBuffer storage class.
1967 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001968
David Neto862b7d82018-06-14 18:48:37 -04001969 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1970 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001971 }
1972 break;
1973 }
1974 case Type::IntegerTyID: {
1975 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1976
1977 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001978 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001979 SPIRVInstList.push_back(Inst);
1980 } else {
1981 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001982 // No matter what LLVM type is requested first, always alias the
1983 // second one's SPIR-V type to be the same as the one we generated
1984 // first.
Neil Henning39672102017-09-29 14:33:13 +01001985 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001986 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001987 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001988 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001989 } else if (BitWidth == 32) {
1990 aliasToWidth = 8;
1991 }
1992 if (aliasToWidth) {
1993 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1994 auto where = TypeMap.find(otherType);
1995 if (where == TypeMap.end()) {
1996 // Go ahead and make it, but also map the other type to it.
1997 TypeMap[otherType] = nextID;
1998 } else {
1999 // Alias this SPIR-V type the existing type.
2000 TypeMap[Ty] = where->second;
2001 break;
2002 }
David Neto22f144c2017-06-12 14:26:21 -04002003 }
2004
David Neto257c3892018-04-11 13:19:45 -04002005 SPIRVOperandList Ops;
2006 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002007
2008 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002009 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002010 }
2011 break;
2012 }
2013 case Type::HalfTyID:
2014 case Type::FloatTyID:
2015 case Type::DoubleTyID: {
2016 SPIRVOperand *WidthOp = new SPIRVOperand(
2017 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2018
2019 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002020 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002021 break;
2022 }
2023 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002024 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002025 const uint64_t Length = ArrTy->getArrayNumElements();
2026 if (Length == 0) {
2027 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002028
David Neto862b7d82018-06-14 18:48:37 -04002029 // Only generate the type once.
2030 // TODO(dneto): Can it ever be generated more than once?
2031 // Doesn't LLVM type uniqueness guarantee we'll only see this
2032 // once?
2033 Type *EleTy = ArrTy->getArrayElementType();
2034 if (OpRuntimeTyMap.count(EleTy) == 0) {
2035 uint32_t OpTypeRuntimeArrayID = nextID;
2036 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002037
David Neto862b7d82018-06-14 18:48:37 -04002038 //
2039 // Generate OpTypeRuntimeArray.
2040 //
David Neto22f144c2017-06-12 14:26:21 -04002041
David Neto862b7d82018-06-14 18:48:37 -04002042 // OpTypeRuntimeArray
2043 // Ops[0] = Element Type ID
2044 SPIRVOperandList Ops;
2045 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002046
David Neto862b7d82018-06-14 18:48:37 -04002047 SPIRVInstList.push_back(
2048 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002049
David Neto862b7d82018-06-14 18:48:37 -04002050 if (Hack_generate_runtime_array_stride_early) {
2051 // Generate OpDecorate.
2052 auto DecoInsertPoint = std::find_if(
2053 SPIRVInstList.begin(), SPIRVInstList.end(),
2054 [](SPIRVInstruction *Inst) -> bool {
2055 return Inst->getOpcode() != spv::OpDecorate &&
2056 Inst->getOpcode() != spv::OpMemberDecorate &&
2057 Inst->getOpcode() != spv::OpExtInstImport;
2058 });
David Neto22f144c2017-06-12 14:26:21 -04002059
David Neto862b7d82018-06-14 18:48:37 -04002060 // Ops[0] = Target ID
2061 // Ops[1] = Decoration (ArrayStride)
2062 // Ops[2] = Stride Number(Literal Number)
2063 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002064
David Neto862b7d82018-06-14 18:48:37 -04002065 Ops << MkId(OpTypeRuntimeArrayID)
2066 << MkNum(spv::DecorationArrayStride)
2067 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04002068
David Neto862b7d82018-06-14 18:48:37 -04002069 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2070 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2071 }
2072 }
David Neto22f144c2017-06-12 14:26:21 -04002073
David Neto862b7d82018-06-14 18:48:37 -04002074 } else {
David Neto22f144c2017-06-12 14:26:21 -04002075
David Neto862b7d82018-06-14 18:48:37 -04002076 //
2077 // Generate OpConstant and OpTypeArray.
2078 //
2079
2080 //
2081 // Generate OpConstant for array length.
2082 //
2083 // Ops[0] = Result Type ID
2084 // Ops[1] .. Ops[n] = Values LiteralNumber
2085 SPIRVOperandList Ops;
2086
2087 Type *LengthTy = Type::getInt32Ty(Context);
2088 uint32_t ResTyID = lookupType(LengthTy);
2089 Ops << MkId(ResTyID);
2090
2091 assert(Length < UINT32_MAX);
2092 Ops << MkNum(static_cast<uint32_t>(Length));
2093
2094 // Add constant for length to constant list.
2095 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2096 AllocatedVMap[CstLength] = nextID;
2097 VMap[CstLength] = nextID;
2098 uint32_t LengthID = nextID;
2099
2100 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2101 SPIRVInstList.push_back(CstInst);
2102
2103 // Remember to generate ArrayStride later
2104 getTypesNeedingArrayStride().insert(Ty);
2105
2106 //
2107 // Generate OpTypeArray.
2108 //
2109 // Ops[0] = Element Type ID
2110 // Ops[1] = Array Length Constant ID
2111 Ops.clear();
2112
2113 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2114 Ops << MkId(EleTyID) << MkId(LengthID);
2115
2116 // Update TypeMap with nextID.
2117 TypeMap[Ty] = nextID;
2118
2119 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2120 SPIRVInstList.push_back(ArrayInst);
2121 }
David Neto22f144c2017-06-12 14:26:21 -04002122 break;
2123 }
2124 case Type::VectorTyID: {
2125 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002126 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2127 if (Ty->getVectorNumElements() == 4) {
2128 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2129 break;
2130 } else {
2131 Ty->print(errs());
2132 llvm_unreachable("Support above i8 vector type");
2133 }
2134 }
2135
2136 // Ops[0] = Component Type ID
2137 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002138 SPIRVOperandList Ops;
2139 Ops << MkId(lookupType(Ty->getVectorElementType()))
2140 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002141
David Neto87846742018-04-11 17:36:22 -04002142 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002143 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002144 break;
2145 }
2146 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002147 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002148 SPIRVInstList.push_back(Inst);
2149 break;
2150 }
2151 case Type::FunctionTyID: {
2152 // Generate SPIRV instruction for function type.
2153 FunctionType *FTy = cast<FunctionType>(Ty);
2154
2155 // Ops[0] = Return Type ID
2156 // Ops[1] ... Ops[n] = Parameter Type IDs
2157 SPIRVOperandList Ops;
2158
2159 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002160 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002161
2162 // Find SPIRV instructions for parameter types
2163 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2164 // Find SPIRV instruction for parameter type.
2165 auto ParamTy = FTy->getParamType(k);
2166 if (ParamTy->isPointerTy()) {
2167 auto PointeeTy = ParamTy->getPointerElementType();
2168 if (PointeeTy->isStructTy() &&
2169 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2170 ParamTy = PointeeTy;
2171 }
2172 }
2173
David Netoc6f3ab22018-04-06 18:02:31 -04002174 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002175 }
2176
David Neto87846742018-04-11 17:36:22 -04002177 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002178 SPIRVInstList.push_back(Inst);
2179 break;
2180 }
2181 }
2182 }
2183
2184 // Generate OpTypeSampledImage.
2185 TypeMapType &OpImageTypeMap = getImageTypeMap();
2186 for (auto &ImageType : OpImageTypeMap) {
2187 //
2188 // Generate OpTypeSampledImage.
2189 //
2190 // Ops[0] = Image Type ID
2191 //
2192 SPIRVOperandList Ops;
2193
2194 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002195 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002196
2197 // Update OpImageTypeMap.
2198 ImageType.second = nextID;
2199
David Neto87846742018-04-11 17:36:22 -04002200 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002201 SPIRVInstList.push_back(Inst);
2202 }
David Netoc6f3ab22018-04-06 18:02:31 -04002203
2204 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002205 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2206 ++spec_id) {
2207 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002208
2209 // Generate the spec constant.
2210 SPIRVOperandList Ops;
2211 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002212 SPIRVInstList.push_back(
2213 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002214
2215 // Generate the array type.
2216 Ops.clear();
2217 // The element type must have been created.
2218 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2219 assert(elem_ty_id);
2220 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2221
2222 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002223 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002224
2225 Ops.clear();
2226 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002227 SPIRVInstList.push_back(new SPIRVInstruction(
2228 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002229 }
David Neto22f144c2017-06-12 14:26:21 -04002230}
2231
2232void SPIRVProducerPass::GenerateSPIRVConstants() {
2233 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2234 ValueMapType &VMap = getValueMap();
2235 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2236 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002237 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002238
2239 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002240 // UniqueVector ids are 1-based.
2241 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002242
2243 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002244 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002245 continue;
2246 }
2247
David Netofb9a7972017-08-25 17:08:24 -04002248 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002249 VMap[Cst] = nextID;
2250
2251 //
2252 // Generate OpConstant.
2253 //
2254
2255 // Ops[0] = Result Type ID
2256 // Ops[1] .. Ops[n] = Values LiteralNumber
2257 SPIRVOperandList Ops;
2258
David Neto257c3892018-04-11 13:19:45 -04002259 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002260
2261 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002262 spv::Op Opcode = spv::OpNop;
2263
2264 if (isa<UndefValue>(Cst)) {
2265 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002266 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002267 if (hack_undef && IsTypeNullable(Cst->getType())) {
2268 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002269 }
David Neto22f144c2017-06-12 14:26:21 -04002270 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2271 unsigned BitWidth = CI->getBitWidth();
2272 if (BitWidth == 1) {
2273 // If the bitwidth of constant is 1, generate OpConstantTrue or
2274 // OpConstantFalse.
2275 if (CI->getZExtValue()) {
2276 // Ops[0] = Result Type ID
2277 Opcode = spv::OpConstantTrue;
2278 } else {
2279 // Ops[0] = Result Type ID
2280 Opcode = spv::OpConstantFalse;
2281 }
David Neto22f144c2017-06-12 14:26:21 -04002282 } else {
2283 auto V = CI->getZExtValue();
2284 LiteralNum.push_back(V & 0xFFFFFFFF);
2285
2286 if (BitWidth > 32) {
2287 LiteralNum.push_back(V >> 32);
2288 }
2289
2290 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002291
David Neto257c3892018-04-11 13:19:45 -04002292 Ops << MkInteger(LiteralNum);
2293
2294 if (BitWidth == 32 && V == 0) {
2295 constant_i32_zero_id_ = nextID;
2296 }
David Neto22f144c2017-06-12 14:26:21 -04002297 }
2298 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2299 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2300 Type *CFPTy = CFP->getType();
2301 if (CFPTy->isFloatTy()) {
2302 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2303 } else {
2304 CFPTy->print(errs());
2305 llvm_unreachable("Implement this ConstantFP Type");
2306 }
2307
2308 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002309
David Neto257c3892018-04-11 13:19:45 -04002310 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002311 } else if (isa<ConstantDataSequential>(Cst) &&
2312 cast<ConstantDataSequential>(Cst)->isString()) {
2313 Cst->print(errs());
2314 llvm_unreachable("Implement this Constant");
2315
2316 } else if (const ConstantDataSequential *CDS =
2317 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002318 // Let's convert <4 x i8> constant to int constant specially.
2319 // This case occurs when all the values are specified as constant
2320 // ints.
2321 Type *CstTy = Cst->getType();
2322 if (is4xi8vec(CstTy)) {
2323 LLVMContext &Context = CstTy->getContext();
2324
2325 //
2326 // Generate OpConstant with OpTypeInt 32 0.
2327 //
Neil Henning39672102017-09-29 14:33:13 +01002328 uint32_t IntValue = 0;
2329 for (unsigned k = 0; k < 4; k++) {
2330 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002331 IntValue = (IntValue << 8) | (Val & 0xffu);
2332 }
2333
2334 Type *i32 = Type::getInt32Ty(Context);
2335 Constant *CstInt = ConstantInt::get(i32, IntValue);
2336 // If this constant is already registered on VMap, use it.
2337 if (VMap.count(CstInt)) {
2338 uint32_t CstID = VMap[CstInt];
2339 VMap[Cst] = CstID;
2340 continue;
2341 }
2342
David Neto257c3892018-04-11 13:19:45 -04002343 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002344
David Neto87846742018-04-11 17:36:22 -04002345 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002346 SPIRVInstList.push_back(CstInst);
2347
2348 continue;
2349 }
2350
2351 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002352 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2353 Constant *EleCst = CDS->getElementAsConstant(k);
2354 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002355 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002356 }
2357
2358 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002359 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2360 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002361 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002362 Type *CstTy = Cst->getType();
2363 if (is4xi8vec(CstTy)) {
2364 LLVMContext &Context = CstTy->getContext();
2365
2366 //
2367 // Generate OpConstant with OpTypeInt 32 0.
2368 //
Neil Henning39672102017-09-29 14:33:13 +01002369 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002370 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2371 I != E; ++I) {
2372 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002373 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002374 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2375 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002376 }
David Neto49351ac2017-08-26 17:32:20 -04002377 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002378 }
2379
David Neto49351ac2017-08-26 17:32:20 -04002380 Type *i32 = Type::getInt32Ty(Context);
2381 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002382 // If this constant is already registered on VMap, use it.
2383 if (VMap.count(CstInt)) {
2384 uint32_t CstID = VMap[CstInt];
2385 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002386 continue;
David Neto22f144c2017-06-12 14:26:21 -04002387 }
2388
David Neto257c3892018-04-11 13:19:45 -04002389 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002390
David Neto87846742018-04-11 17:36:22 -04002391 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002392 SPIRVInstList.push_back(CstInst);
2393
David Neto19a1bad2017-08-25 15:01:41 -04002394 continue;
David Neto22f144c2017-06-12 14:26:21 -04002395 }
2396
2397 // We use a constant composite in SPIR-V for our constant aggregate in
2398 // LLVM.
2399 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002400
2401 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2402 // Look up the ID of the element of this aggregate (which we will
2403 // previously have created a constant for).
2404 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2405
2406 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002407 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002408 }
2409 } else if (Cst->isNullValue()) {
2410 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002411 } else {
2412 Cst->print(errs());
2413 llvm_unreachable("Unsupported Constant???");
2414 }
2415
David Neto87846742018-04-11 17:36:22 -04002416 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002417 SPIRVInstList.push_back(CstInst);
2418 }
2419}
2420
2421void SPIRVProducerPass::GenerateSamplers(Module &M) {
2422 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2423 ValueMapType &VMap = getValueMap();
2424
David Neto862b7d82018-06-14 18:48:37 -04002425 auto& sampler_map = getSamplerMap();
2426 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002427 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002428 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2429 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002430
David Neto862b7d82018-06-14 18:48:37 -04002431 // We might have samplers in the sampler map that are not used
2432 // in the translation unit. We need to allocate variables
2433 // for them and bindings too.
2434 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002435
David Neto862b7d82018-06-14 18:48:37 -04002436 auto* var_fn = M.getFunction("clspv.sampler.var.literal");
2437 if (!var_fn) return;
2438 for (auto user : var_fn->users()) {
2439 // Populate SamplerLiteralToDescriptorSetMap and
2440 // SamplerLiteralToBindingMap.
2441 //
2442 // Look for calls like
2443 // call %opencl.sampler_t addrspace(2)*
2444 // @clspv.sampler.var.literal(
2445 // i32 descriptor,
2446 // i32 binding,
2447 // i32 index-into-sampler-map)
2448 if (auto* call = dyn_cast<CallInst>(user)) {
2449 const auto index_into_sampler_map =
2450 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue();
2451 if (index_into_sampler_map >= sampler_map.size()) {
2452 errs() << "Out of bounds index to sampler map: " << index_into_sampler_map;
2453 llvm_unreachable("bad sampler init: out of bounds");
2454 }
2455
2456 auto sampler_value = sampler_map[index_into_sampler_map].first;
2457 const auto descriptor_set = static_cast<unsigned>(
2458 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2459 const auto binding = static_cast<unsigned>(
2460 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2461
2462 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2463 SamplerLiteralToBindingMap[sampler_value] = binding;
2464 used_bindings.insert(binding);
2465 }
2466 }
2467
2468 unsigned index = 0;
2469 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002470 // Generate OpVariable.
2471 //
2472 // GIDOps[0] : Result Type ID
2473 // GIDOps[1] : Storage Class
2474 SPIRVOperandList Ops;
2475
David Neto257c3892018-04-11 13:19:45 -04002476 Ops << MkId(lookupType(SamplerTy))
2477 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002478
David Neto862b7d82018-06-14 18:48:37 -04002479 auto sampler_var_id = nextID++;
2480 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002481 SPIRVInstList.push_back(Inst);
2482
David Neto862b7d82018-06-14 18:48:37 -04002483 SamplerMapIndexToIDMap[index] = sampler_var_id;
2484 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002485
2486 // Find Insert Point for OpDecorate.
2487 auto DecoInsertPoint =
2488 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2489 [](SPIRVInstruction *Inst) -> bool {
2490 return Inst->getOpcode() != spv::OpDecorate &&
2491 Inst->getOpcode() != spv::OpMemberDecorate &&
2492 Inst->getOpcode() != spv::OpExtInstImport;
2493 });
2494
2495 // Ops[0] = Target ID
2496 // Ops[1] = Decoration (DescriptorSet)
2497 // Ops[2] = LiteralNumber according to Decoration
2498 Ops.clear();
2499
David Neto862b7d82018-06-14 18:48:37 -04002500 unsigned descriptor_set;
2501 unsigned binding;
2502 if(SamplerLiteralToBindingMap.find(SamplerLiteral.first) == SamplerLiteralToBindingMap.end()) {
2503 // This sampler is not actually used. Find the next one.
2504 for (binding = 0; used_bindings.count(binding); binding++)
2505 ;
2506 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2507 used_bindings.insert(binding);
2508 } else {
2509 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2510 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2511 }
2512
2513 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2514 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto44795152017-07-13 15:45:28 -04002516 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002517 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002518 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002519
David Neto87846742018-04-11 17:36:22 -04002520 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002521 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2522
2523 // Ops[0] = Target ID
2524 // Ops[1] = Decoration (Binding)
2525 // Ops[2] = LiteralNumber according to Decoration
2526 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002527 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2528 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002529
David Neto87846742018-04-11 17:36:22 -04002530 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002531 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002532
2533 index++;
David Neto22f144c2017-06-12 14:26:21 -04002534 }
David Neto862b7d82018-06-14 18:48:37 -04002535}
David Neto22f144c2017-06-12 14:26:21 -04002536
David Neto862b7d82018-06-14 18:48:37 -04002537void SPIRVProducerPass::GenerateResourceVars(Module &M) {
2538 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2539 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002540
David Neto862b7d82018-06-14 18:48:37 -04002541 // Generate variables. Make one for each of resource var info object.
2542 for (auto *info : ModuleOrderedResourceVars) {
2543 Type *type = info->var_fn->getReturnType();
2544 // Remap the address space for opaque types.
2545 switch (info->arg_kind) {
2546 case clspv::ArgKind::Sampler:
2547 case clspv::ArgKind::ReadOnlyImage:
2548 case clspv::ArgKind::WriteOnlyImage:
2549 type = PointerType::get(type->getPointerElementType(),
2550 clspv::AddressSpace::UniformConstant);
2551 break;
2552 default:
2553 break;
2554 }
David Neto22f144c2017-06-12 14:26:21 -04002555
David Neto862b7d82018-06-14 18:48:37 -04002556 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002557
David Neto862b7d82018-06-14 18:48:37 -04002558 const auto type_id = lookupType(type);
2559 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2560 SPIRVOperandList Ops;
2561 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002562
David Neto862b7d82018-06-14 18:48:37 -04002563 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2564 SPIRVInstList.push_back(Inst);
2565
2566 // Map calls to the variable-builtin-function.
2567 for (auto &U : info->var_fn->uses()) {
2568 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2569 const auto set = unsigned(
2570 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2571 const auto binding = unsigned(
2572 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2573 if (set == info->descriptor_set && binding == info->binding) {
2574 switch (info->arg_kind) {
2575 case clspv::ArgKind::Buffer:
2576 case clspv::ArgKind::Pod:
2577 // The call maps to the variable directly.
2578 VMap[call] = info->var_id;
2579 break;
2580 case clspv::ArgKind::Sampler:
2581 case clspv::ArgKind::ReadOnlyImage:
2582 case clspv::ArgKind::WriteOnlyImage:
2583 // The call maps to a load we generate later.
2584 ResourceVarDeferredLoadCalls[call] = info->var_id;
2585 break;
2586 default:
2587 llvm_unreachable("Unhandled arg kind");
2588 }
2589 }
David Neto22f144c2017-06-12 14:26:21 -04002590 }
David Neto862b7d82018-06-14 18:48:37 -04002591 }
2592 }
David Neto22f144c2017-06-12 14:26:21 -04002593
David Neto862b7d82018-06-14 18:48:37 -04002594 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002595
David Neto862b7d82018-06-14 18:48:37 -04002596 // Find Insert Point for OpDecorate.
2597 auto DecoInsertPoint =
2598 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2599 [](SPIRVInstruction *Inst) -> bool {
2600 return Inst->getOpcode() != spv::OpDecorate &&
2601 Inst->getOpcode() != spv::OpMemberDecorate &&
2602 Inst->getOpcode() != spv::OpExtInstImport;
2603 });
2604
2605 SPIRVOperandList Ops;
2606 for (auto *info : ModuleOrderedResourceVars) {
2607 // Decorate with DescriptorSet and Binding.
2608 Ops.clear();
2609 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2610 << MkNum(info->descriptor_set);
2611 SPIRVInstList.insert(DecoInsertPoint,
2612 new SPIRVInstruction(spv::OpDecorate, Ops));
2613
2614 Ops.clear();
2615 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2616 << MkNum(info->binding);
2617 SPIRVInstList.insert(DecoInsertPoint,
2618 new SPIRVInstruction(spv::OpDecorate, Ops));
2619
2620 // Generate NonWritable and NonReadable
2621 switch (info->arg_kind) {
2622 case clspv::ArgKind::Buffer:
2623 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2624 clspv::AddressSpace::Constant) {
2625 Ops.clear();
2626 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2627 SPIRVInstList.insert(DecoInsertPoint,
2628 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002629 }
David Neto862b7d82018-06-14 18:48:37 -04002630 break;
2631 case clspv::ArgKind::ReadOnlyImage:
2632 Ops.clear();
2633 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2634 SPIRVInstList.insert(DecoInsertPoint,
2635 new SPIRVInstruction(spv::OpDecorate, Ops));
2636 break;
2637 case clspv::ArgKind::WriteOnlyImage:
2638 Ops.clear();
2639 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2640 SPIRVInstList.insert(DecoInsertPoint,
2641 new SPIRVInstruction(spv::OpDecorate, Ops));
2642 break;
2643 default:
2644 break;
David Neto22f144c2017-06-12 14:26:21 -04002645 }
2646 }
2647}
2648
2649void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto78383442018-06-15 20:31:56 -04002650 Module& M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002651 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2652 ValueMapType &VMap = getValueMap();
2653 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002654 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002655
2656 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2657 Type *Ty = GV.getType();
2658 PointerType *PTy = cast<PointerType>(Ty);
2659
2660 uint32_t InitializerID = 0;
2661
2662 // Workgroup size is handled differently (it goes into a constant)
2663 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2664 std::vector<bool> HasMDVec;
2665 uint32_t PrevXDimCst = 0xFFFFFFFF;
2666 uint32_t PrevYDimCst = 0xFFFFFFFF;
2667 uint32_t PrevZDimCst = 0xFFFFFFFF;
2668 for (Function &Func : *GV.getParent()) {
2669 if (Func.isDeclaration()) {
2670 continue;
2671 }
2672
2673 // We only need to check kernels.
2674 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2675 continue;
2676 }
2677
2678 if (const MDNode *MD =
2679 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2680 uint32_t CurXDimCst = static_cast<uint32_t>(
2681 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2682 uint32_t CurYDimCst = static_cast<uint32_t>(
2683 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2684 uint32_t CurZDimCst = static_cast<uint32_t>(
2685 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2686
2687 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2688 PrevZDimCst == 0xFFFFFFFF) {
2689 PrevXDimCst = CurXDimCst;
2690 PrevYDimCst = CurYDimCst;
2691 PrevZDimCst = CurZDimCst;
2692 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2693 CurZDimCst != PrevZDimCst) {
2694 llvm_unreachable(
2695 "reqd_work_group_size must be the same across all kernels");
2696 } else {
2697 continue;
2698 }
2699
2700 //
2701 // Generate OpConstantComposite.
2702 //
2703 // Ops[0] : Result Type ID
2704 // Ops[1] : Constant size for x dimension.
2705 // Ops[2] : Constant size for y dimension.
2706 // Ops[3] : Constant size for z dimension.
2707 SPIRVOperandList Ops;
2708
2709 uint32_t XDimCstID =
2710 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2711 uint32_t YDimCstID =
2712 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2713 uint32_t ZDimCstID =
2714 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2715
2716 InitializerID = nextID;
2717
David Neto257c3892018-04-11 13:19:45 -04002718 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2719 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002720
David Neto87846742018-04-11 17:36:22 -04002721 auto *Inst =
2722 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002723 SPIRVInstList.push_back(Inst);
2724
2725 HasMDVec.push_back(true);
2726 } else {
2727 HasMDVec.push_back(false);
2728 }
2729 }
2730
2731 // Check all kernels have same definitions for work_group_size.
2732 bool HasMD = false;
2733 if (!HasMDVec.empty()) {
2734 HasMD = HasMDVec[0];
2735 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2736 if (HasMD != HasMDVec[i]) {
2737 llvm_unreachable(
2738 "Kernels should have consistent work group size definition");
2739 }
2740 }
2741 }
2742
2743 // If all kernels do not have metadata for reqd_work_group_size, generate
2744 // OpSpecConstants for x/y/z dimension.
2745 if (!HasMD) {
2746 //
2747 // Generate OpSpecConstants for x/y/z dimension.
2748 //
2749 // Ops[0] : Result Type ID
2750 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2751 uint32_t XDimCstID = 0;
2752 uint32_t YDimCstID = 0;
2753 uint32_t ZDimCstID = 0;
2754
David Neto22f144c2017-06-12 14:26:21 -04002755 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002756 uint32_t result_type_id =
2757 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002758
David Neto257c3892018-04-11 13:19:45 -04002759 // X Dimension
2760 Ops << MkId(result_type_id) << MkNum(1);
2761 XDimCstID = nextID++;
2762 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002763 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002764
2765 // Y Dimension
2766 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002767 Ops << MkId(result_type_id) << MkNum(1);
2768 YDimCstID = nextID++;
2769 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002770 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002771
2772 // Z Dimension
2773 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002774 Ops << MkId(result_type_id) << MkNum(1);
2775 ZDimCstID = nextID++;
2776 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002777 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002778
David Neto22f144c2017-06-12 14:26:21 -04002779
David Neto257c3892018-04-11 13:19:45 -04002780 BuiltinDimVec.push_back(XDimCstID);
2781 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002782 BuiltinDimVec.push_back(ZDimCstID);
2783
David Neto22f144c2017-06-12 14:26:21 -04002784
2785 //
2786 // Generate OpSpecConstantComposite.
2787 //
2788 // Ops[0] : Result Type ID
2789 // Ops[1] : Constant size for x dimension.
2790 // Ops[2] : Constant size for y dimension.
2791 // Ops[3] : Constant size for z dimension.
2792 InitializerID = nextID;
2793
2794 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002795 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2796 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002797
David Neto87846742018-04-11 17:36:22 -04002798 auto *Inst =
2799 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002800 SPIRVInstList.push_back(Inst);
2801 }
2802 }
2803
David Neto22f144c2017-06-12 14:26:21 -04002804 VMap[&GV] = nextID;
2805
2806 //
2807 // Generate OpVariable.
2808 //
2809 // GIDOps[0] : Result Type ID
2810 // GIDOps[1] : Storage Class
2811 SPIRVOperandList Ops;
2812
David Neto85082642018-03-24 06:55:20 -07002813 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002814 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002815
David Neto85082642018-03-24 06:55:20 -07002816 if (GV.hasInitializer()) {
2817 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002818 }
2819
David Neto85082642018-03-24 06:55:20 -07002820 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002821 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002822 clspv::Option::ModuleConstantsInStorageBuffer();
2823
2824 if (0 != InitializerID) {
2825 if (!module_scope_constant_external_init) {
2826 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002827 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002828 }
2829 }
2830 const uint32_t var_id = nextID++;
2831
David Neto87846742018-04-11 17:36:22 -04002832 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002833 SPIRVInstList.push_back(Inst);
2834
2835 // If we have a builtin.
2836 if (spv::BuiltInMax != BuiltinType) {
2837 // Find Insert Point for OpDecorate.
2838 auto DecoInsertPoint =
2839 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2840 [](SPIRVInstruction *Inst) -> bool {
2841 return Inst->getOpcode() != spv::OpDecorate &&
2842 Inst->getOpcode() != spv::OpMemberDecorate &&
2843 Inst->getOpcode() != spv::OpExtInstImport;
2844 });
2845 //
2846 // Generate OpDecorate.
2847 //
2848 // DOps[0] = Target ID
2849 // DOps[1] = Decoration (Builtin)
2850 // DOps[2] = BuiltIn ID
2851 uint32_t ResultID;
2852
2853 // WorkgroupSize is different, we decorate the constant composite that has
2854 // its value, rather than the variable that we use to access the value.
2855 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2856 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002857 // Save both the value and variable IDs for later.
2858 WorkgroupSizeValueID = InitializerID;
2859 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002860 } else {
2861 ResultID = VMap[&GV];
2862 }
2863
2864 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002865 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2866 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002867
David Neto87846742018-04-11 17:36:22 -04002868 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002869 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002870 } else if (module_scope_constant_external_init) {
2871 // This module scope constant is initialized from a storage buffer with data
2872 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002873 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002874
David Neto862b7d82018-06-14 18:48:37 -04002875 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002876 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2877 // that later to other types, like uniform buffer.
2878 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2879 << ",binding,0,kind,buffer,hexbytes,";
2880 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2881 descriptorMapOut << "\n";
2882
2883 // Find Insert Point for OpDecorate.
2884 auto DecoInsertPoint =
2885 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2886 [](SPIRVInstruction *Inst) -> bool {
2887 return Inst->getOpcode() != spv::OpDecorate &&
2888 Inst->getOpcode() != spv::OpMemberDecorate &&
2889 Inst->getOpcode() != spv::OpExtInstImport;
2890 });
2891
David Neto257c3892018-04-11 13:19:45 -04002892 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002893 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002894 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2895 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002896 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002897
2898 // OpDecorate %var DescriptorSet <descriptor_set>
2899 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002900 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2901 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002902 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002903 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002904 }
2905}
2906
David Netoc6f3ab22018-04-06 18:02:31 -04002907void SPIRVProducerPass::GenerateWorkgroupVars() {
2908 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002909 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2910 ++spec_id) {
2911 LocalArgInfo& info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002912
2913 // Generate OpVariable.
2914 //
2915 // GIDOps[0] : Result Type ID
2916 // GIDOps[1] : Storage Class
2917 SPIRVOperandList Ops;
2918 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2919
2920 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002921 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002922 }
2923}
2924
David Neto862b7d82018-06-14 18:48:37 -04002925void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2926 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002927 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2928 return;
2929 }
David Neto862b7d82018-06-14 18:48:37 -04002930 // Gather the list of resources that are used by this function's arguments.
2931 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2932
2933 auto remap_arg_kind = [](StringRef argKind) {
2934 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2935 ? "pod_ubo"
2936 : argKind;
2937 };
2938
2939 auto *fty = F.getType()->getPointerElementType();
2940 auto *func_ty = dyn_cast<FunctionType>(fty);
2941
2942 // If we've clustereed POD arguments, then argument details are in metadata.
2943 // If an argument maps to a resource variable, then get descriptor set and
2944 // binding from the resoure variable. Other info comes from the metadata.
2945 const auto *arg_map = F.getMetadata("kernel_arg_map");
2946 if (arg_map) {
2947 for (const auto &arg : arg_map->operands()) {
2948 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002949 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002950 const auto name =
2951 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2952 const auto old_index =
2953 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2954 // Remapped argument index
2955 const auto new_index =
2956 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2957 const auto offset =
2958 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002959 const auto arg_size =
2960 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002961 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002962 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04002963 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00002964 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002965 if (spec_id > 0) {
2966 // This was a pointer-to-local argument. It is not associated with a
2967 // resource variable.
2968 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2969 << ",argOrdinal," << old_index << ",argKind,"
2970 << argKind << ",arrayElemSize,"
2971 << DL.getTypeAllocSize(
2972 func_ty->getParamType(unsigned(new_index))
2973 ->getPointerElementType())
2974 << ",arrayNumElemSpecId," << spec_id << "\n";
2975 } else {
2976 auto *info = resource_var_at_index[new_index];
2977 assert(info);
2978 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2979 << ",argOrdinal," << old_index << ",descriptorSet,"
2980 << info->descriptor_set << ",binding," << info->binding
Kévin PETITa353c832018-03-20 23:21:21 +00002981 << ",offset," << offset << ",argKind," << argKind;
2982 if (argKind.startswith("pod")) {
2983 descriptorMapOut << ",argSize," << arg_size;
2984 }
2985 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04002986 }
2987 }
2988 } else {
2989 // There is no argument map.
2990 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00002991 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04002992
2993 SmallVector<Argument *, 4> arguments;
2994 for (auto &arg : F.args()) {
2995 arguments.push_back(&arg);
2996 }
2997
2998 unsigned arg_index = 0;
2999 for (auto *info : resource_var_at_index) {
3000 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003001 auto arg = arguments[arg_index];
3002 unsigned arg_size;
3003 if (info->arg_kind == clspv::ArgKind::Pod) {
3004 arg_size = DL.getTypeStoreSize(arg->getType());
3005 }
3006
David Neto862b7d82018-06-14 18:48:37 -04003007 descriptorMapOut << "kernel," << F.getName() << ",arg,"
Kévin PETITa353c832018-03-20 23:21:21 +00003008 << arg->getName() << ",argOrdinal,"
David Neto862b7d82018-06-14 18:48:37 -04003009 << arg_index << ",descriptorSet,"
3010 << info->descriptor_set << ",binding," << info->binding
3011 << ",offset," << 0 << ",argKind,"
3012 << remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003013 clspv::GetArgKindName(info->arg_kind));
3014 if (info->arg_kind == clspv::ArgKind::Pod) {
3015 descriptorMapOut << ",argSize," << arg_size;
3016 }
3017 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003018 }
3019 arg_index++;
3020 }
3021 // Generate mappings for pointer-to-local arguments.
3022 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3023 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003024 auto where = LocalArgSpecIds.find(arg);
3025 if (where != LocalArgSpecIds.end()) {
3026 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003027 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3028 << arg->getName() << ",argOrdinal," << arg_index
3029 << ",argKind,"
3030 << "local"
3031 << ",arrayElemSize,"
3032 << DL.getTypeAllocSize(local_arg_info.elem_type)
3033 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3034 << "\n";
3035 }
3036 }
3037 }
3038}
3039
David Neto22f144c2017-06-12 14:26:21 -04003040void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003041 Module& M = *F.getParent();
3042 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003043 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3044 ValueMapType &VMap = getValueMap();
3045 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003046 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3047 auto &GlobalConstArgSet = getGlobalConstArgSet();
3048
3049 FunctionType *FTy = F.getFunctionType();
3050
3051 //
David Neto22f144c2017-06-12 14:26:21 -04003052 // Generate OPFunction.
3053 //
3054
3055 // FOps[0] : Result Type ID
3056 // FOps[1] : Function Control
3057 // FOps[2] : Function Type ID
3058 SPIRVOperandList FOps;
3059
3060 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003061 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003062
3063 // Check function attributes for SPIRV Function Control.
3064 uint32_t FuncControl = spv::FunctionControlMaskNone;
3065 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3066 FuncControl |= spv::FunctionControlInlineMask;
3067 }
3068 if (F.hasFnAttribute(Attribute::NoInline)) {
3069 FuncControl |= spv::FunctionControlDontInlineMask;
3070 }
3071 // TODO: Check llvm attribute for Function Control Pure.
3072 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3073 FuncControl |= spv::FunctionControlPureMask;
3074 }
3075 // TODO: Check llvm attribute for Function Control Const.
3076 if (F.hasFnAttribute(Attribute::ReadNone)) {
3077 FuncControl |= spv::FunctionControlConstMask;
3078 }
3079
David Neto257c3892018-04-11 13:19:45 -04003080 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003081
3082 uint32_t FTyID;
3083 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3084 SmallVector<Type *, 4> NewFuncParamTys;
3085 FunctionType *NewFTy =
3086 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3087 FTyID = lookupType(NewFTy);
3088 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003089 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003090 if (GlobalConstFuncTyMap.count(FTy)) {
3091 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3092 } else {
3093 FTyID = lookupType(FTy);
3094 }
3095 }
3096
David Neto257c3892018-04-11 13:19:45 -04003097 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003098
3099 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3100 EntryPoints.push_back(std::make_pair(&F, nextID));
3101 }
3102
3103 VMap[&F] = nextID;
3104
David Neto482550a2018-03-24 05:21:07 -07003105 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003106 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3107 }
David Neto22f144c2017-06-12 14:26:21 -04003108 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003109 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003110 SPIRVInstList.push_back(FuncInst);
3111
3112 //
3113 // Generate OpFunctionParameter for Normal function.
3114 //
3115
3116 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3117 // Iterate Argument for name instead of param type from function type.
3118 unsigned ArgIdx = 0;
3119 for (Argument &Arg : F.args()) {
3120 VMap[&Arg] = nextID;
3121
3122 // ParamOps[0] : Result Type ID
3123 SPIRVOperandList ParamOps;
3124
3125 // Find SPIRV instruction for parameter type.
3126 uint32_t ParamTyID = lookupType(Arg.getType());
3127 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3128 if (GlobalConstFuncTyMap.count(FTy)) {
3129 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3130 Type *EleTy = PTy->getPointerElementType();
3131 Type *ArgTy =
3132 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3133 ParamTyID = lookupType(ArgTy);
3134 GlobalConstArgSet.insert(&Arg);
3135 }
3136 }
3137 }
David Neto257c3892018-04-11 13:19:45 -04003138 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003139
3140 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003141 auto *ParamInst =
3142 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003143 SPIRVInstList.push_back(ParamInst);
3144
3145 ArgIdx++;
3146 }
3147 }
3148}
3149
David Neto5c22a252018-03-15 16:07:41 -04003150void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003151 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3152 EntryPointVecType &EntryPoints = getEntryPointVec();
3153 ValueMapType &VMap = getValueMap();
3154 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3155 uint32_t &ExtInstImportID = getOpExtInstImportID();
3156 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3157
3158 // Set up insert point.
3159 auto InsertPoint = SPIRVInstList.begin();
3160
3161 //
3162 // Generate OpCapability
3163 //
3164 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3165
3166 // Ops[0] = Capability
3167 SPIRVOperandList Ops;
3168
David Neto87846742018-04-11 17:36:22 -04003169 auto *CapInst =
3170 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003171 SPIRVInstList.insert(InsertPoint, CapInst);
3172
3173 for (Type *Ty : getTypeList()) {
3174 // Find the i16 type.
3175 if (Ty->isIntegerTy(16)) {
3176 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003177 SPIRVInstList.insert(InsertPoint,
3178 new SPIRVInstruction(spv::OpCapability,
3179 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003180 } else if (Ty->isIntegerTy(64)) {
3181 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003182 SPIRVInstList.insert(InsertPoint,
3183 new SPIRVInstruction(spv::OpCapability,
3184 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003185 } else if (Ty->isHalfTy()) {
3186 // Generate OpCapability for half type.
3187 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003188 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3189 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003190 } else if (Ty->isDoubleTy()) {
3191 // Generate OpCapability for double type.
3192 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003193 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3194 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003195 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3196 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003197 if (STy->getName().equals("opencl.image2d_wo_t") ||
3198 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003199 // Generate OpCapability for write only image type.
3200 SPIRVInstList.insert(
3201 InsertPoint,
3202 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003203 spv::OpCapability,
3204 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003205 }
3206 }
3207 }
3208 }
3209
David Neto5c22a252018-03-15 16:07:41 -04003210 { // OpCapability ImageQuery
3211 bool hasImageQuery = false;
3212 for (const char *imageQuery : {
3213 "_Z15get_image_width14ocl_image2d_ro",
3214 "_Z15get_image_width14ocl_image2d_wo",
3215 "_Z16get_image_height14ocl_image2d_ro",
3216 "_Z16get_image_height14ocl_image2d_wo",
3217 }) {
3218 if (module.getFunction(imageQuery)) {
3219 hasImageQuery = true;
3220 break;
3221 }
3222 }
3223 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003224 auto *ImageQueryCapInst = new SPIRVInstruction(
3225 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003226 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3227 }
3228 }
3229
David Neto22f144c2017-06-12 14:26:21 -04003230 if (hasVariablePointers()) {
3231 //
3232 // Generate OpCapability and OpExtension
3233 //
3234
3235 //
3236 // Generate OpCapability.
3237 //
3238 // Ops[0] = Capability
3239 //
3240 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003241 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003242
David Neto87846742018-04-11 17:36:22 -04003243 SPIRVInstList.insert(InsertPoint,
3244 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003245
3246 //
3247 // Generate OpExtension.
3248 //
3249 // Ops[0] = Name (Literal String)
3250 //
David Netoa772fd12017-08-04 14:17:33 -04003251 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3252 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003253
David Neto87846742018-04-11 17:36:22 -04003254 auto *ExtensionInst =
3255 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003256 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003257 }
David Neto22f144c2017-06-12 14:26:21 -04003258 }
3259
3260 if (ExtInstImportID) {
3261 ++InsertPoint;
3262 }
3263
3264 //
3265 // Generate OpMemoryModel
3266 //
3267 // Memory model for Vulkan will always be GLSL450.
3268
3269 // Ops[0] = Addressing Model
3270 // Ops[1] = Memory Model
3271 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003272 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003273
David Neto87846742018-04-11 17:36:22 -04003274 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003275 SPIRVInstList.insert(InsertPoint, MemModelInst);
3276
3277 //
3278 // Generate OpEntryPoint
3279 //
3280 for (auto EntryPoint : EntryPoints) {
3281 // Ops[0] = Execution Model
3282 // Ops[1] = EntryPoint ID
3283 // Ops[2] = Name (Literal String)
3284 // ...
3285 //
3286 // TODO: Do we need to consider Interface ID for forward references???
3287 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003288 const StringRef& name = EntryPoint.first->getName();
3289 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3290 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003291
David Neto22f144c2017-06-12 14:26:21 -04003292 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003293 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003294 }
3295
David Neto87846742018-04-11 17:36:22 -04003296 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003297 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3298 }
3299
3300 for (auto EntryPoint : EntryPoints) {
3301 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3302 ->getMetadata("reqd_work_group_size")) {
3303
3304 if (!BuiltinDimVec.empty()) {
3305 llvm_unreachable(
3306 "Kernels should have consistent work group size definition");
3307 }
3308
3309 //
3310 // Generate OpExecutionMode
3311 //
3312
3313 // Ops[0] = Entry Point ID
3314 // Ops[1] = Execution Mode
3315 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3316 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003317 Ops << MkId(EntryPoint.second)
3318 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003319
3320 uint32_t XDim = static_cast<uint32_t>(
3321 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3322 uint32_t YDim = static_cast<uint32_t>(
3323 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3324 uint32_t ZDim = static_cast<uint32_t>(
3325 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3326
David Neto257c3892018-04-11 13:19:45 -04003327 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003328
David Neto87846742018-04-11 17:36:22 -04003329 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003330 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3331 }
3332 }
3333
3334 //
3335 // Generate OpSource.
3336 //
3337 // Ops[0] = SourceLanguage ID
3338 // Ops[1] = Version (LiteralNum)
3339 //
3340 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003341 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003342
David Neto87846742018-04-11 17:36:22 -04003343 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003344 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3345
3346 if (!BuiltinDimVec.empty()) {
3347 //
3348 // Generate OpDecorates for x/y/z dimension.
3349 //
3350 // Ops[0] = Target ID
3351 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003352 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003353
3354 // X Dimension
3355 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003356 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003357 SPIRVInstList.insert(InsertPoint,
3358 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003359
3360 // Y Dimension
3361 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003362 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003363 SPIRVInstList.insert(InsertPoint,
3364 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003365
3366 // Z Dimension
3367 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003368 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003369 SPIRVInstList.insert(InsertPoint,
3370 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003371 }
3372}
3373
David Netob6e2e062018-04-25 10:32:06 -04003374void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3375 // Work around a driver bug. Initializers on Private variables might not
3376 // work. So the start of the kernel should store the initializer value to the
3377 // variables. Yes, *every* entry point pays this cost if *any* entry point
3378 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3379 // of complexity vs. runtime, for a broken driver.
3380 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3381 if (WorkgroupSizeVarID) {
3382 assert(WorkgroupSizeValueID);
3383
3384 SPIRVOperandList Ops;
3385 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3386
3387 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3388 getSPIRVInstList().push_back(Inst);
3389 }
3390}
3391
David Neto22f144c2017-06-12 14:26:21 -04003392void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3393 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3394 ValueMapType &VMap = getValueMap();
3395
David Netob6e2e062018-04-25 10:32:06 -04003396 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003397
3398 for (BasicBlock &BB : F) {
3399 // Register BasicBlock to ValueMap.
3400 VMap[&BB] = nextID;
3401
3402 //
3403 // Generate OpLabel for Basic Block.
3404 //
3405 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003406 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003407 SPIRVInstList.push_back(Inst);
3408
David Neto6dcd4712017-06-23 11:06:47 -04003409 // OpVariable instructions must come first.
3410 for (Instruction &I : BB) {
3411 if (isa<AllocaInst>(I)) {
3412 GenerateInstruction(I);
3413 }
3414 }
3415
David Neto22f144c2017-06-12 14:26:21 -04003416 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003417 if (clspv::Option::HackInitializers()) {
3418 GenerateEntryPointInitialStores();
3419 }
David Neto22f144c2017-06-12 14:26:21 -04003420 }
3421
3422 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003423 if (!isa<AllocaInst>(I)) {
3424 GenerateInstruction(I);
3425 }
David Neto22f144c2017-06-12 14:26:21 -04003426 }
3427 }
3428}
3429
3430spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3431 const std::map<CmpInst::Predicate, spv::Op> Map = {
3432 {CmpInst::ICMP_EQ, spv::OpIEqual},
3433 {CmpInst::ICMP_NE, spv::OpINotEqual},
3434 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3435 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3436 {CmpInst::ICMP_ULT, spv::OpULessThan},
3437 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3438 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3439 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3440 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3441 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3442 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3443 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3444 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3445 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3446 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3447 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3448 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3449 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3450 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3451 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3452 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3453 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3454
3455 assert(0 != Map.count(I->getPredicate()));
3456
3457 return Map.at(I->getPredicate());
3458}
3459
3460spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3461 const std::map<unsigned, spv::Op> Map{
3462 {Instruction::Trunc, spv::OpUConvert},
3463 {Instruction::ZExt, spv::OpUConvert},
3464 {Instruction::SExt, spv::OpSConvert},
3465 {Instruction::FPToUI, spv::OpConvertFToU},
3466 {Instruction::FPToSI, spv::OpConvertFToS},
3467 {Instruction::UIToFP, spv::OpConvertUToF},
3468 {Instruction::SIToFP, spv::OpConvertSToF},
3469 {Instruction::FPTrunc, spv::OpFConvert},
3470 {Instruction::FPExt, spv::OpFConvert},
3471 {Instruction::BitCast, spv::OpBitcast}};
3472
3473 assert(0 != Map.count(I.getOpcode()));
3474
3475 return Map.at(I.getOpcode());
3476}
3477
3478spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003479 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003480 switch (I.getOpcode()) {
3481 default:
3482 break;
3483 case Instruction::Or:
3484 return spv::OpLogicalOr;
3485 case Instruction::And:
3486 return spv::OpLogicalAnd;
3487 case Instruction::Xor:
3488 return spv::OpLogicalNotEqual;
3489 }
3490 }
3491
3492 const std::map<unsigned, spv::Op> Map {
3493 {Instruction::Add, spv::OpIAdd},
3494 {Instruction::FAdd, spv::OpFAdd},
3495 {Instruction::Sub, spv::OpISub},
3496 {Instruction::FSub, spv::OpFSub},
3497 {Instruction::Mul, spv::OpIMul},
3498 {Instruction::FMul, spv::OpFMul},
3499 {Instruction::UDiv, spv::OpUDiv},
3500 {Instruction::SDiv, spv::OpSDiv},
3501 {Instruction::FDiv, spv::OpFDiv},
3502 {Instruction::URem, spv::OpUMod},
3503 {Instruction::SRem, spv::OpSRem},
3504 {Instruction::FRem, spv::OpFRem},
3505 {Instruction::Or, spv::OpBitwiseOr},
3506 {Instruction::Xor, spv::OpBitwiseXor},
3507 {Instruction::And, spv::OpBitwiseAnd},
3508 {Instruction::Shl, spv::OpShiftLeftLogical},
3509 {Instruction::LShr, spv::OpShiftRightLogical},
3510 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3511
3512 assert(0 != Map.count(I.getOpcode()));
3513
3514 return Map.at(I.getOpcode());
3515}
3516
3517void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3518 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3519 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003520 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3521 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3522
3523 // Register Instruction to ValueMap.
3524 if (0 == VMap[&I]) {
3525 VMap[&I] = nextID;
3526 }
3527
3528 switch (I.getOpcode()) {
3529 default: {
3530 if (Instruction::isCast(I.getOpcode())) {
3531 //
3532 // Generate SPIRV instructions for cast operators.
3533 //
3534
David Netod2de94a2017-08-28 17:27:47 -04003535
3536 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003537 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003538 auto toI8 = Ty == Type::getInt8Ty(Context);
3539 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003540 // Handle zext, sext and uitofp with i1 type specially.
3541 if ((I.getOpcode() == Instruction::ZExt ||
3542 I.getOpcode() == Instruction::SExt ||
3543 I.getOpcode() == Instruction::UIToFP) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003544 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003545 //
3546 // Generate OpSelect.
3547 //
3548
3549 // Ops[0] = Result Type ID
3550 // Ops[1] = Condition ID
3551 // Ops[2] = True Constant ID
3552 // Ops[3] = False Constant ID
3553 SPIRVOperandList Ops;
3554
David Neto257c3892018-04-11 13:19:45 -04003555 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003556
David Neto22f144c2017-06-12 14:26:21 -04003557 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003558 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003559
3560 uint32_t TrueID = 0;
3561 if (I.getOpcode() == Instruction::ZExt) {
3562 APInt One(32, 1);
3563 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3564 } else if (I.getOpcode() == Instruction::SExt) {
3565 APInt MinusOne(32, UINT64_MAX, true);
3566 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3567 } else {
3568 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3569 }
David Neto257c3892018-04-11 13:19:45 -04003570 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003571
3572 uint32_t FalseID = 0;
3573 if (I.getOpcode() == Instruction::ZExt) {
3574 FalseID = VMap[Constant::getNullValue(I.getType())];
3575 } else if (I.getOpcode() == Instruction::SExt) {
3576 FalseID = VMap[Constant::getNullValue(I.getType())];
3577 } else {
3578 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3579 }
David Neto257c3892018-04-11 13:19:45 -04003580 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003581
David Neto87846742018-04-11 17:36:22 -04003582 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003583 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003584 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3585 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3586 // 8 bits.
3587 // Before:
3588 // %result = trunc i32 %a to i8
3589 // After
3590 // %result = OpBitwiseAnd %uint %a %uint_255
3591
3592 SPIRVOperandList Ops;
3593
David Neto257c3892018-04-11 13:19:45 -04003594 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003595
3596 Type *UintTy = Type::getInt32Ty(Context);
3597 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003598 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003599
David Neto87846742018-04-11 17:36:22 -04003600 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003601 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003602 } else {
3603 // Ops[0] = Result Type ID
3604 // Ops[1] = Source Value ID
3605 SPIRVOperandList Ops;
3606
David Neto257c3892018-04-11 13:19:45 -04003607 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003608
David Neto87846742018-04-11 17:36:22 -04003609 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003610 SPIRVInstList.push_back(Inst);
3611 }
3612 } else if (isa<BinaryOperator>(I)) {
3613 //
3614 // Generate SPIRV instructions for binary operators.
3615 //
3616
3617 // Handle xor with i1 type specially.
3618 if (I.getOpcode() == Instruction::Xor &&
3619 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003620 ((isa<ConstantInt>(I.getOperand(0)) &&
3621 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3622 (isa<ConstantInt>(I.getOperand(1)) &&
3623 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003624 //
3625 // Generate OpLogicalNot.
3626 //
3627 // Ops[0] = Result Type ID
3628 // Ops[1] = Operand
3629 SPIRVOperandList Ops;
3630
David Neto257c3892018-04-11 13:19:45 -04003631 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003632
3633 Value *CondV = I.getOperand(0);
3634 if (isa<Constant>(I.getOperand(0))) {
3635 CondV = I.getOperand(1);
3636 }
David Neto257c3892018-04-11 13:19:45 -04003637 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003638
David Neto87846742018-04-11 17:36:22 -04003639 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003640 SPIRVInstList.push_back(Inst);
3641 } else {
3642 // Ops[0] = Result Type ID
3643 // Ops[1] = Operand 0
3644 // Ops[2] = Operand 1
3645 SPIRVOperandList Ops;
3646
David Neto257c3892018-04-11 13:19:45 -04003647 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3648 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003649
David Neto87846742018-04-11 17:36:22 -04003650 auto *Inst =
3651 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003652 SPIRVInstList.push_back(Inst);
3653 }
3654 } else {
3655 I.print(errs());
3656 llvm_unreachable("Unsupported instruction???");
3657 }
3658 break;
3659 }
3660 case Instruction::GetElementPtr: {
3661 auto &GlobalConstArgSet = getGlobalConstArgSet();
3662
3663 //
3664 // Generate OpAccessChain.
3665 //
3666 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3667
3668 //
3669 // Generate OpAccessChain.
3670 //
3671
3672 // Ops[0] = Result Type ID
3673 // Ops[1] = Base ID
3674 // Ops[2] ... Ops[n] = Indexes ID
3675 SPIRVOperandList Ops;
3676
David Neto1a1a0582017-07-07 12:01:44 -04003677 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003678 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3679 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3680 // Use pointer type with private address space for global constant.
3681 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003682 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003683 }
David Neto257c3892018-04-11 13:19:45 -04003684
3685 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003686
David Neto862b7d82018-06-14 18:48:37 -04003687 // Generate the base pointer.
3688 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003689
David Neto862b7d82018-06-14 18:48:37 -04003690 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003691
3692 //
3693 // Follows below rules for gep.
3694 //
David Neto862b7d82018-06-14 18:48:37 -04003695 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3696 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003697 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3698 // first index.
3699 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3700 // use gep's first index.
3701 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3702 // gep's first index.
3703 //
3704 spv::Op Opcode = spv::OpAccessChain;
3705 unsigned offset = 0;
3706 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003707 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003708 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003709 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003710 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003711 }
David Neto862b7d82018-06-14 18:48:37 -04003712 } else {
David Neto22f144c2017-06-12 14:26:21 -04003713 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003714 }
3715
3716 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003717 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003718 // Do we need to generate ArrayStride? Check against the GEP result type
3719 // rather than the pointer type of the base because when indexing into
3720 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3721 // for something else in the SPIR-V.
3722 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3723 if (GetStorageClass(ResultType->getAddressSpace()) ==
3724 spv::StorageClassStorageBuffer) {
3725 // Save the need to generate an ArrayStride decoration. But defer
3726 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003727 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003728 }
David Neto22f144c2017-06-12 14:26:21 -04003729 }
3730
3731 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003732 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003733 }
3734
David Neto87846742018-04-11 17:36:22 -04003735 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003736 SPIRVInstList.push_back(Inst);
3737 break;
3738 }
3739 case Instruction::ExtractValue: {
3740 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3741 // Ops[0] = Result Type ID
3742 // Ops[1] = Composite ID
3743 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3744 SPIRVOperandList Ops;
3745
David Neto257c3892018-04-11 13:19:45 -04003746 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003747
3748 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003749 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003750
3751 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003752 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003753 }
3754
David Neto87846742018-04-11 17:36:22 -04003755 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003756 SPIRVInstList.push_back(Inst);
3757 break;
3758 }
3759 case Instruction::InsertValue: {
3760 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3761 // Ops[0] = Result Type ID
3762 // Ops[1] = Object ID
3763 // Ops[2] = Composite ID
3764 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3765 SPIRVOperandList Ops;
3766
3767 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003768 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003769
3770 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003771 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003772
3773 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003774 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003775
3776 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003777 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003778 }
3779
David Neto87846742018-04-11 17:36:22 -04003780 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003781 SPIRVInstList.push_back(Inst);
3782 break;
3783 }
3784 case Instruction::Select: {
3785 //
3786 // Generate OpSelect.
3787 //
3788
3789 // Ops[0] = Result Type ID
3790 // Ops[1] = Condition ID
3791 // Ops[2] = True Constant ID
3792 // Ops[3] = False Constant ID
3793 SPIRVOperandList Ops;
3794
3795 // Find SPIRV instruction for parameter type.
3796 auto Ty = I.getType();
3797 if (Ty->isPointerTy()) {
3798 auto PointeeTy = Ty->getPointerElementType();
3799 if (PointeeTy->isStructTy() &&
3800 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3801 Ty = PointeeTy;
3802 }
3803 }
3804
David Neto257c3892018-04-11 13:19:45 -04003805 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3806 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003807
David Neto87846742018-04-11 17:36:22 -04003808 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003809 SPIRVInstList.push_back(Inst);
3810 break;
3811 }
3812 case Instruction::ExtractElement: {
3813 // Handle <4 x i8> type manually.
3814 Type *CompositeTy = I.getOperand(0)->getType();
3815 if (is4xi8vec(CompositeTy)) {
3816 //
3817 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3818 // <4 x i8>.
3819 //
3820
3821 //
3822 // Generate OpShiftRightLogical
3823 //
3824 // Ops[0] = Result Type ID
3825 // Ops[1] = Operand 0
3826 // Ops[2] = Operand 1
3827 //
3828 SPIRVOperandList Ops;
3829
David Neto257c3892018-04-11 13:19:45 -04003830 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003831
3832 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003833 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003834
3835 uint32_t Op1ID = 0;
3836 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3837 // Handle constant index.
3838 uint64_t Idx = CI->getZExtValue();
3839 Value *ShiftAmount =
3840 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3841 Op1ID = VMap[ShiftAmount];
3842 } else {
3843 // Handle variable index.
3844 SPIRVOperandList TmpOps;
3845
David Neto257c3892018-04-11 13:19:45 -04003846 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3847 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003848
3849 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003850 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003851
3852 Op1ID = nextID;
3853
David Neto87846742018-04-11 17:36:22 -04003854 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003855 SPIRVInstList.push_back(TmpInst);
3856 }
David Neto257c3892018-04-11 13:19:45 -04003857 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003858
3859 uint32_t ShiftID = nextID;
3860
David Neto87846742018-04-11 17:36:22 -04003861 auto *Inst =
3862 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003863 SPIRVInstList.push_back(Inst);
3864
3865 //
3866 // Generate OpBitwiseAnd
3867 //
3868 // Ops[0] = Result Type ID
3869 // Ops[1] = Operand 0
3870 // Ops[2] = Operand 1
3871 //
3872 Ops.clear();
3873
David Neto257c3892018-04-11 13:19:45 -04003874 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003875
3876 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003877 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003878
David Neto9b2d6252017-09-06 15:47:37 -04003879 // Reset mapping for this value to the result of the bitwise and.
3880 VMap[&I] = nextID;
3881
David Neto87846742018-04-11 17:36:22 -04003882 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003883 SPIRVInstList.push_back(Inst);
3884 break;
3885 }
3886
3887 // Ops[0] = Result Type ID
3888 // Ops[1] = Composite ID
3889 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3890 SPIRVOperandList Ops;
3891
David Neto257c3892018-04-11 13:19:45 -04003892 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003893
3894 spv::Op Opcode = spv::OpCompositeExtract;
3895 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003896 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003897 } else {
David Neto257c3892018-04-11 13:19:45 -04003898 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003899 Opcode = spv::OpVectorExtractDynamic;
3900 }
3901
David Neto87846742018-04-11 17:36:22 -04003902 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003903 SPIRVInstList.push_back(Inst);
3904 break;
3905 }
3906 case Instruction::InsertElement: {
3907 // Handle <4 x i8> type manually.
3908 Type *CompositeTy = I.getOperand(0)->getType();
3909 if (is4xi8vec(CompositeTy)) {
3910 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3911 uint32_t CstFFID = VMap[CstFF];
3912
3913 uint32_t ShiftAmountID = 0;
3914 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3915 // Handle constant index.
3916 uint64_t Idx = CI->getZExtValue();
3917 Value *ShiftAmount =
3918 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3919 ShiftAmountID = VMap[ShiftAmount];
3920 } else {
3921 // Handle variable index.
3922 SPIRVOperandList TmpOps;
3923
David Neto257c3892018-04-11 13:19:45 -04003924 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3925 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003926
3927 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003928 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003929
3930 ShiftAmountID = nextID;
3931
David Neto87846742018-04-11 17:36:22 -04003932 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003933 SPIRVInstList.push_back(TmpInst);
3934 }
3935
3936 //
3937 // Generate mask operations.
3938 //
3939
3940 // ShiftLeft mask according to index of insertelement.
3941 SPIRVOperandList Ops;
3942
David Neto257c3892018-04-11 13:19:45 -04003943 const uint32_t ResTyID = lookupType(CompositeTy);
3944 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003945
3946 uint32_t MaskID = nextID;
3947
David Neto87846742018-04-11 17:36:22 -04003948 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003949 SPIRVInstList.push_back(Inst);
3950
3951 // Inverse mask.
3952 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003953 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003954
3955 uint32_t InvMaskID = nextID;
3956
David Neto87846742018-04-11 17:36:22 -04003957 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003958 SPIRVInstList.push_back(Inst);
3959
3960 // Apply mask.
3961 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003962 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003963
3964 uint32_t OrgValID = nextID;
3965
David Neto87846742018-04-11 17:36:22 -04003966 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003967 SPIRVInstList.push_back(Inst);
3968
3969 // Create correct value according to index of insertelement.
3970 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003971 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003972
3973 uint32_t InsertValID = nextID;
3974
David Neto87846742018-04-11 17:36:22 -04003975 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003976 SPIRVInstList.push_back(Inst);
3977
3978 // Insert value to original value.
3979 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003980 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003981
David Netoa394f392017-08-26 20:45:29 -04003982 VMap[&I] = nextID;
3983
David Neto87846742018-04-11 17:36:22 -04003984 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003985 SPIRVInstList.push_back(Inst);
3986
3987 break;
3988 }
3989
David Neto22f144c2017-06-12 14:26:21 -04003990 SPIRVOperandList Ops;
3991
James Priced26efea2018-06-09 23:28:32 +01003992 // Ops[0] = Result Type ID
3993 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003994
3995 spv::Op Opcode = spv::OpCompositeInsert;
3996 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04003997 const auto value = CI->getZExtValue();
3998 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01003999 // Ops[1] = Object ID
4000 // Ops[2] = Composite ID
4001 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4002 Ops << MkId(VMap[I.getOperand(1)])
4003 << MkId(VMap[I.getOperand(0)])
4004 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004005 } else {
James Priced26efea2018-06-09 23:28:32 +01004006 // Ops[1] = Composite ID
4007 // Ops[2] = Object ID
4008 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4009 Ops << MkId(VMap[I.getOperand(0)])
4010 << MkId(VMap[I.getOperand(1)])
4011 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004012 Opcode = spv::OpVectorInsertDynamic;
4013 }
4014
David Neto87846742018-04-11 17:36:22 -04004015 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004016 SPIRVInstList.push_back(Inst);
4017 break;
4018 }
4019 case Instruction::ShuffleVector: {
4020 // Ops[0] = Result Type ID
4021 // Ops[1] = Vector 1 ID
4022 // Ops[2] = Vector 2 ID
4023 // Ops[3] ... Ops[n] = Components (Literal Number)
4024 SPIRVOperandList Ops;
4025
David Neto257c3892018-04-11 13:19:45 -04004026 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4027 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004028
4029 uint64_t NumElements = 0;
4030 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4031 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4032
4033 if (Cst->isNullValue()) {
4034 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004035 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004036 }
4037 } else if (const ConstantDataSequential *CDS =
4038 dyn_cast<ConstantDataSequential>(Cst)) {
4039 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4040 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004041 const auto value = CDS->getElementAsInteger(i);
4042 assert(value <= UINT32_MAX);
4043 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004044 }
4045 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4046 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4047 auto Op = CV->getOperand(i);
4048
4049 uint32_t literal = 0;
4050
4051 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4052 literal = static_cast<uint32_t>(CI->getZExtValue());
4053 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4054 literal = 0xFFFFFFFFu;
4055 } else {
4056 Op->print(errs());
4057 llvm_unreachable("Unsupported element in ConstantVector!");
4058 }
4059
David Neto257c3892018-04-11 13:19:45 -04004060 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004061 }
4062 } else {
4063 Cst->print(errs());
4064 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4065 }
4066 }
4067
David Neto87846742018-04-11 17:36:22 -04004068 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004069 SPIRVInstList.push_back(Inst);
4070 break;
4071 }
4072 case Instruction::ICmp:
4073 case Instruction::FCmp: {
4074 CmpInst *CmpI = cast<CmpInst>(&I);
4075
David Netod4ca2e62017-07-06 18:47:35 -04004076 // Pointer equality is invalid.
4077 Type* ArgTy = CmpI->getOperand(0)->getType();
4078 if (isa<PointerType>(ArgTy)) {
4079 CmpI->print(errs());
4080 std::string name = I.getParent()->getParent()->getName();
4081 errs()
4082 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4083 << "in function " << name << "\n";
4084 llvm_unreachable("Pointer equality check is invalid");
4085 break;
4086 }
4087
David Neto257c3892018-04-11 13:19:45 -04004088 // Ops[0] = Result Type ID
4089 // Ops[1] = Operand 1 ID
4090 // Ops[2] = Operand 2 ID
4091 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004092
David Neto257c3892018-04-11 13:19:45 -04004093 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4094 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004095
4096 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004097 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004098 SPIRVInstList.push_back(Inst);
4099 break;
4100 }
4101 case Instruction::Br: {
4102 // Branch instrucion is deferred because it needs label's ID. Record slot's
4103 // location on SPIRVInstructionList.
4104 DeferredInsts.push_back(
4105 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4106 break;
4107 }
4108 case Instruction::Switch: {
4109 I.print(errs());
4110 llvm_unreachable("Unsupported instruction???");
4111 break;
4112 }
4113 case Instruction::IndirectBr: {
4114 I.print(errs());
4115 llvm_unreachable("Unsupported instruction???");
4116 break;
4117 }
4118 case Instruction::PHI: {
4119 // Branch instrucion is deferred because it needs label's ID. Record slot's
4120 // location on SPIRVInstructionList.
4121 DeferredInsts.push_back(
4122 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4123 break;
4124 }
4125 case Instruction::Alloca: {
4126 //
4127 // Generate OpVariable.
4128 //
4129 // Ops[0] : Result Type ID
4130 // Ops[1] : Storage Class
4131 SPIRVOperandList Ops;
4132
David Neto257c3892018-04-11 13:19:45 -04004133 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004134
David Neto87846742018-04-11 17:36:22 -04004135 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004136 SPIRVInstList.push_back(Inst);
4137 break;
4138 }
4139 case Instruction::Load: {
4140 LoadInst *LD = cast<LoadInst>(&I);
4141 //
4142 // Generate OpLoad.
4143 //
4144
David Neto0a2f98d2017-09-15 19:38:40 -04004145 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004146 uint32_t PointerID = VMap[LD->getPointerOperand()];
4147
4148 // This is a hack to work around what looks like a driver bug.
4149 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004150 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4151 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004152 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004153 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004154 // Generate a bitwise-and of the original value with itself.
4155 // We should have been able to get away with just an OpCopyObject,
4156 // but we need something more complex to get past certain driver bugs.
4157 // This is ridiculous, but necessary.
4158 // TODO(dneto): Revisit this once drivers fix their bugs.
4159
4160 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004161 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4162 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004163
David Neto87846742018-04-11 17:36:22 -04004164 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004165 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004166 break;
4167 }
4168
4169 // This is the normal path. Generate a load.
4170
David Neto22f144c2017-06-12 14:26:21 -04004171 // Ops[0] = Result Type ID
4172 // Ops[1] = Pointer ID
4173 // Ops[2] ... Ops[n] = Optional Memory Access
4174 //
4175 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004176
David Neto22f144c2017-06-12 14:26:21 -04004177 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004178 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004179
David Neto87846742018-04-11 17:36:22 -04004180 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004181 SPIRVInstList.push_back(Inst);
4182 break;
4183 }
4184 case Instruction::Store: {
4185 StoreInst *ST = cast<StoreInst>(&I);
4186 //
4187 // Generate OpStore.
4188 //
4189
4190 // Ops[0] = Pointer ID
4191 // Ops[1] = Object ID
4192 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4193 //
4194 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004195 SPIRVOperandList Ops;
4196 Ops << MkId(VMap[ST->getPointerOperand()])
4197 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004198
David Neto87846742018-04-11 17:36:22 -04004199 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004200 SPIRVInstList.push_back(Inst);
4201 break;
4202 }
4203 case Instruction::AtomicCmpXchg: {
4204 I.print(errs());
4205 llvm_unreachable("Unsupported instruction???");
4206 break;
4207 }
4208 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004209 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4210
4211 spv::Op opcode;
4212
4213 switch (AtomicRMW->getOperation()) {
4214 default:
4215 I.print(errs());
4216 llvm_unreachable("Unsupported instruction???");
4217 case llvm::AtomicRMWInst::Add:
4218 opcode = spv::OpAtomicIAdd;
4219 break;
4220 case llvm::AtomicRMWInst::Sub:
4221 opcode = spv::OpAtomicISub;
4222 break;
4223 case llvm::AtomicRMWInst::Xchg:
4224 opcode = spv::OpAtomicExchange;
4225 break;
4226 case llvm::AtomicRMWInst::Min:
4227 opcode = spv::OpAtomicSMin;
4228 break;
4229 case llvm::AtomicRMWInst::Max:
4230 opcode = spv::OpAtomicSMax;
4231 break;
4232 case llvm::AtomicRMWInst::UMin:
4233 opcode = spv::OpAtomicUMin;
4234 break;
4235 case llvm::AtomicRMWInst::UMax:
4236 opcode = spv::OpAtomicUMax;
4237 break;
4238 case llvm::AtomicRMWInst::And:
4239 opcode = spv::OpAtomicAnd;
4240 break;
4241 case llvm::AtomicRMWInst::Or:
4242 opcode = spv::OpAtomicOr;
4243 break;
4244 case llvm::AtomicRMWInst::Xor:
4245 opcode = spv::OpAtomicXor;
4246 break;
4247 }
4248
4249 //
4250 // Generate OpAtomic*.
4251 //
4252 SPIRVOperandList Ops;
4253
David Neto257c3892018-04-11 13:19:45 -04004254 Ops << MkId(lookupType(I.getType()))
4255 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004256
4257 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004258 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004259 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004260
4261 const auto ConstantMemorySemantics = ConstantInt::get(
4262 IntTy, spv::MemorySemanticsUniformMemoryMask |
4263 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004264 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004265
David Neto257c3892018-04-11 13:19:45 -04004266 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004267
4268 VMap[&I] = nextID;
4269
David Neto87846742018-04-11 17:36:22 -04004270 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004271 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004272 break;
4273 }
4274 case Instruction::Fence: {
4275 I.print(errs());
4276 llvm_unreachable("Unsupported instruction???");
4277 break;
4278 }
4279 case Instruction::Call: {
4280 CallInst *Call = dyn_cast<CallInst>(&I);
4281 Function *Callee = Call->getCalledFunction();
4282
Alan Baker202c8c72018-08-13 13:47:44 -04004283 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004284 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4285 // Generate an OpLoad
4286 SPIRVOperandList Ops;
4287 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004288
David Neto862b7d82018-06-14 18:48:37 -04004289 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4290 << MkId(ResourceVarDeferredLoadCalls[Call]);
4291
4292 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4293 SPIRVInstList.push_back(Inst);
4294 VMap[Call] = load_id;
4295 break;
4296
4297 } else {
4298 // This maps to an OpVariable we've already generated.
4299 // No code is generated for the call.
4300 }
4301 break;
Alan Baker202c8c72018-08-13 13:47:44 -04004302 } else if (Callee->getName().startswith(clspv::WorkgroupAccessorFunction())) {
4303 // Don't codegen an instruction here, but instead map this call directly
4304 // to the workgroup variable id.
4305 int spec_id = cast<ConstantInt>(Call->getOperand(0))->getSExtValue();
4306 const auto &info = LocalSpecIdInfoMap[spec_id];
4307 VMap[Call] = info.variable_id;
4308 break;
David Neto862b7d82018-06-14 18:48:37 -04004309 }
4310
4311 // Sampler initializers become a load of the corresponding sampler.
4312
4313 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4314 // Map this to a load from the variable.
4315 const auto index_into_sampler_map =
4316 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4317
4318 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004319 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004320 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004321
David Neto257c3892018-04-11 13:19:45 -04004322 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004323 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004324
David Neto862b7d82018-06-14 18:48:37 -04004325 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004326 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004327 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004328 break;
4329 }
4330
4331 if (Callee->getName().startswith("spirv.atomic")) {
4332 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4333 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4334 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4335 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4336 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4337 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4338 .Case("spirv.atomic_compare_exchange",
4339 spv::OpAtomicCompareExchange)
4340 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4341 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4342 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4343 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4344 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4345 .Case("spirv.atomic_or", spv::OpAtomicOr)
4346 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4347 .Default(spv::OpNop);
4348
4349 //
4350 // Generate OpAtomic*.
4351 //
4352 SPIRVOperandList Ops;
4353
David Neto257c3892018-04-11 13:19:45 -04004354 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004355
4356 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004357 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004358 }
4359
4360 VMap[&I] = nextID;
4361
David Neto87846742018-04-11 17:36:22 -04004362 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004363 SPIRVInstList.push_back(Inst);
4364 break;
4365 }
4366
4367 if (Callee->getName().startswith("_Z3dot")) {
4368 // If the argument is a vector type, generate OpDot
4369 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4370 //
4371 // Generate OpDot.
4372 //
4373 SPIRVOperandList Ops;
4374
David Neto257c3892018-04-11 13:19:45 -04004375 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004376
4377 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004378 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004379 }
4380
4381 VMap[&I] = nextID;
4382
David Neto87846742018-04-11 17:36:22 -04004383 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004384 SPIRVInstList.push_back(Inst);
4385 } else {
4386 //
4387 // Generate OpFMul.
4388 //
4389 SPIRVOperandList Ops;
4390
David Neto257c3892018-04-11 13:19:45 -04004391 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004392
4393 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004394 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004395 }
4396
4397 VMap[&I] = nextID;
4398
David Neto87846742018-04-11 17:36:22 -04004399 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004400 SPIRVInstList.push_back(Inst);
4401 }
4402 break;
4403 }
4404
David Neto8505ebf2017-10-13 18:50:50 -04004405 if (Callee->getName().startswith("_Z4fmod")) {
4406 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4407 // The sign for a non-zero result is taken from x.
4408 // (Try an example.)
4409 // So translate to OpFRem
4410
4411 SPIRVOperandList Ops;
4412
David Neto257c3892018-04-11 13:19:45 -04004413 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004414
4415 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004416 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004417 }
4418
4419 VMap[&I] = nextID;
4420
David Neto87846742018-04-11 17:36:22 -04004421 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004422 SPIRVInstList.push_back(Inst);
4423 break;
4424 }
4425
David Neto22f144c2017-06-12 14:26:21 -04004426 // spirv.store_null.* intrinsics become OpStore's.
4427 if (Callee->getName().startswith("spirv.store_null")) {
4428 //
4429 // Generate OpStore.
4430 //
4431
4432 // Ops[0] = Pointer ID
4433 // Ops[1] = Object ID
4434 // Ops[2] ... Ops[n]
4435 SPIRVOperandList Ops;
4436
4437 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004438 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004439 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004440
David Neto87846742018-04-11 17:36:22 -04004441 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004442
4443 break;
4444 }
4445
4446 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4447 if (Callee->getName().startswith("spirv.copy_memory")) {
4448 //
4449 // Generate OpCopyMemory.
4450 //
4451
4452 // Ops[0] = Dst ID
4453 // Ops[1] = Src ID
4454 // Ops[2] = Memory Access
4455 // Ops[3] = Alignment
4456
4457 auto IsVolatile =
4458 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4459
4460 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4461 : spv::MemoryAccessMaskNone;
4462
4463 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4464
4465 auto Alignment =
4466 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4467
David Neto257c3892018-04-11 13:19:45 -04004468 SPIRVOperandList Ops;
4469 Ops << MkId(VMap[Call->getArgOperand(0)])
4470 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4471 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004472
David Neto87846742018-04-11 17:36:22 -04004473 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004474
4475 SPIRVInstList.push_back(Inst);
4476
4477 break;
4478 }
4479
4480 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4481 // with unit.
4482 if (Callee->getName().equals("_Z3absj") ||
4483 Callee->getName().equals("_Z3absDv2_j") ||
4484 Callee->getName().equals("_Z3absDv3_j") ||
4485 Callee->getName().equals("_Z3absDv4_j")) {
4486 VMap[&I] = VMap[Call->getOperand(0)];
4487 break;
4488 }
4489
4490 // barrier is converted to OpControlBarrier
4491 if (Callee->getName().equals("__spirv_control_barrier")) {
4492 //
4493 // Generate OpControlBarrier.
4494 //
4495 // Ops[0] = Execution Scope ID
4496 // Ops[1] = Memory Scope ID
4497 // Ops[2] = Memory Semantics ID
4498 //
4499 Value *ExecutionScope = Call->getArgOperand(0);
4500 Value *MemoryScope = Call->getArgOperand(1);
4501 Value *MemorySemantics = Call->getArgOperand(2);
4502
David Neto257c3892018-04-11 13:19:45 -04004503 SPIRVOperandList Ops;
4504 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4505 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004506
David Neto87846742018-04-11 17:36:22 -04004507 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004508 break;
4509 }
4510
4511 // memory barrier is converted to OpMemoryBarrier
4512 if (Callee->getName().equals("__spirv_memory_barrier")) {
4513 //
4514 // Generate OpMemoryBarrier.
4515 //
4516 // Ops[0] = Memory Scope ID
4517 // Ops[1] = Memory Semantics ID
4518 //
4519 SPIRVOperandList Ops;
4520
David Neto257c3892018-04-11 13:19:45 -04004521 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4522 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004523
David Neto257c3892018-04-11 13:19:45 -04004524 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004525
David Neto87846742018-04-11 17:36:22 -04004526 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004527 SPIRVInstList.push_back(Inst);
4528 break;
4529 }
4530
4531 // isinf is converted to OpIsInf
4532 if (Callee->getName().equals("__spirv_isinff") ||
4533 Callee->getName().equals("__spirv_isinfDv2_f") ||
4534 Callee->getName().equals("__spirv_isinfDv3_f") ||
4535 Callee->getName().equals("__spirv_isinfDv4_f")) {
4536 //
4537 // Generate OpIsInf.
4538 //
4539 // Ops[0] = Result Type ID
4540 // Ops[1] = X ID
4541 //
4542 SPIRVOperandList Ops;
4543
David Neto257c3892018-04-11 13:19:45 -04004544 Ops << MkId(lookupType(I.getType()))
4545 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004546
4547 VMap[&I] = nextID;
4548
David Neto87846742018-04-11 17:36:22 -04004549 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004550 SPIRVInstList.push_back(Inst);
4551 break;
4552 }
4553
4554 // isnan is converted to OpIsNan
4555 if (Callee->getName().equals("__spirv_isnanf") ||
4556 Callee->getName().equals("__spirv_isnanDv2_f") ||
4557 Callee->getName().equals("__spirv_isnanDv3_f") ||
4558 Callee->getName().equals("__spirv_isnanDv4_f")) {
4559 //
4560 // Generate OpIsInf.
4561 //
4562 // Ops[0] = Result Type ID
4563 // Ops[1] = X ID
4564 //
4565 SPIRVOperandList Ops;
4566
David Neto257c3892018-04-11 13:19:45 -04004567 Ops << MkId(lookupType(I.getType()))
4568 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004569
4570 VMap[&I] = nextID;
4571
David Neto87846742018-04-11 17:36:22 -04004572 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004573 SPIRVInstList.push_back(Inst);
4574 break;
4575 }
4576
4577 // all is converted to OpAll
4578 if (Callee->getName().equals("__spirv_allDv2_i") ||
4579 Callee->getName().equals("__spirv_allDv3_i") ||
4580 Callee->getName().equals("__spirv_allDv4_i")) {
4581 //
4582 // Generate OpAll.
4583 //
4584 // Ops[0] = Result Type ID
4585 // Ops[1] = Vector ID
4586 //
4587 SPIRVOperandList Ops;
4588
David Neto257c3892018-04-11 13:19:45 -04004589 Ops << MkId(lookupType(I.getType()))
4590 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004591
4592 VMap[&I] = nextID;
4593
David Neto87846742018-04-11 17:36:22 -04004594 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004595 SPIRVInstList.push_back(Inst);
4596 break;
4597 }
4598
4599 // any is converted to OpAny
4600 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4601 Callee->getName().equals("__spirv_anyDv3_i") ||
4602 Callee->getName().equals("__spirv_anyDv4_i")) {
4603 //
4604 // Generate OpAny.
4605 //
4606 // Ops[0] = Result Type ID
4607 // Ops[1] = Vector ID
4608 //
4609 SPIRVOperandList Ops;
4610
David Neto257c3892018-04-11 13:19:45 -04004611 Ops << MkId(lookupType(I.getType()))
4612 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004613
4614 VMap[&I] = nextID;
4615
David Neto87846742018-04-11 17:36:22 -04004616 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004617 SPIRVInstList.push_back(Inst);
4618 break;
4619 }
4620
4621 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4622 // Additionally, OpTypeSampledImage is generated.
4623 if (Callee->getName().equals(
4624 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4625 Callee->getName().equals(
4626 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4627 //
4628 // Generate OpSampledImage.
4629 //
4630 // Ops[0] = Result Type ID
4631 // Ops[1] = Image ID
4632 // Ops[2] = Sampler ID
4633 //
4634 SPIRVOperandList Ops;
4635
4636 Value *Image = Call->getArgOperand(0);
4637 Value *Sampler = Call->getArgOperand(1);
4638 Value *Coordinate = Call->getArgOperand(2);
4639
4640 TypeMapType &OpImageTypeMap = getImageTypeMap();
4641 Type *ImageTy = Image->getType()->getPointerElementType();
4642 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004643 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004644 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004645
4646 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004647
4648 uint32_t SampledImageID = nextID;
4649
David Neto87846742018-04-11 17:36:22 -04004650 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004651 SPIRVInstList.push_back(Inst);
4652
4653 //
4654 // Generate OpImageSampleExplicitLod.
4655 //
4656 // Ops[0] = Result Type ID
4657 // Ops[1] = Sampled Image ID
4658 // Ops[2] = Coordinate ID
4659 // Ops[3] = Image Operands Type ID
4660 // Ops[4] ... Ops[n] = Operands ID
4661 //
4662 Ops.clear();
4663
David Neto257c3892018-04-11 13:19:45 -04004664 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4665 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004666
4667 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004668 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004669
4670 VMap[&I] = nextID;
4671
David Neto87846742018-04-11 17:36:22 -04004672 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004673 SPIRVInstList.push_back(Inst);
4674 break;
4675 }
4676
4677 // write_imagef is mapped to OpImageWrite.
4678 if (Callee->getName().equals(
4679 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4680 Callee->getName().equals(
4681 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4682 //
4683 // Generate OpImageWrite.
4684 //
4685 // Ops[0] = Image ID
4686 // Ops[1] = Coordinate ID
4687 // Ops[2] = Texel ID
4688 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4689 // Ops[4] ... Ops[n] = (Optional) Operands ID
4690 //
4691 SPIRVOperandList Ops;
4692
4693 Value *Image = Call->getArgOperand(0);
4694 Value *Coordinate = Call->getArgOperand(1);
4695 Value *Texel = Call->getArgOperand(2);
4696
4697 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004698 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004699 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004700 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004701
David Neto87846742018-04-11 17:36:22 -04004702 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004703 SPIRVInstList.push_back(Inst);
4704 break;
4705 }
4706
David Neto5c22a252018-03-15 16:07:41 -04004707 // get_image_width is mapped to OpImageQuerySize
4708 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4709 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4710 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4711 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4712 //
4713 // Generate OpImageQuerySize, then pull out the right component.
4714 // Assume 2D image for now.
4715 //
4716 // Ops[0] = Image ID
4717 //
4718 // %sizes = OpImageQuerySizes %uint2 %im
4719 // %result = OpCompositeExtract %uint %sizes 0-or-1
4720 SPIRVOperandList Ops;
4721
4722 // Implement:
4723 // %sizes = OpImageQuerySizes %uint2 %im
4724 uint32_t SizesTypeID =
4725 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004726 Value *Image = Call->getArgOperand(0);
4727 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004728 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004729
4730 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004731 auto *QueryInst =
4732 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004733 SPIRVInstList.push_back(QueryInst);
4734
4735 // Reset value map entry since we generated an intermediate instruction.
4736 VMap[&I] = nextID;
4737
4738 // Implement:
4739 // %result = OpCompositeExtract %uint %sizes 0-or-1
4740 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004741 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004742
4743 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004744 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004745
David Neto87846742018-04-11 17:36:22 -04004746 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004747 SPIRVInstList.push_back(Inst);
4748 break;
4749 }
4750
David Neto22f144c2017-06-12 14:26:21 -04004751 // Call instrucion is deferred because it needs function's ID. Record
4752 // slot's location on SPIRVInstructionList.
4753 DeferredInsts.push_back(
4754 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4755
David Neto3fbb4072017-10-16 11:28:14 -04004756 // Check whether the implementation of this call uses an extended
4757 // instruction plus one more value-producing instruction. If so, then
4758 // reserve the id for the extra value-producing slot.
4759 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4760 if (EInst != kGlslExtInstBad) {
4761 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004762 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004763 VMap[&I] = nextID;
4764 nextID++;
4765 }
4766 break;
4767 }
4768 case Instruction::Ret: {
4769 unsigned NumOps = I.getNumOperands();
4770 if (NumOps == 0) {
4771 //
4772 // Generate OpReturn.
4773 //
David Neto87846742018-04-11 17:36:22 -04004774 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004775 } else {
4776 //
4777 // Generate OpReturnValue.
4778 //
4779
4780 // Ops[0] = Return Value ID
4781 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004782
4783 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004784
David Neto87846742018-04-11 17:36:22 -04004785 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004786 SPIRVInstList.push_back(Inst);
4787 break;
4788 }
4789 break;
4790 }
4791 }
4792}
4793
4794void SPIRVProducerPass::GenerateFuncEpilogue() {
4795 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4796
4797 //
4798 // Generate OpFunctionEnd
4799 //
4800
David Neto87846742018-04-11 17:36:22 -04004801 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004802 SPIRVInstList.push_back(Inst);
4803}
4804
4805bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4806 LLVMContext &Context = Ty->getContext();
4807 if (Ty->isVectorTy()) {
4808 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4809 Ty->getVectorNumElements() == 4) {
4810 return true;
4811 }
4812 }
4813
4814 return false;
4815}
4816
David Neto257c3892018-04-11 13:19:45 -04004817uint32_t SPIRVProducerPass::GetI32Zero() {
4818 if (0 == constant_i32_zero_id_) {
4819 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4820 "defined in the SPIR-V module");
4821 }
4822 return constant_i32_zero_id_;
4823}
4824
David Neto22f144c2017-06-12 14:26:21 -04004825void SPIRVProducerPass::HandleDeferredInstruction() {
4826 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4827 ValueMapType &VMap = getValueMap();
4828 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4829
4830 for (auto DeferredInst = DeferredInsts.rbegin();
4831 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4832 Value *Inst = std::get<0>(*DeferredInst);
4833 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4834 if (InsertPoint != SPIRVInstList.end()) {
4835 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4836 ++InsertPoint;
4837 }
4838 }
4839
4840 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4841 // Check whether basic block, which has this branch instruction, is loop
4842 // header or not. If it is loop header, generate OpLoopMerge and
4843 // OpBranchConditional.
4844 Function *Func = Br->getParent()->getParent();
4845 DominatorTree &DT =
4846 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4847 const LoopInfo &LI =
4848 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4849
4850 BasicBlock *BrBB = Br->getParent();
4851 if (LI.isLoopHeader(BrBB)) {
4852 Value *ContinueBB = nullptr;
4853 Value *MergeBB = nullptr;
4854
4855 Loop *L = LI.getLoopFor(BrBB);
4856 MergeBB = L->getExitBlock();
4857 if (!MergeBB) {
4858 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4859 // has regions with single entry/exit. As a result, loop should not
4860 // have multiple exits.
4861 llvm_unreachable("Loop has multiple exits???");
4862 }
4863
4864 if (L->isLoopLatch(BrBB)) {
4865 ContinueBB = BrBB;
4866 } else {
4867 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4868 // block.
4869 BasicBlock *Header = L->getHeader();
4870 BasicBlock *Latch = L->getLoopLatch();
4871 for (BasicBlock *BB : L->blocks()) {
4872 if (BB == Header) {
4873 continue;
4874 }
4875
4876 // Check whether block dominates block with back-edge.
4877 if (DT.dominates(BB, Latch)) {
4878 ContinueBB = BB;
4879 }
4880 }
4881
4882 if (!ContinueBB) {
4883 llvm_unreachable("Wrong continue block from loop");
4884 }
4885 }
4886
4887 //
4888 // Generate OpLoopMerge.
4889 //
4890 // Ops[0] = Merge Block ID
4891 // Ops[1] = Continue Target ID
4892 // Ops[2] = Selection Control
4893 SPIRVOperandList Ops;
4894
4895 // StructurizeCFG pass already manipulated CFG. Just use false block of
4896 // branch instruction as merge block.
4897 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004898 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004899 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4900 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004901
David Neto87846742018-04-11 17:36:22 -04004902 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004903 SPIRVInstList.insert(InsertPoint, MergeInst);
4904
4905 } else if (Br->isConditional()) {
4906 bool HasBackEdge = false;
4907
4908 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4909 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4910 HasBackEdge = true;
4911 }
4912 }
4913 if (!HasBackEdge) {
4914 //
4915 // Generate OpSelectionMerge.
4916 //
4917 // Ops[0] = Merge Block ID
4918 // Ops[1] = Selection Control
4919 SPIRVOperandList Ops;
4920
4921 // StructurizeCFG pass already manipulated CFG. Just use false block
4922 // of branch instruction as merge block.
4923 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004924 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004925
David Neto87846742018-04-11 17:36:22 -04004926 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004927 SPIRVInstList.insert(InsertPoint, MergeInst);
4928 }
4929 }
4930
4931 if (Br->isConditional()) {
4932 //
4933 // Generate OpBranchConditional.
4934 //
4935 // Ops[0] = Condition ID
4936 // Ops[1] = True Label ID
4937 // Ops[2] = False Label ID
4938 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4939 SPIRVOperandList Ops;
4940
4941 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004942 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004943 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004944
4945 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004946
David Neto87846742018-04-11 17:36:22 -04004947 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004948 SPIRVInstList.insert(InsertPoint, BrInst);
4949 } else {
4950 //
4951 // Generate OpBranch.
4952 //
4953 // Ops[0] = Target Label ID
4954 SPIRVOperandList Ops;
4955
4956 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004957 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004958
David Neto87846742018-04-11 17:36:22 -04004959 SPIRVInstList.insert(InsertPoint,
4960 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004961 }
4962 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4963 //
4964 // Generate OpPhi.
4965 //
4966 // Ops[0] = Result Type ID
4967 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4968 SPIRVOperandList Ops;
4969
David Neto257c3892018-04-11 13:19:45 -04004970 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004971
David Neto22f144c2017-06-12 14:26:21 -04004972 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4973 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004974 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004975 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004976 }
4977
4978 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004979 InsertPoint,
4980 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004981 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4982 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004983 auto callee_name = Callee->getName();
4984 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004985
4986 if (EInst) {
4987 uint32_t &ExtInstImportID = getOpExtInstImportID();
4988
4989 //
4990 // Generate OpExtInst.
4991 //
4992
4993 // Ops[0] = Result Type ID
4994 // Ops[1] = Set ID (OpExtInstImport ID)
4995 // Ops[2] = Instruction Number (Literal Number)
4996 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
4997 SPIRVOperandList Ops;
4998
David Neto862b7d82018-06-14 18:48:37 -04004999 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5000 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005001
David Neto22f144c2017-06-12 14:26:21 -04005002 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5003 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005004 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005005 }
5006
David Neto87846742018-04-11 17:36:22 -04005007 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5008 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005009 SPIRVInstList.insert(InsertPoint, ExtInst);
5010
David Neto3fbb4072017-10-16 11:28:14 -04005011 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5012 if (IndirectExtInst != kGlslExtInstBad) {
5013 // Generate one more instruction that uses the result of the extended
5014 // instruction. Its result id is one more than the id of the
5015 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005016 LLVMContext &Context =
5017 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005018
David Neto3fbb4072017-10-16 11:28:14 -04005019 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5020 &VMap, &SPIRVInstList, &InsertPoint](
5021 spv::Op opcode, Constant *constant) {
5022 //
5023 // Generate instruction like:
5024 // result = opcode constant <extinst-result>
5025 //
5026 // Ops[0] = Result Type ID
5027 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5028 // Ops[2] = Operand 1 ;; the result of the extended instruction
5029 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005030
David Neto3fbb4072017-10-16 11:28:14 -04005031 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005032 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005033
5034 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5035 constant = ConstantVector::getSplat(
5036 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5037 }
David Neto257c3892018-04-11 13:19:45 -04005038 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005039
5040 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005041 InsertPoint, new SPIRVInstruction(
5042 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005043 };
5044
5045 switch (IndirectExtInst) {
5046 case glsl::ExtInstFindUMsb: // Implementing clz
5047 generate_extra_inst(
5048 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5049 break;
5050 case glsl::ExtInstAcos: // Implementing acospi
5051 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005052 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005053 case glsl::ExtInstAtan2: // Implementing atan2pi
5054 generate_extra_inst(
5055 spv::OpFMul,
5056 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5057 break;
5058
5059 default:
5060 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005061 }
David Neto22f144c2017-06-12 14:26:21 -04005062 }
David Neto3fbb4072017-10-16 11:28:14 -04005063
David Neto862b7d82018-06-14 18:48:37 -04005064 } else if (callee_name.equals("_Z8popcounti") ||
5065 callee_name.equals("_Z8popcountj") ||
5066 callee_name.equals("_Z8popcountDv2_i") ||
5067 callee_name.equals("_Z8popcountDv3_i") ||
5068 callee_name.equals("_Z8popcountDv4_i") ||
5069 callee_name.equals("_Z8popcountDv2_j") ||
5070 callee_name.equals("_Z8popcountDv3_j") ||
5071 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005072 //
5073 // Generate OpBitCount
5074 //
5075 // Ops[0] = Result Type ID
5076 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005077 SPIRVOperandList Ops;
5078 Ops << MkId(lookupType(Call->getType()))
5079 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005080
5081 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005082 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005083 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005084
David Neto862b7d82018-06-14 18:48:37 -04005085 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005086
5087 // Generate an OpCompositeConstruct
5088 SPIRVOperandList Ops;
5089
5090 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005091 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005092
5093 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005094 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005095 }
5096
5097 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005098 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5099 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005100
Alan Baker202c8c72018-08-13 13:47:44 -04005101 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5102
5103 // We have already mapped the call's result value to an ID.
5104 // Don't generate any code now.
5105
5106 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005107
5108 // We have already mapped the call's result value to an ID.
5109 // Don't generate any code now.
5110
David Neto22f144c2017-06-12 14:26:21 -04005111 } else {
5112 //
5113 // Generate OpFunctionCall.
5114 //
5115
5116 // Ops[0] = Result Type ID
5117 // Ops[1] = Callee Function ID
5118 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5119 SPIRVOperandList Ops;
5120
David Neto862b7d82018-06-14 18:48:37 -04005121 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005122
5123 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005124 if (CalleeID == 0) {
5125 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005126 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005127 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5128 // causes an infinite loop. Instead, go ahead and generate
5129 // the bad function call. A validator will catch the 0-Id.
5130 // llvm_unreachable("Can't translate function call");
5131 }
David Neto22f144c2017-06-12 14:26:21 -04005132
David Neto257c3892018-04-11 13:19:45 -04005133 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005134
David Neto22f144c2017-06-12 14:26:21 -04005135 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5136 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005137 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005138 }
5139
David Neto87846742018-04-11 17:36:22 -04005140 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5141 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005142 SPIRVInstList.insert(InsertPoint, CallInst);
5143 }
5144 }
5145 }
5146}
5147
David Neto1a1a0582017-07-07 12:01:44 -04005148void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005149 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005150 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005151 }
David Neto1a1a0582017-07-07 12:01:44 -04005152
5153 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005154
5155 // Find an iterator pointing just past the last decoration.
5156 bool seen_decorations = false;
5157 auto DecoInsertPoint =
5158 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5159 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5160 const bool is_decoration =
5161 Inst->getOpcode() == spv::OpDecorate ||
5162 Inst->getOpcode() == spv::OpMemberDecorate;
5163 if (is_decoration) {
5164 seen_decorations = true;
5165 return false;
5166 } else {
5167 return seen_decorations;
5168 }
5169 });
5170
David Netoc6f3ab22018-04-06 18:02:31 -04005171 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5172 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005173 for (auto *type : getTypesNeedingArrayStride()) {
5174 Type *elemTy = nullptr;
5175 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5176 elemTy = ptrTy->getElementType();
5177 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5178 elemTy = arrayTy->getArrayElementType();
5179 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5180 elemTy = seqTy->getSequentialElementType();
5181 } else {
5182 errs() << "Unhandled strided type " << *type << "\n";
5183 llvm_unreachable("Unhandled strided type");
5184 }
David Neto1a1a0582017-07-07 12:01:44 -04005185
5186 // Ops[0] = Target ID
5187 // Ops[1] = Decoration (ArrayStride)
5188 // Ops[2] = Stride number (Literal Number)
5189 SPIRVOperandList Ops;
5190
David Neto85082642018-03-24 06:55:20 -07005191 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005192 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005193
5194 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5195 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005196
David Neto87846742018-04-11 17:36:22 -04005197 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005198 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5199 }
David Netoc6f3ab22018-04-06 18:02:31 -04005200
5201 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005202 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5203 ++spec_id) {
5204 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005205 SPIRVOperandList Ops;
5206 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5207 << MkNum(arg_info.spec_id);
5208 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005209 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005210 }
David Neto1a1a0582017-07-07 12:01:44 -04005211}
5212
David Neto22f144c2017-06-12 14:26:21 -04005213glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5214 return StringSwitch<glsl::ExtInst>(Name)
5215 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5216 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5217 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5218 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5219 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5220 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5221 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5222 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5223 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5224 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5225 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5226 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5227 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5228 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5229 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5230 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005231 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5232 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5233 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5234 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5235 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5236 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5237 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5238 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5239 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5240 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5241 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5242 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5243 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5244 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5245 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5246 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5247 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5248 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5249 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5250 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5251 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5252 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5253 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5254 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5255 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5256 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5257 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5258 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5259 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5260 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5261 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5262 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5263 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5264 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5265 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5266 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5267 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5268 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5269 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5270 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5271 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5272 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5273 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5274 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5275 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5276 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5277 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5278 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5279 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5280 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5281 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5282 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5283 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5284 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5285 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5286 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5287 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5288 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5289 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5290 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5291 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5292 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005293 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005294 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5295 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5296 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5297 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5298 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5299 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5300 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5301 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5302 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5303 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5304 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5305 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5306 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5307 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5308 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5309 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5310 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005311 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005312 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005313 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005314 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005315 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005316 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5317 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005318 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005319 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5320 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5321 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005322 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5323 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5324 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5325 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005326 .Default(kGlslExtInstBad);
5327}
5328
5329glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5330 // Check indirect cases.
5331 return StringSwitch<glsl::ExtInst>(Name)
5332 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5333 // Use exact match on float arg because these need a multiply
5334 // of a constant of the right floating point type.
5335 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5336 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5337 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5338 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5339 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5340 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5341 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5342 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005343 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5344 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5345 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5346 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005347 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5348 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5349 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5350 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5351 .Default(kGlslExtInstBad);
5352}
5353
5354glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5355 auto direct = getExtInstEnum(Name);
5356 if (direct != kGlslExtInstBad)
5357 return direct;
5358 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005359}
5360
5361void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5362 out << "%" << Inst->getResultID();
5363}
5364
5365void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5366 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5367 out << "\t" << spv::getOpName(Opcode);
5368}
5369
5370void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5371 SPIRVOperandType OpTy = Op->getType();
5372 switch (OpTy) {
5373 default: {
5374 llvm_unreachable("Unsupported SPIRV Operand Type???");
5375 break;
5376 }
5377 case SPIRVOperandType::NUMBERID: {
5378 out << "%" << Op->getNumID();
5379 break;
5380 }
5381 case SPIRVOperandType::LITERAL_STRING: {
5382 out << "\"" << Op->getLiteralStr() << "\"";
5383 break;
5384 }
5385 case SPIRVOperandType::LITERAL_INTEGER: {
5386 // TODO: Handle LiteralNum carefully.
5387 for (auto Word : Op->getLiteralNum()) {
5388 out << Word;
5389 }
5390 break;
5391 }
5392 case SPIRVOperandType::LITERAL_FLOAT: {
5393 // TODO: Handle LiteralNum carefully.
5394 for (auto Word : Op->getLiteralNum()) {
5395 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5396 SmallString<8> Str;
5397 APF.toString(Str, 6, 2);
5398 out << Str;
5399 }
5400 break;
5401 }
5402 }
5403}
5404
5405void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5406 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5407 out << spv::getCapabilityName(Cap);
5408}
5409
5410void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5411 auto LiteralNum = Op->getLiteralNum();
5412 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5413 out << glsl::getExtInstName(Ext);
5414}
5415
5416void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5417 spv::AddressingModel AddrModel =
5418 static_cast<spv::AddressingModel>(Op->getNumID());
5419 out << spv::getAddressingModelName(AddrModel);
5420}
5421
5422void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5423 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5424 out << spv::getMemoryModelName(MemModel);
5425}
5426
5427void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5428 spv::ExecutionModel ExecModel =
5429 static_cast<spv::ExecutionModel>(Op->getNumID());
5430 out << spv::getExecutionModelName(ExecModel);
5431}
5432
5433void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5434 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5435 out << spv::getExecutionModeName(ExecMode);
5436}
5437
5438void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5439 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5440 out << spv::getSourceLanguageName(SourceLang);
5441}
5442
5443void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5444 spv::FunctionControlMask FuncCtrl =
5445 static_cast<spv::FunctionControlMask>(Op->getNumID());
5446 out << spv::getFunctionControlName(FuncCtrl);
5447}
5448
5449void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5450 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5451 out << getStorageClassName(StClass);
5452}
5453
5454void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5455 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5456 out << getDecorationName(Deco);
5457}
5458
5459void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5460 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5461 out << getBuiltInName(BIn);
5462}
5463
5464void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5465 spv::SelectionControlMask BIn =
5466 static_cast<spv::SelectionControlMask>(Op->getNumID());
5467 out << getSelectionControlName(BIn);
5468}
5469
5470void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5471 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5472 out << getLoopControlName(BIn);
5473}
5474
5475void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5476 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5477 out << getDimName(DIM);
5478}
5479
5480void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5481 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5482 out << getImageFormatName(Format);
5483}
5484
5485void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5486 out << spv::getMemoryAccessName(
5487 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5488}
5489
5490void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5491 auto LiteralNum = Op->getLiteralNum();
5492 spv::ImageOperandsMask Type =
5493 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5494 out << getImageOperandsName(Type);
5495}
5496
5497void SPIRVProducerPass::WriteSPIRVAssembly() {
5498 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5499
5500 for (auto Inst : SPIRVInstList) {
5501 SPIRVOperandList Ops = Inst->getOperands();
5502 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5503
5504 switch (Opcode) {
5505 default: {
5506 llvm_unreachable("Unsupported SPIRV instruction");
5507 break;
5508 }
5509 case spv::OpCapability: {
5510 // Ops[0] = Capability
5511 PrintOpcode(Inst);
5512 out << " ";
5513 PrintCapability(Ops[0]);
5514 out << "\n";
5515 break;
5516 }
5517 case spv::OpMemoryModel: {
5518 // Ops[0] = Addressing Model
5519 // Ops[1] = Memory Model
5520 PrintOpcode(Inst);
5521 out << " ";
5522 PrintAddrModel(Ops[0]);
5523 out << " ";
5524 PrintMemModel(Ops[1]);
5525 out << "\n";
5526 break;
5527 }
5528 case spv::OpEntryPoint: {
5529 // Ops[0] = Execution Model
5530 // Ops[1] = EntryPoint ID
5531 // Ops[2] = Name (Literal String)
5532 // Ops[3] ... Ops[n] = Interface ID
5533 PrintOpcode(Inst);
5534 out << " ";
5535 PrintExecModel(Ops[0]);
5536 for (uint32_t i = 1; i < Ops.size(); i++) {
5537 out << " ";
5538 PrintOperand(Ops[i]);
5539 }
5540 out << "\n";
5541 break;
5542 }
5543 case spv::OpExecutionMode: {
5544 // Ops[0] = Entry Point ID
5545 // Ops[1] = Execution Mode
5546 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5547 PrintOpcode(Inst);
5548 out << " ";
5549 PrintOperand(Ops[0]);
5550 out << " ";
5551 PrintExecMode(Ops[1]);
5552 for (uint32_t i = 2; i < Ops.size(); i++) {
5553 out << " ";
5554 PrintOperand(Ops[i]);
5555 }
5556 out << "\n";
5557 break;
5558 }
5559 case spv::OpSource: {
5560 // Ops[0] = SourceLanguage ID
5561 // Ops[1] = Version (LiteralNum)
5562 PrintOpcode(Inst);
5563 out << " ";
5564 PrintSourceLanguage(Ops[0]);
5565 out << " ";
5566 PrintOperand(Ops[1]);
5567 out << "\n";
5568 break;
5569 }
5570 case spv::OpDecorate: {
5571 // Ops[0] = Target ID
5572 // Ops[1] = Decoration (Block or BufferBlock)
5573 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5574 PrintOpcode(Inst);
5575 out << " ";
5576 PrintOperand(Ops[0]);
5577 out << " ";
5578 PrintDecoration(Ops[1]);
5579 // Handle BuiltIn OpDecorate specially.
5580 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5581 out << " ";
5582 PrintBuiltIn(Ops[2]);
5583 } else {
5584 for (uint32_t i = 2; i < Ops.size(); i++) {
5585 out << " ";
5586 PrintOperand(Ops[i]);
5587 }
5588 }
5589 out << "\n";
5590 break;
5591 }
5592 case spv::OpMemberDecorate: {
5593 // Ops[0] = Structure Type ID
5594 // Ops[1] = Member Index(Literal Number)
5595 // Ops[2] = Decoration
5596 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5597 PrintOpcode(Inst);
5598 out << " ";
5599 PrintOperand(Ops[0]);
5600 out << " ";
5601 PrintOperand(Ops[1]);
5602 out << " ";
5603 PrintDecoration(Ops[2]);
5604 for (uint32_t i = 3; i < Ops.size(); i++) {
5605 out << " ";
5606 PrintOperand(Ops[i]);
5607 }
5608 out << "\n";
5609 break;
5610 }
5611 case spv::OpTypePointer: {
5612 // Ops[0] = Storage Class
5613 // Ops[1] = Element Type ID
5614 PrintResID(Inst);
5615 out << " = ";
5616 PrintOpcode(Inst);
5617 out << " ";
5618 PrintStorageClass(Ops[0]);
5619 out << " ";
5620 PrintOperand(Ops[1]);
5621 out << "\n";
5622 break;
5623 }
5624 case spv::OpTypeImage: {
5625 // Ops[0] = Sampled Type ID
5626 // Ops[1] = Dim ID
5627 // Ops[2] = Depth (Literal Number)
5628 // Ops[3] = Arrayed (Literal Number)
5629 // Ops[4] = MS (Literal Number)
5630 // Ops[5] = Sampled (Literal Number)
5631 // Ops[6] = Image Format ID
5632 PrintResID(Inst);
5633 out << " = ";
5634 PrintOpcode(Inst);
5635 out << " ";
5636 PrintOperand(Ops[0]);
5637 out << " ";
5638 PrintDimensionality(Ops[1]);
5639 out << " ";
5640 PrintOperand(Ops[2]);
5641 out << " ";
5642 PrintOperand(Ops[3]);
5643 out << " ";
5644 PrintOperand(Ops[4]);
5645 out << " ";
5646 PrintOperand(Ops[5]);
5647 out << " ";
5648 PrintImageFormat(Ops[6]);
5649 out << "\n";
5650 break;
5651 }
5652 case spv::OpFunction: {
5653 // Ops[0] : Result Type ID
5654 // Ops[1] : Function Control
5655 // Ops[2] : Function Type ID
5656 PrintResID(Inst);
5657 out << " = ";
5658 PrintOpcode(Inst);
5659 out << " ";
5660 PrintOperand(Ops[0]);
5661 out << " ";
5662 PrintFuncCtrl(Ops[1]);
5663 out << " ";
5664 PrintOperand(Ops[2]);
5665 out << "\n";
5666 break;
5667 }
5668 case spv::OpSelectionMerge: {
5669 // Ops[0] = Merge Block ID
5670 // Ops[1] = Selection Control
5671 PrintOpcode(Inst);
5672 out << " ";
5673 PrintOperand(Ops[0]);
5674 out << " ";
5675 PrintSelectionControl(Ops[1]);
5676 out << "\n";
5677 break;
5678 }
5679 case spv::OpLoopMerge: {
5680 // Ops[0] = Merge Block ID
5681 // Ops[1] = Continue Target ID
5682 // Ops[2] = Selection Control
5683 PrintOpcode(Inst);
5684 out << " ";
5685 PrintOperand(Ops[0]);
5686 out << " ";
5687 PrintOperand(Ops[1]);
5688 out << " ";
5689 PrintLoopControl(Ops[2]);
5690 out << "\n";
5691 break;
5692 }
5693 case spv::OpImageSampleExplicitLod: {
5694 // Ops[0] = Result Type ID
5695 // Ops[1] = Sampled Image ID
5696 // Ops[2] = Coordinate ID
5697 // Ops[3] = Image Operands Type ID
5698 // Ops[4] ... Ops[n] = Operands ID
5699 PrintResID(Inst);
5700 out << " = ";
5701 PrintOpcode(Inst);
5702 for (uint32_t i = 0; i < 3; i++) {
5703 out << " ";
5704 PrintOperand(Ops[i]);
5705 }
5706 out << " ";
5707 PrintImageOperandsType(Ops[3]);
5708 for (uint32_t i = 4; i < Ops.size(); i++) {
5709 out << " ";
5710 PrintOperand(Ops[i]);
5711 }
5712 out << "\n";
5713 break;
5714 }
5715 case spv::OpVariable: {
5716 // Ops[0] : Result Type ID
5717 // Ops[1] : Storage Class
5718 // Ops[2] ... Ops[n] = Initializer IDs
5719 PrintResID(Inst);
5720 out << " = ";
5721 PrintOpcode(Inst);
5722 out << " ";
5723 PrintOperand(Ops[0]);
5724 out << " ";
5725 PrintStorageClass(Ops[1]);
5726 for (uint32_t i = 2; i < Ops.size(); i++) {
5727 out << " ";
5728 PrintOperand(Ops[i]);
5729 }
5730 out << "\n";
5731 break;
5732 }
5733 case spv::OpExtInst: {
5734 // Ops[0] = Result Type ID
5735 // Ops[1] = Set ID (OpExtInstImport ID)
5736 // Ops[2] = Instruction Number (Literal Number)
5737 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5738 PrintResID(Inst);
5739 out << " = ";
5740 PrintOpcode(Inst);
5741 out << " ";
5742 PrintOperand(Ops[0]);
5743 out << " ";
5744 PrintOperand(Ops[1]);
5745 out << " ";
5746 PrintExtInst(Ops[2]);
5747 for (uint32_t i = 3; i < Ops.size(); i++) {
5748 out << " ";
5749 PrintOperand(Ops[i]);
5750 }
5751 out << "\n";
5752 break;
5753 }
5754 case spv::OpCopyMemory: {
5755 // Ops[0] = Addressing Model
5756 // Ops[1] = Memory Model
5757 PrintOpcode(Inst);
5758 out << " ";
5759 PrintOperand(Ops[0]);
5760 out << " ";
5761 PrintOperand(Ops[1]);
5762 out << " ";
5763 PrintMemoryAccess(Ops[2]);
5764 out << " ";
5765 PrintOperand(Ops[3]);
5766 out << "\n";
5767 break;
5768 }
5769 case spv::OpExtension:
5770 case spv::OpControlBarrier:
5771 case spv::OpMemoryBarrier:
5772 case spv::OpBranch:
5773 case spv::OpBranchConditional:
5774 case spv::OpStore:
5775 case spv::OpImageWrite:
5776 case spv::OpReturnValue:
5777 case spv::OpReturn:
5778 case spv::OpFunctionEnd: {
5779 PrintOpcode(Inst);
5780 for (uint32_t i = 0; i < Ops.size(); i++) {
5781 out << " ";
5782 PrintOperand(Ops[i]);
5783 }
5784 out << "\n";
5785 break;
5786 }
5787 case spv::OpExtInstImport:
5788 case spv::OpTypeRuntimeArray:
5789 case spv::OpTypeStruct:
5790 case spv::OpTypeSampler:
5791 case spv::OpTypeSampledImage:
5792 case spv::OpTypeInt:
5793 case spv::OpTypeFloat:
5794 case spv::OpTypeArray:
5795 case spv::OpTypeVector:
5796 case spv::OpTypeBool:
5797 case spv::OpTypeVoid:
5798 case spv::OpTypeFunction:
5799 case spv::OpFunctionParameter:
5800 case spv::OpLabel:
5801 case spv::OpPhi:
5802 case spv::OpLoad:
5803 case spv::OpSelect:
5804 case spv::OpAccessChain:
5805 case spv::OpPtrAccessChain:
5806 case spv::OpInBoundsAccessChain:
5807 case spv::OpUConvert:
5808 case spv::OpSConvert:
5809 case spv::OpConvertFToU:
5810 case spv::OpConvertFToS:
5811 case spv::OpConvertUToF:
5812 case spv::OpConvertSToF:
5813 case spv::OpFConvert:
5814 case spv::OpConvertPtrToU:
5815 case spv::OpConvertUToPtr:
5816 case spv::OpBitcast:
5817 case spv::OpIAdd:
5818 case spv::OpFAdd:
5819 case spv::OpISub:
5820 case spv::OpFSub:
5821 case spv::OpIMul:
5822 case spv::OpFMul:
5823 case spv::OpUDiv:
5824 case spv::OpSDiv:
5825 case spv::OpFDiv:
5826 case spv::OpUMod:
5827 case spv::OpSRem:
5828 case spv::OpFRem:
5829 case spv::OpBitwiseOr:
5830 case spv::OpBitwiseXor:
5831 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005832 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005833 case spv::OpShiftLeftLogical:
5834 case spv::OpShiftRightLogical:
5835 case spv::OpShiftRightArithmetic:
5836 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005837 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005838 case spv::OpCompositeExtract:
5839 case spv::OpVectorExtractDynamic:
5840 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005841 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005842 case spv::OpVectorInsertDynamic:
5843 case spv::OpVectorShuffle:
5844 case spv::OpIEqual:
5845 case spv::OpINotEqual:
5846 case spv::OpUGreaterThan:
5847 case spv::OpUGreaterThanEqual:
5848 case spv::OpULessThan:
5849 case spv::OpULessThanEqual:
5850 case spv::OpSGreaterThan:
5851 case spv::OpSGreaterThanEqual:
5852 case spv::OpSLessThan:
5853 case spv::OpSLessThanEqual:
5854 case spv::OpFOrdEqual:
5855 case spv::OpFOrdGreaterThan:
5856 case spv::OpFOrdGreaterThanEqual:
5857 case spv::OpFOrdLessThan:
5858 case spv::OpFOrdLessThanEqual:
5859 case spv::OpFOrdNotEqual:
5860 case spv::OpFUnordEqual:
5861 case spv::OpFUnordGreaterThan:
5862 case spv::OpFUnordGreaterThanEqual:
5863 case spv::OpFUnordLessThan:
5864 case spv::OpFUnordLessThanEqual:
5865 case spv::OpFUnordNotEqual:
5866 case spv::OpSampledImage:
5867 case spv::OpFunctionCall:
5868 case spv::OpConstantTrue:
5869 case spv::OpConstantFalse:
5870 case spv::OpConstant:
5871 case spv::OpSpecConstant:
5872 case spv::OpConstantComposite:
5873 case spv::OpSpecConstantComposite:
5874 case spv::OpConstantNull:
5875 case spv::OpLogicalOr:
5876 case spv::OpLogicalAnd:
5877 case spv::OpLogicalNot:
5878 case spv::OpLogicalNotEqual:
5879 case spv::OpUndef:
5880 case spv::OpIsInf:
5881 case spv::OpIsNan:
5882 case spv::OpAny:
5883 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005884 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005885 case spv::OpAtomicIAdd:
5886 case spv::OpAtomicISub:
5887 case spv::OpAtomicExchange:
5888 case spv::OpAtomicIIncrement:
5889 case spv::OpAtomicIDecrement:
5890 case spv::OpAtomicCompareExchange:
5891 case spv::OpAtomicUMin:
5892 case spv::OpAtomicSMin:
5893 case spv::OpAtomicUMax:
5894 case spv::OpAtomicSMax:
5895 case spv::OpAtomicAnd:
5896 case spv::OpAtomicOr:
5897 case spv::OpAtomicXor:
5898 case spv::OpDot: {
5899 PrintResID(Inst);
5900 out << " = ";
5901 PrintOpcode(Inst);
5902 for (uint32_t i = 0; i < Ops.size(); i++) {
5903 out << " ";
5904 PrintOperand(Ops[i]);
5905 }
5906 out << "\n";
5907 break;
5908 }
5909 }
5910 }
5911}
5912
5913void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005914 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005915}
5916
5917void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5918 WriteOneWord(Inst->getResultID());
5919}
5920
5921void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5922 // High 16 bit : Word Count
5923 // Low 16 bit : Opcode
5924 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005925 const uint32_t count = Inst->getWordCount();
5926 if (count > 65535) {
5927 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5928 llvm_unreachable("Word count too high");
5929 }
David Neto22f144c2017-06-12 14:26:21 -04005930 Word |= Inst->getWordCount() << 16;
5931 WriteOneWord(Word);
5932}
5933
5934void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5935 SPIRVOperandType OpTy = Op->getType();
5936 switch (OpTy) {
5937 default: {
5938 llvm_unreachable("Unsupported SPIRV Operand Type???");
5939 break;
5940 }
5941 case SPIRVOperandType::NUMBERID: {
5942 WriteOneWord(Op->getNumID());
5943 break;
5944 }
5945 case SPIRVOperandType::LITERAL_STRING: {
5946 std::string Str = Op->getLiteralStr();
5947 const char *Data = Str.c_str();
5948 size_t WordSize = Str.size() / 4;
5949 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5950 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5951 }
5952
5953 uint32_t Remainder = Str.size() % 4;
5954 uint32_t LastWord = 0;
5955 if (Remainder) {
5956 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5957 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5958 }
5959 }
5960
5961 WriteOneWord(LastWord);
5962 break;
5963 }
5964 case SPIRVOperandType::LITERAL_INTEGER:
5965 case SPIRVOperandType::LITERAL_FLOAT: {
5966 auto LiteralNum = Op->getLiteralNum();
5967 // TODO: Handle LiteranNum carefully.
5968 for (auto Word : LiteralNum) {
5969 WriteOneWord(Word);
5970 }
5971 break;
5972 }
5973 }
5974}
5975
5976void SPIRVProducerPass::WriteSPIRVBinary() {
5977 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5978
5979 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005980 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005981 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5982
5983 switch (Opcode) {
5984 default: {
David Neto5c22a252018-03-15 16:07:41 -04005985 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005986 llvm_unreachable("Unsupported SPIRV instruction");
5987 break;
5988 }
5989 case spv::OpCapability:
5990 case spv::OpExtension:
5991 case spv::OpMemoryModel:
5992 case spv::OpEntryPoint:
5993 case spv::OpExecutionMode:
5994 case spv::OpSource:
5995 case spv::OpDecorate:
5996 case spv::OpMemberDecorate:
5997 case spv::OpBranch:
5998 case spv::OpBranchConditional:
5999 case spv::OpSelectionMerge:
6000 case spv::OpLoopMerge:
6001 case spv::OpStore:
6002 case spv::OpImageWrite:
6003 case spv::OpReturnValue:
6004 case spv::OpControlBarrier:
6005 case spv::OpMemoryBarrier:
6006 case spv::OpReturn:
6007 case spv::OpFunctionEnd:
6008 case spv::OpCopyMemory: {
6009 WriteWordCountAndOpcode(Inst);
6010 for (uint32_t i = 0; i < Ops.size(); i++) {
6011 WriteOperand(Ops[i]);
6012 }
6013 break;
6014 }
6015 case spv::OpTypeBool:
6016 case spv::OpTypeVoid:
6017 case spv::OpTypeSampler:
6018 case spv::OpLabel:
6019 case spv::OpExtInstImport:
6020 case spv::OpTypePointer:
6021 case spv::OpTypeRuntimeArray:
6022 case spv::OpTypeStruct:
6023 case spv::OpTypeImage:
6024 case spv::OpTypeSampledImage:
6025 case spv::OpTypeInt:
6026 case spv::OpTypeFloat:
6027 case spv::OpTypeArray:
6028 case spv::OpTypeVector:
6029 case spv::OpTypeFunction: {
6030 WriteWordCountAndOpcode(Inst);
6031 WriteResultID(Inst);
6032 for (uint32_t i = 0; i < Ops.size(); i++) {
6033 WriteOperand(Ops[i]);
6034 }
6035 break;
6036 }
6037 case spv::OpFunction:
6038 case spv::OpFunctionParameter:
6039 case spv::OpAccessChain:
6040 case spv::OpPtrAccessChain:
6041 case spv::OpInBoundsAccessChain:
6042 case spv::OpUConvert:
6043 case spv::OpSConvert:
6044 case spv::OpConvertFToU:
6045 case spv::OpConvertFToS:
6046 case spv::OpConvertUToF:
6047 case spv::OpConvertSToF:
6048 case spv::OpFConvert:
6049 case spv::OpConvertPtrToU:
6050 case spv::OpConvertUToPtr:
6051 case spv::OpBitcast:
6052 case spv::OpIAdd:
6053 case spv::OpFAdd:
6054 case spv::OpISub:
6055 case spv::OpFSub:
6056 case spv::OpIMul:
6057 case spv::OpFMul:
6058 case spv::OpUDiv:
6059 case spv::OpSDiv:
6060 case spv::OpFDiv:
6061 case spv::OpUMod:
6062 case spv::OpSRem:
6063 case spv::OpFRem:
6064 case spv::OpBitwiseOr:
6065 case spv::OpBitwiseXor:
6066 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006067 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006068 case spv::OpShiftLeftLogical:
6069 case spv::OpShiftRightLogical:
6070 case spv::OpShiftRightArithmetic:
6071 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006072 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006073 case spv::OpCompositeExtract:
6074 case spv::OpVectorExtractDynamic:
6075 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006076 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006077 case spv::OpVectorInsertDynamic:
6078 case spv::OpVectorShuffle:
6079 case spv::OpIEqual:
6080 case spv::OpINotEqual:
6081 case spv::OpUGreaterThan:
6082 case spv::OpUGreaterThanEqual:
6083 case spv::OpULessThan:
6084 case spv::OpULessThanEqual:
6085 case spv::OpSGreaterThan:
6086 case spv::OpSGreaterThanEqual:
6087 case spv::OpSLessThan:
6088 case spv::OpSLessThanEqual:
6089 case spv::OpFOrdEqual:
6090 case spv::OpFOrdGreaterThan:
6091 case spv::OpFOrdGreaterThanEqual:
6092 case spv::OpFOrdLessThan:
6093 case spv::OpFOrdLessThanEqual:
6094 case spv::OpFOrdNotEqual:
6095 case spv::OpFUnordEqual:
6096 case spv::OpFUnordGreaterThan:
6097 case spv::OpFUnordGreaterThanEqual:
6098 case spv::OpFUnordLessThan:
6099 case spv::OpFUnordLessThanEqual:
6100 case spv::OpFUnordNotEqual:
6101 case spv::OpExtInst:
6102 case spv::OpIsInf:
6103 case spv::OpIsNan:
6104 case spv::OpAny:
6105 case spv::OpAll:
6106 case spv::OpUndef:
6107 case spv::OpConstantNull:
6108 case spv::OpLogicalOr:
6109 case spv::OpLogicalAnd:
6110 case spv::OpLogicalNot:
6111 case spv::OpLogicalNotEqual:
6112 case spv::OpConstantComposite:
6113 case spv::OpSpecConstantComposite:
6114 case spv::OpConstantTrue:
6115 case spv::OpConstantFalse:
6116 case spv::OpConstant:
6117 case spv::OpSpecConstant:
6118 case spv::OpVariable:
6119 case spv::OpFunctionCall:
6120 case spv::OpSampledImage:
6121 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006122 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006123 case spv::OpSelect:
6124 case spv::OpPhi:
6125 case spv::OpLoad:
6126 case spv::OpAtomicIAdd:
6127 case spv::OpAtomicISub:
6128 case spv::OpAtomicExchange:
6129 case spv::OpAtomicIIncrement:
6130 case spv::OpAtomicIDecrement:
6131 case spv::OpAtomicCompareExchange:
6132 case spv::OpAtomicUMin:
6133 case spv::OpAtomicSMin:
6134 case spv::OpAtomicUMax:
6135 case spv::OpAtomicSMax:
6136 case spv::OpAtomicAnd:
6137 case spv::OpAtomicOr:
6138 case spv::OpAtomicXor:
6139 case spv::OpDot: {
6140 WriteWordCountAndOpcode(Inst);
6141 WriteOperand(Ops[0]);
6142 WriteResultID(Inst);
6143 for (uint32_t i = 1; i < Ops.size(); i++) {
6144 WriteOperand(Ops[i]);
6145 }
6146 break;
6147 }
6148 }
6149 }
6150}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006151
6152bool SPIRVProducerPass::IsTypeNullable(const Type* type) const {
6153 switch (type->getTypeID()) {
6154 case Type::HalfTyID:
6155 case Type::FloatTyID:
6156 case Type::DoubleTyID:
6157 case Type::IntegerTyID:
6158 case Type::VectorTyID:
6159 return true;
6160 case Type::PointerTyID: {
6161 const PointerType *pointer_type = cast<PointerType>(type);
6162 if (pointer_type->getPointerAddressSpace() !=
6163 AddressSpace::UniformConstant) {
6164 auto pointee_type = pointer_type->getPointerElementType();
6165 if (pointee_type->isStructTy() &&
6166 cast<StructType>(pointee_type)->isOpaque()) {
6167 // Images and samplers are not nullable.
6168 return false;
6169 }
6170 }
6171 return true;
6172 }
6173 case Type::ArrayTyID:
6174 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6175 case Type::StructTyID: {
6176 const StructType* struct_type = cast<StructType>(type);
6177 // Images and samplers are not nullable.
6178 if (struct_type->isOpaque()) return false;
6179 for (const auto element : struct_type->elements()) {
6180 if (!IsTypeNullable(element)) return false;
6181 }
6182 return true;
6183 }
6184 default:
6185 return false;
6186 }
6187}