blob: 2297802d66c1a492b94d8ae9e4c2cdeab4147c93 [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>
21
David Neto5c22a252018-03-15 16:07:41 -040022#include <unordered_set>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
24
David Neto482550a2018-03-24 05:21:07 -070025#include <clspv/Option.h>
David Neto22f144c2017-06-12 14:26:21 -040026#include <clspv/Passes.h>
27
28#include <llvm/ADT/StringSwitch.h>
29#include <llvm/ADT/UniqueVector.h>
30#include <llvm/Analysis/LoopInfo.h>
31#include <llvm/IR/Constants.h>
32#include <llvm/IR/Dominators.h>
33#include <llvm/IR/Instructions.h>
34#include <llvm/IR/Metadata.h>
35#include <llvm/IR/Module.h>
36#include <llvm/Pass.h>
David Netocd8ca5f2017-10-02 23:34:11 -040037#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040038#include <llvm/Support/raw_ostream.h>
39#include <llvm/Transforms/Utils/Cloning.h>
40
David Neto85082642018-03-24 06:55:20 -070041#include "spirv/1.0/spirv.hpp"
42#include "clspv/AddressSpace.h"
43#include "clspv/spirv_c_strings.hpp"
44#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040045
David Neto4feb7a42017-10-06 17:29:42 -040046#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070047#include "ConstantEmitter.h"
David Neto78383442018-06-15 20:31:56 -040048#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040049
David Neto22f144c2017-06-12 14:26:21 -040050#include <list>
David Neto0676e6f2017-07-11 18:47:44 -040051#include <iomanip>
David Neto26aaf622017-10-23 18:11:53 -040052#include <set>
David Neto0676e6f2017-07-11 18:47:44 -040053#include <sstream>
David Neto257c3892018-04-11 13:19:45 -040054#include <string>
David Neto26aaf622017-10-23 18:11:53 -040055#include <tuple>
David Neto44795152017-07-13 15:45:28 -040056#include <utility>
David Neto22f144c2017-06-12 14:26:21 -040057
58#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),
David Neto78383442018-06-15 20:31:56 -0400232 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);
David Neto22f144c2017-06-12 14:26:21 -0400301 bool FindExtInst(Module &M);
302 void FindTypePerGlobalVar(GlobalVariable &GV);
303 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400304 void FindTypesForSamplerMap(Module &M);
305 void FindTypesForResourceVars(Module &M);
David Neto19a1bad2017-08-25 15:01:41 -0400306 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
307 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400308 void FindType(Type *Ty);
309 void FindConstantPerGlobalVar(GlobalVariable &GV);
310 void FindConstantPerFunc(Function &F);
311 void FindConstant(Value *V);
312 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400313 // Generates instructions for SPIR-V types corresponding to the LLVM types
314 // saved in the |Types| member. A type follows its subtypes. IDs are
315 // allocated sequentially starting with the current value of nextID, and
316 // with a type following its subtypes. Also updates nextID to just beyond
317 // the last generated ID.
David Netoc6f3ab22018-04-06 18:02:31 -0400318 void GenerateSPIRVTypes(LLVMContext& context, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400319 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400320 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400321 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400322 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400323 // Generate descriptor map entries for resource variables associated with
324 // arguments to F.
325 void GenerateDescriptorMapInfo(const DataLayout& DL, Function& F);
David Neto22f144c2017-06-12 14:26:21 -0400326 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400327 // Generate OpVariables for %clspv.resource.var.* calls.
328 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400329 void GenerateFuncPrologue(Function &F);
330 void GenerateFuncBody(Function &F);
331 void GenerateInstForArg(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
385private:
386 static char ID;
David Neto44795152017-07-13 15:45:28 -0400387 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400388 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400389
390 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
391 // convert to other formats on demand?
392
393 // When emitting a C initialization list, the WriteSPIRVBinary method
394 // will actually write its words to this vector via binaryTempOut.
395 SmallVector<char, 100> binaryTempUnderlyingVector;
396 raw_svector_ostream binaryTempOut;
397
398 // Binary output writes to this stream, which might be |out| or
399 // |binaryTempOut|. It's the latter when we really want to write a C
400 // initializer list.
401 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400402 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400403 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400404 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400405 uint64_t patchBoundOffset;
406 uint32_t nextID;
407
David Neto19a1bad2017-08-25 15:01:41 -0400408 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400409 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400410 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400411 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400412 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400413 TypeList Types;
414 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400415 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400416 ValueMapType ValueMap;
417 ValueMapType AllocatedValueMap;
418 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400419
David Neto22f144c2017-06-12 14:26:21 -0400420 EntryPointVecType EntryPointVec;
421 DeferredInstVecType DeferredInstVec;
422 ValueList EntryPointInterfacesVec;
423 uint32_t OpExtInstImportID;
424 std::vector<uint32_t> BuiltinDimensionVec;
425 bool HasVariablePointers;
426 Type *SamplerTy;
David Neto862b7d82018-06-14 18:48:37 -0400427 DenseMap<unsigned,uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700428
429 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700430 // will map F's type to (G, index of the parameter), where in a first phase
431 // G is F's type. During FindTypePerFunc, G will be changed to F's type
432 // but replacing the pointer-to-constant parameter with
433 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700434 // TODO(dneto): This doesn't seem general enough? A function might have
435 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400436 GlobalConstFuncMapType GlobalConstFuncTypeMap;
437 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400438 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700439 // or array types, and which point into transparent memory (StorageBuffer
440 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400441 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700442 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400443
444 // This is truly ugly, but works around what look like driver bugs.
445 // For get_local_size, an earlier part of the flow has created a module-scope
446 // variable in Private address space to hold the value for the workgroup
447 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
448 // When this is present, save the IDs of the initializer value and variable
449 // in these two variables. We only ever do a vector load from it, and
450 // when we see one of those, substitute just the value of the intializer.
451 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700452 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400453 uint32_t WorkgroupSizeValueID;
454 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400455
David Neto862b7d82018-06-14 18:48:37 -0400456 // Bookkeeping for mapping kernel arguments to resource variables.
457 struct ResourceVarInfo {
458 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
459 Function *fn, clspv::ArgKind arg_kind_arg)
460 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
461 var_fn(fn), arg_kind(arg_kind_arg),
462 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
463 const int index; // Index into ResourceVarInfoList
464 const unsigned descriptor_set;
465 const unsigned binding;
466 Function *const var_fn; // The @clspv.resource.var.* function.
467 const clspv::ArgKind arg_kind;
468 const unsigned addr_space; // The LLVM address space
469 // The SPIR-V ID of the OpVariable. Not populated at construction time.
470 uint32_t var_id = 0;
471 };
472 // A list of resource var info. Each one correponds to a module-scope
473 // resource variable we will have to create. Resource var indices are
474 // indices into this vector.
475 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
476 // This is a vector of pointers of all the resource vars, but ordered by
477 // kernel function, and then by argument.
478 UniqueVector<ResourceVarInfo*> ModuleOrderedResourceVars;
479 // Map a function to the ordered list of resource variables it uses, one for
480 // each argument. If an argument does not use a resource variable, it
481 // will have a null pointer entry.
482 using FunctionToResourceVarsMapType =
483 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
484 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
485
486 // What LLVM types map to SPIR-V types needing layout? These are the
487 // arrays and structures supporting storage buffers and uniform buffers.
488 TypeList TypesNeedingLayout;
489 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
490 UniqueVector<StructType *> StructTypesNeedingBlock;
491 // For a call that represents a load from an opaque type (samplers, images),
492 // map it to the variable id it should load from.
493 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700494
David Netoc6f3ab22018-04-06 18:02:31 -0400495 // An ordered list of the kernel arguments of type pointer-to-local.
496 using LocalArgList = SmallVector<const Argument*, 8>;
497 LocalArgList LocalArgs;
498 // Information about a pointer-to-local argument.
499 struct LocalArgInfo {
500 // The SPIR-V ID of the array variable.
501 uint32_t variable_id;
502 // The element type of the
503 Type* elem_type;
504 // The ID of the array type.
505 uint32_t array_size_id;
506 // The ID of the array type.
507 uint32_t array_type_id;
508 // The ID of the pointer to the array type.
509 uint32_t ptr_array_type_id;
510 // The ID of the pointer to the first element of the array.
511 uint32_t first_elem_ptr_id;
512 // The specialization constant ID of the array size.
513 int spec_id;
514 };
515 // A mapping from a pointer-to-local argument value to a LocalArgInfo value.
516 DenseMap<const Argument*, LocalArgInfo> LocalArgMap;
517
David Netoc6f3ab22018-04-06 18:02:31 -0400518 // A mapping from pointer-to-local argument to a specialization constant ID
519 // for that argument's array size. This is generated from AllocatArgSpecIds.
520 ArgIdMapType ArgSpecIdMap;
David Neto257c3892018-04-11 13:19:45 -0400521
522 // The ID of 32-bit integer zero constant. This is only valid after
523 // GenerateSPIRVConstants has run.
524 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400525};
526
527char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400528
David Neto22f144c2017-06-12 14:26:21 -0400529}
530
531namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400532ModulePass *
533createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
534 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
535 bool outputAsm, bool outputCInitList) {
536 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
537 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400538}
David Netoc2c368d2017-06-30 16:50:17 -0400539} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400540
541bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400542 binaryOut = outputCInitList ? &binaryTempOut : &out;
543
David Neto257c3892018-04-11 13:19:45 -0400544 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
545
David Netoc6f3ab22018-04-06 18:02:31 -0400546 ArgSpecIdMap = AllocateArgSpecIds(module);
547
David Neto22f144c2017-06-12 14:26:21 -0400548 // SPIR-V always begins with its header information
549 outputHeader();
550
David Netoc6f3ab22018-04-06 18:02:31 -0400551 const DataLayout &DL = module.getDataLayout();
552
David Neto22f144c2017-06-12 14:26:21 -0400553 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400554 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400555
David Neto22f144c2017-06-12 14:26:21 -0400556 // Collect information on global variables too.
557 for (GlobalVariable &GV : module.globals()) {
558 // If the GV is one of our special __spirv_* variables, remove the
559 // initializer as it was only placed there to force LLVM to not throw the
560 // value away.
561 if (GV.getName().startswith("__spirv_")) {
562 GV.setInitializer(nullptr);
563 }
564
565 // Collect types' information from global variable.
566 FindTypePerGlobalVar(GV);
567
568 // Collect constant information from global variable.
569 FindConstantPerGlobalVar(GV);
570
571 // If the variable is an input, entry points need to know about it.
572 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400573 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400574 }
575 }
576
David Netoc6f3ab22018-04-06 18:02:31 -0400577 // Find types related to pointer-to-local arguments.
578 for (auto& arg_spec_id_pair : ArgSpecIdMap) {
579 const Argument* arg = arg_spec_id_pair.first;
580 FindType(arg->getType());
581 FindType(arg->getType()->getPointerElementType());
582 }
583
David Neto22f144c2017-06-12 14:26:21 -0400584 // If there are extended instructions, generate OpExtInstImport.
585 if (FindExtInst(module)) {
586 GenerateExtInstImport();
587 }
588
589 // Generate SPIRV instructions for types.
David Netoc6f3ab22018-04-06 18:02:31 -0400590 GenerateSPIRVTypes(module.getContext(), DL);
David Neto22f144c2017-06-12 14:26:21 -0400591
592 // Generate SPIRV constants.
593 GenerateSPIRVConstants();
594
595 // If we have a sampler map, we might have literal samplers to generate.
596 if (0 < getSamplerMap().size()) {
597 GenerateSamplers(module);
598 }
599
600 // Generate SPIRV variables.
601 for (GlobalVariable &GV : module.globals()) {
602 GenerateGlobalVar(GV);
603 }
David Neto862b7d82018-06-14 18:48:37 -0400604 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400605 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400606
607 // Generate SPIRV instructions for each function.
608 for (Function &F : module) {
609 if (F.isDeclaration()) {
610 continue;
611 }
612
David Neto862b7d82018-06-14 18:48:37 -0400613 GenerateDescriptorMapInfo(DL, F);
614
David Neto22f144c2017-06-12 14:26:21 -0400615 // Generate Function Prologue.
616 GenerateFuncPrologue(F);
617
618 // Generate SPIRV instructions for function body.
619 GenerateFuncBody(F);
620
621 // Generate Function Epilogue.
622 GenerateFuncEpilogue();
623 }
624
625 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400626 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400627
628 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400629 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400630
631 if (outputAsm) {
632 WriteSPIRVAssembly();
633 } else {
634 WriteSPIRVBinary();
635 }
636
637 // We need to patch the SPIR-V header to set bound correctly.
638 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400639
640 if (outputCInitList) {
641 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400642 std::ostringstream os;
643
David Neto57fb0b92017-08-04 15:35:09 -0400644 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400645 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400646 os << ",\n";
647 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400648 first = false;
649 };
650
651 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400652 const std::string str(binaryTempOut.str());
653 for (unsigned i = 0; i < str.size(); i += 4) {
654 const uint32_t a = static_cast<unsigned char>(str[i]);
655 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
656 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
657 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
658 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400659 }
660 os << "}\n";
661 out << os.str();
662 }
663
David Neto22f144c2017-06-12 14:26:21 -0400664 return false;
665}
666
667void SPIRVProducerPass::outputHeader() {
668 if (outputAsm) {
669 // for ASM output the header goes into 5 comments at the beginning of the
670 // file
671 out << "; SPIR-V\n";
672
673 // the major version number is in the 2nd highest byte
674 const uint32_t major = (spv::Version >> 16) & 0xFF;
675
676 // the minor version number is in the 2nd lowest byte
677 const uint32_t minor = (spv::Version >> 8) & 0xFF;
678 out << "; Version: " << major << "." << minor << "\n";
679
680 // use Codeplay's vendor ID
681 out << "; Generator: Codeplay; 0\n";
682
683 out << "; Bound: ";
684
685 // we record where we need to come back to and patch in the bound value
686 patchBoundOffset = out.tell();
687
688 // output one space per digit for the max size of a 32 bit unsigned integer
689 // (which is the maximum ID we could possibly be using)
690 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
691 out << " ";
692 }
693
694 out << "\n";
695
696 out << "; Schema: 0\n";
697 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400698 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400699 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400700 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400701 sizeof(spv::Version));
702
703 // use Codeplay's vendor ID
704 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400705 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400706
707 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400708 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400709
710 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400711 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400712
713 // output the schema (reserved for use and must be 0)
714 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400715 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400716 }
717}
718
719void SPIRVProducerPass::patchHeader() {
720 if (outputAsm) {
721 // get the string representation of the max bound used (nextID will be the
722 // max ID used)
723 auto asString = std::to_string(nextID);
724 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
725 } else {
726 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400727 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
728 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400729 }
730}
731
David Netoc6f3ab22018-04-06 18:02:31 -0400732void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400733 // This function generates LLVM IR for function such as global variable for
734 // argument, constant and pointer type for argument access. These information
735 // is artificial one because we need Vulkan SPIR-V output. This function is
736 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400737 LLVMContext &Context = M.getContext();
738
739 // Map for avoiding to generate struct type with same fields.
740 DenseMap<Type *, Type *> ArgTyMap;
741
David Neto862b7d82018-06-14 18:48:37 -0400742 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400743
David Neto862b7d82018-06-14 18:48:37 -0400744 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400745
746 bool HasWorkGroupBuiltin = false;
747 for (GlobalVariable &GV : M.globals()) {
748 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
749 if (spv::BuiltInWorkgroupSize == BuiltinType) {
750 HasWorkGroupBuiltin = true;
751 }
752 }
753
David Neto862b7d82018-06-14 18:48:37 -0400754 FindTypesForSamplerMap(M);
755 FindTypesForResourceVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400756
David Neto862b7d82018-06-14 18:48:37 -0400757 // TODO(dneto): Delete the next 3 vars.
758
759 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400760 // Map kernel functions to their ordinal number in the compilation unit.
761 UniqueVector<Function*> KernelOrdinal;
762
763 // Map the global variables created for kernel args to their creation
764 // order.
765 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
766
David Neto862b7d82018-06-14 18:48:37 -0400767 // For each kernel argument type, record the kernel arg global resource
768 // variables generated for that type, the function in which that variable
769 // was most recently used, and the binding number it took. For
770 // reproducibility, we track things by ordinal number (rather than pointer),
771 // and we use a std::set rather than DenseSet since std::set maintains an
772 // ordering. Each tuple is the ordinals of the kernel function, the binding
773 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400774 //
775 // This table lets us reuse module-scope StorageBuffer variables between
776 // different kernels.
777 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
778 GVarsForType;
779
David Neto862b7d82018-06-14 18:48:37 -0400780 // These function calls need a <2 x i32> as an intermediate result but not
781 // the final result.
782 std::unordered_set<std::string> NeedsIVec2{
783 "_Z15get_image_width14ocl_image2d_ro",
784 "_Z15get_image_width14ocl_image2d_wo",
785 "_Z16get_image_height14ocl_image2d_ro",
786 "_Z16get_image_height14ocl_image2d_wo",
787 };
788
David Neto22f144c2017-06-12 14:26:21 -0400789 for (Function &F : M) {
790 // Handle kernel function first.
791 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
792 continue;
793 }
David Neto26aaf622017-10-23 18:11:53 -0400794 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400795
796 for (BasicBlock &BB : F) {
797 for (Instruction &I : BB) {
798 if (I.getOpcode() == Instruction::ZExt ||
799 I.getOpcode() == Instruction::SExt ||
800 I.getOpcode() == Instruction::UIToFP) {
801 // If there is zext with i1 type, it will be changed to OpSelect. The
802 // OpSelect needs constant 0 and 1 so the constants are added here.
803
804 auto OpTy = I.getOperand(0)->getType();
805
806 if (OpTy->isIntegerTy(1) ||
807 (OpTy->isVectorTy() &&
808 OpTy->getVectorElementType()->isIntegerTy(1))) {
809 if (I.getOpcode() == Instruction::ZExt) {
810 APInt One(32, 1);
811 FindConstant(Constant::getNullValue(I.getType()));
812 FindConstant(Constant::getIntegerValue(I.getType(), One));
813 } else if (I.getOpcode() == Instruction::SExt) {
814 APInt MinusOne(32, UINT64_MAX, true);
815 FindConstant(Constant::getNullValue(I.getType()));
816 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
817 } else {
818 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
819 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
820 }
821 }
822 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400823 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400824
825 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400826 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400827 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400828 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400829 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
830 TypeMapType &OpImageTypeMap = getImageTypeMap();
831 Type *ImageTy =
832 Call->getArgOperand(0)->getType()->getPointerElementType();
833 OpImageTypeMap[ImageTy] = 0;
834
835 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
836 }
David Neto5c22a252018-03-15 16:07:41 -0400837
David Neto862b7d82018-06-14 18:48:37 -0400838 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400839 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
840 }
David Neto22f144c2017-06-12 14:26:21 -0400841 }
842 }
843 }
844
David Neto22f144c2017-06-12 14:26:21 -0400845 if (const MDNode *MD =
846 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
847 // We generate constants if the WorkgroupSize builtin is being used.
848 if (HasWorkGroupBuiltin) {
849 // Collect constant information for work group size.
850 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
851 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
852 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
853 }
854 }
855
David Neto862b7d82018-06-14 18:48:37 -0400856 // Allocated IDs for pointer-to-local arguments. We'll create module
857 // scope variables for them later. All other arguments have no uses
858 // since they were converted to calls to clspv.resource.var.* functions.
David Neto22f144c2017-06-12 14:26:21 -0400859 bool HasArgUser = false;
David Neto22f144c2017-06-12 14:26:21 -0400860 for (const Argument &Arg : F.args()) {
David Neto862b7d82018-06-14 18:48:37 -0400861 if (Arg.use_empty())
862 continue;
863 HasArgUser = true;
864
David Neto22f144c2017-06-12 14:26:21 -0400865 Type *ArgTy = Arg.getType();
David Neto862b7d82018-06-14 18:48:37 -0400866 // Only pointer-to-local arguments reach here.
867 if (!IsLocalPtr(ArgTy)) {
868 errs() << "Ooops. Expected only pointer-to-local arguments to have uses. Got " << Arg << "\n";
869 llvm_unreachable("Expected only pointer-to-local arguments to have uses");
David Netoe439d702018-03-23 13:14:08 -0700870 }
871
David Neto862b7d82018-06-14 18:48:37 -0400872 auto spec_id = ArgSpecIdMap[&Arg];
873 assert(spec_id > 0);
874 LocalArgMap[&Arg] =
875 LocalArgInfo{nextID, ArgTy->getPointerElementType(),
876 nextID + 1, nextID + 2,
877 nextID + 3, nextID + 4,
878 spec_id};
879 LocalArgs.push_back(&Arg);
880 nextID += 5;
David Neto22f144c2017-06-12 14:26:21 -0400881
David Neto22f144c2017-06-12 14:26:21 -0400882 }
883
884 if (HasArgUser) {
885 // Generate constant 0 for OpAccessChain of argument.
886 Type *IdxTy = Type::getInt32Ty(Context);
887 FindConstant(ConstantInt::get(IdxTy, 0));
888 FindType(IdxTy);
889 }
890
891 // Collect types' information from function.
892 FindTypePerFunc(F);
893
894 // Collect constant information from function.
895 FindConstantPerFunc(F);
896 }
897
898 for (Function &F : M) {
899 // Handle non-kernel functions.
900 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
901 continue;
902 }
903
904 for (BasicBlock &BB : F) {
905 for (Instruction &I : BB) {
906 if (I.getOpcode() == Instruction::ZExt ||
907 I.getOpcode() == Instruction::SExt ||
908 I.getOpcode() == Instruction::UIToFP) {
909 // If there is zext with i1 type, it will be changed to OpSelect. The
910 // OpSelect needs constant 0 and 1 so the constants are added here.
911
912 auto OpTy = I.getOperand(0)->getType();
913
914 if (OpTy->isIntegerTy(1) ||
915 (OpTy->isVectorTy() &&
916 OpTy->getVectorElementType()->isIntegerTy(1))) {
917 if (I.getOpcode() == Instruction::ZExt) {
918 APInt One(32, 1);
919 FindConstant(Constant::getNullValue(I.getType()));
920 FindConstant(Constant::getIntegerValue(I.getType(), One));
921 } else if (I.getOpcode() == Instruction::SExt) {
922 APInt MinusOne(32, UINT64_MAX, true);
923 FindConstant(Constant::getNullValue(I.getType()));
924 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
925 } else {
926 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
927 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
928 }
929 }
930 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
931 Function *Callee = Call->getCalledFunction();
932
933 // Handle image type specially.
934 if (Callee->getName().equals(
935 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
936 Callee->getName().equals(
937 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
938 TypeMapType &OpImageTypeMap = getImageTypeMap();
939 Type *ImageTy =
940 Call->getArgOperand(0)->getType()->getPointerElementType();
941 OpImageTypeMap[ImageTy] = 0;
942
943 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
944 }
945 }
946 }
947 }
948
949 if (M.getTypeByName("opencl.image2d_ro_t") ||
950 M.getTypeByName("opencl.image2d_wo_t") ||
951 M.getTypeByName("opencl.image3d_ro_t") ||
952 M.getTypeByName("opencl.image3d_wo_t")) {
953 // Assume Image type's sampled type is float type.
954 FindType(Type::getFloatTy(Context));
955 }
956
957 // Collect types' information from function.
958 FindTypePerFunc(F);
959
960 // Collect constant information from function.
961 FindConstantPerFunc(F);
962 }
963}
964
David Neto862b7d82018-06-14 18:48:37 -0400965void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
966 SmallVector<GlobalVariable *, 8> GVList;
967 SmallVector<GlobalVariable *, 8> DeadGVList;
968 for (GlobalVariable &GV : M.globals()) {
969 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
970 if (GV.use_empty()) {
971 DeadGVList.push_back(&GV);
972 } else {
973 GVList.push_back(&GV);
974 }
975 }
976 }
977
978 // Remove dead global __constant variables.
979 for (auto GV : DeadGVList) {
980 GV->eraseFromParent();
981 }
982 DeadGVList.clear();
983
984 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
985 // For now, we only support a single storage buffer.
986 if (GVList.size() > 0) {
987 assert(GVList.size() == 1);
988 const auto *GV = GVList[0];
989 const auto constants_byte_size =
990 (DL.getTypeSizeInBits(GV->getInitializer()->getType())) / 8;
991 const size_t kConstantMaxSize = 65536;
992 if (constants_byte_size > kConstantMaxSize) {
993 outs() << "Max __constant capacity of " << kConstantMaxSize
994 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
995 llvm_unreachable("Max __constant capacity exceeded");
996 }
997 }
998 } else {
999 // Change global constant variable's address space to ModuleScopePrivate.
1000 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1001 for (auto GV : GVList) {
1002 // Create new gv with ModuleScopePrivate address space.
1003 Type *NewGVTy = GV->getType()->getPointerElementType();
1004 GlobalVariable *NewGV = new GlobalVariable(
1005 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
1006 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
1007 NewGV->takeName(GV);
1008
1009 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
1010 SmallVector<User *, 8> CandidateUsers;
1011
1012 auto record_called_function_type_as_user =
1013 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
1014 // Find argument index.
1015 unsigned index = 0;
1016 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
1017 if (gv == call->getOperand(i)) {
1018 // TODO(dneto): Should we break here?
1019 index = i;
1020 }
1021 }
1022
1023 // Record function type with global constant.
1024 GlobalConstFuncTyMap[call->getFunctionType()] =
1025 std::make_pair(call->getFunctionType(), index);
1026 };
1027
1028 for (User *GVU : GVUsers) {
1029 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
1030 record_called_function_type_as_user(GV, Call);
1031 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
1032 // Check GEP users.
1033 for (User *GEPU : GEP->users()) {
1034 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1035 record_called_function_type_as_user(GEP, GEPCall);
1036 }
1037 }
1038 }
1039
1040 CandidateUsers.push_back(GVU);
1041 }
1042
1043 for (User *U : CandidateUsers) {
1044 // Update users of gv with new gv.
1045 U->replaceUsesOfWith(GV, NewGV);
1046 }
1047
1048 // Delete original gv.
1049 GV->eraseFromParent();
1050 }
1051 }
1052}
1053
1054void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &DL) {
1055 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1056 ValueMapType &VMap = getValueMap();
1057
1058 ResourceVarInfoList.clear();
1059 FunctionToResourceVarsMap.clear();
1060 ModuleOrderedResourceVars.reset();
1061 // Normally, there is one resource variable per clspv.resource.var.*
1062 // function, since that is unique'd by arg type and index. By design,
1063 // we can share these resource variables across kernels because all
1064 // kernels use the same descriptor set.
1065 //
1066 // But if the user requested distinct descriptor sets per kernel, then
1067 // the descriptor allocator has made different (set,binding) pairs for
1068 // the same (type,arg_index) pair. Since we can decorate a resource
1069 // variable with only exactly one DescriptorSet and Binding, we are
1070 // forced in this case to make distinct resource variables whenever
1071 // the same clspv.reource.var.X function is seen with disintct
1072 // (set,binding) values.
1073 const bool always_distinct_sets =
1074 clspv::Option::DistinctKernelDescriptorSets();
1075 for (Function &F : M) {
1076 // Rely on the fact the resource var functions have a stable ordering
1077 // in the module.
1078 if (F.getName().startswith("clspv.resource.var.")) {
1079 // Find all calls to this function with distinct set and binding pairs.
1080 // Save them in ResourceVarInfoList.
1081
1082 // Determine uniqueness of the (set,binding) pairs only withing this
1083 // one resource-var builtin function.
1084 using SetAndBinding = std::pair<unsigned, unsigned>;
1085 // Maps set and binding to the resource var info.
1086 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1087 bool first_use = true;
1088 for (auto &U : F.uses()) {
1089 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1090 const auto set = unsigned(
1091 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1092 const auto binding = unsigned(
1093 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1094 const auto arg_kind = clspv::ArgKind(
1095 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1096 const auto arg_index = unsigned(
1097 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1098
1099 // Find or make the resource var info for this combination.
1100 ResourceVarInfo *rv = nullptr;
1101 if (always_distinct_sets) {
1102 // Make a new resource var any time we see a different
1103 // (set,binding) pair.
1104 SetAndBinding key{set, binding};
1105 auto where = set_and_binding_map.find(key);
1106 if (where == set_and_binding_map.end()) {
1107 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1108 binding, &F, arg_kind);
1109 ResourceVarInfoList.emplace_back(rv);
1110 set_and_binding_map[key] = rv;
1111 } else {
1112 rv = where->second;
1113 }
1114 } else {
1115 // The default is to make exactly one resource for each
1116 // clspv.resource.var.* function.
1117 if (first_use) {
1118 first_use = false;
1119 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1120 binding, &F, arg_kind);
1121 ResourceVarInfoList.emplace_back(rv);
1122 } else {
1123 rv = ResourceVarInfoList.back().get();
1124 }
1125 }
1126
1127 // Now populate FunctionToResourceVarsMap.
1128 auto &mapping =
1129 FunctionToResourceVarsMap[call->getParent()->getParent()];
1130 while (mapping.size() <= arg_index) {
1131 mapping.push_back(nullptr);
1132 }
1133 mapping[arg_index] = rv;
1134 }
1135 }
1136 }
1137 }
1138
1139 // Populate ModuleOrderedResourceVars.
1140 for (Function &F : M) {
1141 auto where = FunctionToResourceVarsMap.find(&F);
1142 if (where != FunctionToResourceVarsMap.end()) {
1143 for (auto &rv : where->second) {
1144 if (rv != nullptr) {
1145 ModuleOrderedResourceVars.insert(rv);
1146 }
1147 }
1148 }
1149 }
1150 if (ShowResourceVars) {
1151 for (auto *info : ModuleOrderedResourceVars) {
1152 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1153 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1154 << "\n";
1155 }
1156 }
1157}
1158
David Neto22f144c2017-06-12 14:26:21 -04001159bool SPIRVProducerPass::FindExtInst(Module &M) {
1160 LLVMContext &Context = M.getContext();
1161 bool HasExtInst = false;
1162
1163 for (Function &F : M) {
1164 for (BasicBlock &BB : F) {
1165 for (Instruction &I : BB) {
1166 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1167 Function *Callee = Call->getCalledFunction();
1168 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001169 auto callee_name = Callee->getName();
1170 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1171 const glsl::ExtInst IndirectEInst =
1172 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001173
David Neto3fbb4072017-10-16 11:28:14 -04001174 HasExtInst |=
1175 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1176
1177 if (IndirectEInst) {
1178 // Register extra constants if needed.
1179
1180 // Registers a type and constant for computing the result of the
1181 // given instruction. If the result of the instruction is a vector,
1182 // then make a splat vector constant with the same number of
1183 // elements.
1184 auto register_constant = [this, &I](Constant *constant) {
1185 FindType(constant->getType());
1186 FindConstant(constant);
1187 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1188 // Register the splat vector of the value with the same
1189 // width as the result of the instruction.
1190 auto *vec_constant = ConstantVector::getSplat(
1191 static_cast<unsigned>(vectorTy->getNumElements()),
1192 constant);
1193 FindConstant(vec_constant);
1194 FindType(vec_constant->getType());
1195 }
1196 };
1197 switch (IndirectEInst) {
1198 case glsl::ExtInstFindUMsb:
1199 // clz needs OpExtInst and OpISub with constant 31, or splat
1200 // vector of 31. Add it to the constant list here.
1201 register_constant(
1202 ConstantInt::get(Type::getInt32Ty(Context), 31));
1203 break;
1204 case glsl::ExtInstAcos:
1205 case glsl::ExtInstAsin:
1206 case glsl::ExtInstAtan2:
1207 // We need 1/pi for acospi, asinpi, atan2pi.
1208 register_constant(
1209 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1210 break;
1211 default:
1212 assert(false && "internally inconsistent");
1213 }
David Neto22f144c2017-06-12 14:26:21 -04001214 }
1215 }
1216 }
1217 }
1218 }
1219
1220 return HasExtInst;
1221}
1222
1223void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1224 // Investigate global variable's type.
1225 FindType(GV.getType());
1226}
1227
1228void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1229 // Investigate function's type.
1230 FunctionType *FTy = F.getFunctionType();
1231
1232 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1233 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001234 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001235 if (GlobalConstFuncTyMap.count(FTy)) {
1236 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1237 SmallVector<Type *, 4> NewFuncParamTys;
1238 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1239 Type *ParamTy = FTy->getParamType(i);
1240 if (i == GVCstArgIdx) {
1241 Type *EleTy = ParamTy->getPointerElementType();
1242 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1243 }
1244
1245 NewFuncParamTys.push_back(ParamTy);
1246 }
1247
1248 FunctionType *NewFTy =
1249 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1250 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1251 FTy = NewFTy;
1252 }
1253
1254 FindType(FTy);
1255 } else {
1256 // As kernel functions do not have parameters, create new function type and
1257 // add it to type map.
1258 SmallVector<Type *, 4> NewFuncParamTys;
1259 FunctionType *NewFTy =
1260 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1261 FindType(NewFTy);
1262 }
1263
1264 // Investigate instructions' type in function body.
1265 for (BasicBlock &BB : F) {
1266 for (Instruction &I : BB) {
1267 if (isa<ShuffleVectorInst>(I)) {
1268 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1269 // Ignore type for mask of shuffle vector instruction.
1270 if (i == 2) {
1271 continue;
1272 }
1273
1274 Value *Op = I.getOperand(i);
1275 if (!isa<MetadataAsValue>(Op)) {
1276 FindType(Op->getType());
1277 }
1278 }
1279
1280 FindType(I.getType());
1281 continue;
1282 }
1283
David Neto862b7d82018-06-14 18:48:37 -04001284 CallInst *Call = dyn_cast<CallInst>(&I);
1285
1286 if (Call && Call->getCalledFunction()->getName().startswith(
1287 "clspv.resource.var.")) {
1288 // This is a fake call representing access to a resource variable.
1289 // We handle that elsewhere.
1290 continue;
1291 }
1292
David Neto22f144c2017-06-12 14:26:21 -04001293 // Work through the operands of the instruction.
1294 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1295 Value *const Op = I.getOperand(i);
1296 // If any of the operands is a constant, find the type!
1297 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1298 FindType(Op->getType());
1299 }
1300 }
1301
1302 for (Use &Op : I.operands()) {
1303 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1304 // Avoid to check call instruction's type.
1305 break;
1306 }
1307 if (!isa<MetadataAsValue>(&Op)) {
1308 FindType(Op->getType());
1309 continue;
1310 }
1311 }
1312
David Neto22f144c2017-06-12 14:26:21 -04001313 // We don't want to track the type of this call as we are going to replace
1314 // it.
David Neto862b7d82018-06-14 18:48:37 -04001315 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001316 Call->getCalledFunction()->getName())) {
1317 continue;
1318 }
1319
1320 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1321 // If gep's base operand has ModuleScopePrivate address space, make gep
1322 // return ModuleScopePrivate address space.
1323 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1324 // Add pointer type with private address space for global constant to
1325 // type list.
1326 Type *EleTy = I.getType()->getPointerElementType();
1327 Type *NewPTy =
1328 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1329
1330 FindType(NewPTy);
1331 continue;
1332 }
1333 }
1334
1335 FindType(I.getType());
1336 }
1337 }
1338}
1339
David Neto862b7d82018-06-14 18:48:37 -04001340void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1341 // If we are using a sampler map, find the type of the sampler.
1342 if (M.getFunction("clspv.sampler.var.literal") ||
1343 0 < getSamplerMap().size()) {
1344 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1345 if (!SamplerStructTy) {
1346 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1347 }
1348
1349 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1350
1351 FindType(SamplerTy);
1352 }
1353}
1354
1355void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1356 // Record types so they are generated.
1357 TypesNeedingLayout.reset();
1358 StructTypesNeedingBlock.reset();
1359
1360 // To match older clspv codegen, generate the float type first if required
1361 // for images.
1362 for (const auto *info : ModuleOrderedResourceVars) {
1363 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1364 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1365 // We need "float" for the sampled component type.
1366 FindType(Type::getFloatTy(M.getContext()));
1367 // We only need to find it once.
1368 break;
1369 }
1370 }
1371
1372 for (const auto *info : ModuleOrderedResourceVars) {
1373 Type *type = info->var_fn->getReturnType();
1374
1375 switch (info->arg_kind) {
1376 case clspv::ArgKind::Buffer:
1377 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1378 StructTypesNeedingBlock.insert(sty);
1379 } else {
1380 errs() << *type << "\n";
1381 llvm_unreachable("Buffer arguments must map to structures!");
1382 }
1383 break;
1384 case clspv::ArgKind::Pod:
1385 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1386 StructTypesNeedingBlock.insert(sty);
1387 } else {
1388 errs() << *type << "\n";
1389 llvm_unreachable("POD arguments must map to structures!");
1390 }
1391 break;
1392 case clspv::ArgKind::ReadOnlyImage:
1393 case clspv::ArgKind::WriteOnlyImage:
1394 case clspv::ArgKind::Sampler:
1395 // Sampler and image types map to the pointee type but
1396 // in the uniform constant address space.
1397 type = PointerType::get(type->getPointerElementType(),
1398 clspv::AddressSpace::UniformConstant);
1399 break;
1400 default:
1401 break;
1402 }
1403
1404 // The converted type is the type of the OpVariable we will generate.
1405 // If the pointee type is an array of size zero, FindType will convert it
1406 // to a runtime array.
1407 FindType(type);
1408 }
1409
1410 // Traverse the arrays and structures underneath each Block, and
1411 // mark them as needing layout.
1412 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1413 StructTypesNeedingBlock.end());
1414 while (!work_list.empty()) {
1415 Type *type = work_list.back();
1416 work_list.pop_back();
1417 TypesNeedingLayout.insert(type);
1418 switch (type->getTypeID()) {
1419 case Type::ArrayTyID:
1420 work_list.push_back(type->getArrayElementType());
1421 if (!Hack_generate_runtime_array_stride_early) {
1422 // Remember this array type for deferred decoration.
1423 TypesNeedingArrayStride.insert(type);
1424 }
1425 break;
1426 case Type::StructTyID:
1427 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1428 work_list.push_back(elem_ty);
1429 }
1430 default:
1431 // This type and its contained types don't get layout.
1432 break;
1433 }
1434 }
1435}
1436
David Neto22f144c2017-06-12 14:26:21 -04001437void SPIRVProducerPass::FindType(Type *Ty) {
1438 TypeList &TyList = getTypeList();
1439
1440 if (0 != TyList.idFor(Ty)) {
1441 return;
1442 }
1443
1444 if (Ty->isPointerTy()) {
1445 auto AddrSpace = Ty->getPointerAddressSpace();
1446 if ((AddressSpace::Constant == AddrSpace) ||
1447 (AddressSpace::Global == AddrSpace)) {
1448 auto PointeeTy = Ty->getPointerElementType();
1449
1450 if (PointeeTy->isStructTy() &&
1451 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1452 FindType(PointeeTy);
1453 auto ActualPointerTy =
1454 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1455 FindType(ActualPointerTy);
1456 return;
1457 }
1458 }
1459 }
1460
David Neto862b7d82018-06-14 18:48:37 -04001461 // By convention, LLVM array type with 0 elements will map to
1462 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1463 // has a constant number of elements. We need to support type of the
1464 // constant.
1465 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1466 if (arrayTy->getNumElements() > 0) {
1467 LLVMContext &Context = Ty->getContext();
1468 FindType(Type::getInt32Ty(Context));
1469 }
David Neto22f144c2017-06-12 14:26:21 -04001470 }
1471
1472 for (Type *SubTy : Ty->subtypes()) {
1473 FindType(SubTy);
1474 }
1475
1476 TyList.insert(Ty);
1477}
1478
1479void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1480 // If the global variable has a (non undef) initializer.
1481 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001482 // Generate the constant if it's not the initializer to a module scope
1483 // constant that we will expect in a storage buffer.
1484 const bool module_scope_constant_external_init =
1485 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1486 clspv::Option::ModuleConstantsInStorageBuffer();
1487 if (!module_scope_constant_external_init) {
1488 FindConstant(GV.getInitializer());
1489 }
David Neto22f144c2017-06-12 14:26:21 -04001490 }
1491}
1492
1493void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1494 // Investigate constants in function body.
1495 for (BasicBlock &BB : F) {
1496 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001497 if (auto *call = dyn_cast<CallInst>(&I)) {
1498 auto name = call->getCalledFunction()->getName();
1499 if (name == "clspv.sampler.var.literal") {
1500 // We've handled these constants elsewhere, so skip it.
1501 continue;
1502 }
1503 if (name.startswith("clspv.resource.var.")) {
1504 continue;
1505 }
David Neto22f144c2017-06-12 14:26:21 -04001506 }
1507
1508 if (isa<AllocaInst>(I)) {
1509 // Alloca instruction has constant for the number of element. Ignore it.
1510 continue;
1511 } else if (isa<ShuffleVectorInst>(I)) {
1512 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1513 // Ignore constant for mask of shuffle vector instruction.
1514 if (i == 2) {
1515 continue;
1516 }
1517
1518 if (isa<Constant>(I.getOperand(i)) &&
1519 !isa<GlobalValue>(I.getOperand(i))) {
1520 FindConstant(I.getOperand(i));
1521 }
1522 }
1523
1524 continue;
1525 } else if (isa<InsertElementInst>(I)) {
1526 // Handle InsertElement with <4 x i8> specially.
1527 Type *CompositeTy = I.getOperand(0)->getType();
1528 if (is4xi8vec(CompositeTy)) {
1529 LLVMContext &Context = CompositeTy->getContext();
1530 if (isa<Constant>(I.getOperand(0))) {
1531 FindConstant(I.getOperand(0));
1532 }
1533
1534 if (isa<Constant>(I.getOperand(1))) {
1535 FindConstant(I.getOperand(1));
1536 }
1537
1538 // Add mask constant 0xFF.
1539 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1540 FindConstant(CstFF);
1541
1542 // Add shift amount constant.
1543 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1544 uint64_t Idx = CI->getZExtValue();
1545 Constant *CstShiftAmount =
1546 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1547 FindConstant(CstShiftAmount);
1548 }
1549
1550 continue;
1551 }
1552
1553 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1554 // Ignore constant for index of InsertElement instruction.
1555 if (i == 2) {
1556 continue;
1557 }
1558
1559 if (isa<Constant>(I.getOperand(i)) &&
1560 !isa<GlobalValue>(I.getOperand(i))) {
1561 FindConstant(I.getOperand(i));
1562 }
1563 }
1564
1565 continue;
1566 } else if (isa<ExtractElementInst>(I)) {
1567 // Handle ExtractElement with <4 x i8> specially.
1568 Type *CompositeTy = I.getOperand(0)->getType();
1569 if (is4xi8vec(CompositeTy)) {
1570 LLVMContext &Context = CompositeTy->getContext();
1571 if (isa<Constant>(I.getOperand(0))) {
1572 FindConstant(I.getOperand(0));
1573 }
1574
1575 // Add mask constant 0xFF.
1576 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1577 FindConstant(CstFF);
1578
1579 // Add shift amount constant.
1580 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1581 uint64_t Idx = CI->getZExtValue();
1582 Constant *CstShiftAmount =
1583 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1584 FindConstant(CstShiftAmount);
1585 } else {
1586 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1587 FindConstant(Cst8);
1588 }
1589
1590 continue;
1591 }
1592
1593 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1594 // Ignore constant for index of ExtractElement instruction.
1595 if (i == 1) {
1596 continue;
1597 }
1598
1599 if (isa<Constant>(I.getOperand(i)) &&
1600 !isa<GlobalValue>(I.getOperand(i))) {
1601 FindConstant(I.getOperand(i));
1602 }
1603 }
1604
1605 continue;
1606 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1607 // 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
1608 bool foundConstantTrue = false;
1609 for (Use &Op : I.operands()) {
1610 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1611 auto CI = cast<ConstantInt>(Op);
1612
1613 if (CI->isZero() || foundConstantTrue) {
1614 // 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.
1615 FindConstant(Op);
1616 } else {
1617 foundConstantTrue = true;
1618 }
1619 }
1620 }
1621
1622 continue;
David Netod2de94a2017-08-28 17:27:47 -04001623 } else if (isa<TruncInst>(I)) {
1624 // For truncation to i8 we mask against 255.
1625 Type *ToTy = I.getType();
1626 if (8u == ToTy->getPrimitiveSizeInBits()) {
1627 LLVMContext &Context = ToTy->getContext();
1628 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1629 FindConstant(Cst255);
1630 }
1631 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001632 } else if (isa<AtomicRMWInst>(I)) {
1633 LLVMContext &Context = I.getContext();
1634
1635 FindConstant(
1636 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1637 FindConstant(ConstantInt::get(
1638 Type::getInt32Ty(Context),
1639 spv::MemorySemanticsUniformMemoryMask |
1640 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001641 }
1642
1643 for (Use &Op : I.operands()) {
1644 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1645 FindConstant(Op);
1646 }
1647 }
1648 }
1649 }
1650}
1651
1652void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001653 ValueList &CstList = getConstantList();
1654
David Netofb9a7972017-08-25 17:08:24 -04001655 // If V is already tracked, ignore it.
1656 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001657 return;
1658 }
1659
David Neto862b7d82018-06-14 18:48:37 -04001660 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1661 return;
1662 }
1663
David Neto22f144c2017-06-12 14:26:21 -04001664 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001665 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001666
1667 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001668 if (is4xi8vec(CstTy)) {
1669 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001670 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001671 }
1672 }
1673
1674 if (Cst->getNumOperands()) {
1675 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1676 ++I) {
1677 FindConstant(*I);
1678 }
1679
David Netofb9a7972017-08-25 17:08:24 -04001680 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001681 return;
1682 } else if (const ConstantDataSequential *CDS =
1683 dyn_cast<ConstantDataSequential>(Cst)) {
1684 // Add constants for each element to constant list.
1685 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1686 Constant *EleCst = CDS->getElementAsConstant(i);
1687 FindConstant(EleCst);
1688 }
1689 }
1690
1691 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001692 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001693 }
1694}
1695
1696spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1697 switch (AddrSpace) {
1698 default:
1699 llvm_unreachable("Unsupported OpenCL address space");
1700 case AddressSpace::Private:
1701 return spv::StorageClassFunction;
1702 case AddressSpace::Global:
1703 case AddressSpace::Constant:
1704 return spv::StorageClassStorageBuffer;
1705 case AddressSpace::Input:
1706 return spv::StorageClassInput;
1707 case AddressSpace::Local:
1708 return spv::StorageClassWorkgroup;
1709 case AddressSpace::UniformConstant:
1710 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001711 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001712 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001713 case AddressSpace::ModuleScopePrivate:
1714 return spv::StorageClassPrivate;
1715 }
1716}
1717
David Neto862b7d82018-06-14 18:48:37 -04001718spv::StorageClass
1719SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1720 switch (arg_kind) {
1721 case clspv::ArgKind::Buffer:
1722 return spv::StorageClassStorageBuffer;
1723 case clspv::ArgKind::Pod:
1724 return clspv::Option::PodArgsInUniformBuffer()
1725 ? spv::StorageClassUniform
1726 : spv::StorageClassStorageBuffer;
1727 case clspv::ArgKind::Local:
1728 return spv::StorageClassWorkgroup;
1729 case clspv::ArgKind::ReadOnlyImage:
1730 case clspv::ArgKind::WriteOnlyImage:
1731 case clspv::ArgKind::Sampler:
1732 return spv::StorageClassUniformConstant;
1733 }
1734}
1735
David Neto22f144c2017-06-12 14:26:21 -04001736spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1737 return StringSwitch<spv::BuiltIn>(Name)
1738 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1739 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1740 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1741 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1742 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1743 .Default(spv::BuiltInMax);
1744}
1745
1746void SPIRVProducerPass::GenerateExtInstImport() {
1747 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1748 uint32_t &ExtInstImportID = getOpExtInstImportID();
1749
1750 //
1751 // Generate OpExtInstImport.
1752 //
1753 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001754 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001755 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1756 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001757}
1758
David Netoc6f3ab22018-04-06 18:02:31 -04001759void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001760 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1761 ValueMapType &VMap = getValueMap();
1762 ValueMapType &AllocatedVMap = getAllocatedValueMap();
David Neto22f144c2017-06-12 14:26:21 -04001763
1764 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1765 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1766 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1767
1768 for (Type *Ty : getTypeList()) {
1769 // Update TypeMap with nextID for reference later.
1770 TypeMap[Ty] = nextID;
1771
1772 switch (Ty->getTypeID()) {
1773 default: {
1774 Ty->print(errs());
1775 llvm_unreachable("Unsupported type???");
1776 break;
1777 }
1778 case Type::MetadataTyID:
1779 case Type::LabelTyID: {
1780 // Ignore these types.
1781 break;
1782 }
1783 case Type::PointerTyID: {
1784 PointerType *PTy = cast<PointerType>(Ty);
1785 unsigned AddrSpace = PTy->getAddressSpace();
1786
1787 // For the purposes of our Vulkan SPIR-V type system, constant and global
1788 // are conflated.
1789 bool UseExistingOpTypePointer = false;
1790 if (AddressSpace::Constant == AddrSpace) {
1791 AddrSpace = AddressSpace::Global;
1792
1793 // Check to see if we already created this type (for instance, if we had
1794 // a constant <type>* and a global <type>*, the type would be created by
1795 // one of these types, and shared by both).
1796 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1797 if (0 < TypeMap.count(GlobalTy)) {
1798 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001799 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001800 break;
1801 }
1802 } else if (AddressSpace::Global == AddrSpace) {
1803 AddrSpace = AddressSpace::Constant;
1804
1805 // Check to see if we already created this type (for instance, if we had
1806 // a constant <type>* and a global <type>*, the type would be created by
1807 // one of these types, and shared by both).
1808 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1809 if (0 < TypeMap.count(ConstantTy)) {
1810 TypeMap[PTy] = TypeMap[ConstantTy];
1811 UseExistingOpTypePointer = true;
1812 }
1813 }
1814
David Neto862b7d82018-06-14 18:48:37 -04001815 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001816
David Neto862b7d82018-06-14 18:48:37 -04001817 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001818 //
1819 // Generate OpTypePointer.
1820 //
1821
1822 // OpTypePointer
1823 // Ops[0] = Storage Class
1824 // Ops[1] = Element Type ID
1825 SPIRVOperandList Ops;
1826
David Neto257c3892018-04-11 13:19:45 -04001827 Ops << MkNum(GetStorageClass(AddrSpace))
1828 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001829
David Neto87846742018-04-11 17:36:22 -04001830 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001831 SPIRVInstList.push_back(Inst);
1832 }
David Neto22f144c2017-06-12 14:26:21 -04001833 break;
1834 }
1835 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001836 StructType *STy = cast<StructType>(Ty);
1837
1838 // Handle sampler type.
1839 if (STy->isOpaque()) {
1840 if (STy->getName().equals("opencl.sampler_t")) {
1841 //
1842 // Generate OpTypeSampler
1843 //
1844 // Empty Ops.
1845 SPIRVOperandList Ops;
1846
David Neto87846742018-04-11 17:36:22 -04001847 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001848 SPIRVInstList.push_back(Inst);
1849 break;
1850 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1851 STy->getName().equals("opencl.image2d_wo_t") ||
1852 STy->getName().equals("opencl.image3d_ro_t") ||
1853 STy->getName().equals("opencl.image3d_wo_t")) {
1854 //
1855 // Generate OpTypeImage
1856 //
1857 // Ops[0] = Sampled Type ID
1858 // Ops[1] = Dim ID
1859 // Ops[2] = Depth (Literal Number)
1860 // Ops[3] = Arrayed (Literal Number)
1861 // Ops[4] = MS (Literal Number)
1862 // Ops[5] = Sampled (Literal Number)
1863 // Ops[6] = Image Format ID
1864 //
1865 SPIRVOperandList Ops;
1866
1867 // TODO: Changed Sampled Type according to situations.
1868 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001869 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001870
1871 spv::Dim DimID = spv::Dim2D;
1872 if (STy->getName().equals("opencl.image3d_ro_t") ||
1873 STy->getName().equals("opencl.image3d_wo_t")) {
1874 DimID = spv::Dim3D;
1875 }
David Neto257c3892018-04-11 13:19:45 -04001876 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001877
1878 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001879 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001880
1881 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001882 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001883
1884 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001885 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001886
1887 // TODO: Set up Sampled.
1888 //
1889 // From Spec
1890 //
1891 // 0 indicates this is only known at run time, not at compile time
1892 // 1 indicates will be used with sampler
1893 // 2 indicates will be used without a sampler (a storage image)
1894 uint32_t Sampled = 1;
1895 if (STy->getName().equals("opencl.image2d_wo_t") ||
1896 STy->getName().equals("opencl.image3d_wo_t")) {
1897 Sampled = 2;
1898 }
David Neto257c3892018-04-11 13:19:45 -04001899 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001900
1901 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001902 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001903
David Neto87846742018-04-11 17:36:22 -04001904 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001905 SPIRVInstList.push_back(Inst);
1906 break;
1907 }
1908 }
1909
1910 //
1911 // Generate OpTypeStruct
1912 //
1913 // Ops[0] ... Ops[n] = Member IDs
1914 SPIRVOperandList Ops;
1915
1916 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001917 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001918 }
1919
David Neto22f144c2017-06-12 14:26:21 -04001920 uint32_t STyID = nextID;
1921
David Neto87846742018-04-11 17:36:22 -04001922 auto *Inst =
1923 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001924 SPIRVInstList.push_back(Inst);
1925
1926 // Generate OpMemberDecorate.
1927 auto DecoInsertPoint =
1928 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1929 [](SPIRVInstruction *Inst) -> bool {
1930 return Inst->getOpcode() != spv::OpDecorate &&
1931 Inst->getOpcode() != spv::OpMemberDecorate &&
1932 Inst->getOpcode() != spv::OpExtInstImport;
1933 });
1934
David Netoc463b372017-08-10 15:32:21 -04001935 const auto StructLayout = DL.getStructLayout(STy);
1936
David Neto862b7d82018-06-14 18:48:37 -04001937 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001938 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1939 MemberIdx++) {
1940 // Ops[0] = Structure Type ID
1941 // Ops[1] = Member Index(Literal Number)
1942 // Ops[2] = Decoration (Offset)
1943 // Ops[3] = Byte Offset (Literal Number)
1944 Ops.clear();
1945
David Neto257c3892018-04-11 13:19:45 -04001946 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001947
David Netoc463b372017-08-10 15:32:21 -04001948 const auto ByteOffset =
1949 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001950 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001951
David Neto87846742018-04-11 17:36:22 -04001952 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001953 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001954 }
1955
1956 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001957 if (StructTypesNeedingBlock.idFor(STy)) {
1958 Ops.clear();
1959 // Use Block decorations with StorageBuffer storage class.
1960 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001961
David Neto862b7d82018-06-14 18:48:37 -04001962 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
1963 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001964 }
1965 break;
1966 }
1967 case Type::IntegerTyID: {
1968 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1969
1970 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04001971 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04001972 SPIRVInstList.push_back(Inst);
1973 } else {
1974 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001975 // No matter what LLVM type is requested first, always alias the
1976 // second one's SPIR-V type to be the same as the one we generated
1977 // first.
Neil Henning39672102017-09-29 14:33:13 +01001978 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001979 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001980 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001981 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001982 } else if (BitWidth == 32) {
1983 aliasToWidth = 8;
1984 }
1985 if (aliasToWidth) {
1986 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1987 auto where = TypeMap.find(otherType);
1988 if (where == TypeMap.end()) {
1989 // Go ahead and make it, but also map the other type to it.
1990 TypeMap[otherType] = nextID;
1991 } else {
1992 // Alias this SPIR-V type the existing type.
1993 TypeMap[Ty] = where->second;
1994 break;
1995 }
David Neto22f144c2017-06-12 14:26:21 -04001996 }
1997
David Neto257c3892018-04-11 13:19:45 -04001998 SPIRVOperandList Ops;
1999 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002000
2001 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002002 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002003 }
2004 break;
2005 }
2006 case Type::HalfTyID:
2007 case Type::FloatTyID:
2008 case Type::DoubleTyID: {
2009 SPIRVOperand *WidthOp = new SPIRVOperand(
2010 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2011
2012 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002013 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002014 break;
2015 }
2016 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002017 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002018 const uint64_t Length = ArrTy->getArrayNumElements();
2019 if (Length == 0) {
2020 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002021
David Neto862b7d82018-06-14 18:48:37 -04002022 // Only generate the type once.
2023 // TODO(dneto): Can it ever be generated more than once?
2024 // Doesn't LLVM type uniqueness guarantee we'll only see this
2025 // once?
2026 Type *EleTy = ArrTy->getArrayElementType();
2027 if (OpRuntimeTyMap.count(EleTy) == 0) {
2028 uint32_t OpTypeRuntimeArrayID = nextID;
2029 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002030
David Neto862b7d82018-06-14 18:48:37 -04002031 //
2032 // Generate OpTypeRuntimeArray.
2033 //
David Neto22f144c2017-06-12 14:26:21 -04002034
David Neto862b7d82018-06-14 18:48:37 -04002035 // OpTypeRuntimeArray
2036 // Ops[0] = Element Type ID
2037 SPIRVOperandList Ops;
2038 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002039
David Neto862b7d82018-06-14 18:48:37 -04002040 SPIRVInstList.push_back(
2041 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002042
David Neto862b7d82018-06-14 18:48:37 -04002043 if (Hack_generate_runtime_array_stride_early) {
2044 // Generate OpDecorate.
2045 auto DecoInsertPoint = std::find_if(
2046 SPIRVInstList.begin(), SPIRVInstList.end(),
2047 [](SPIRVInstruction *Inst) -> bool {
2048 return Inst->getOpcode() != spv::OpDecorate &&
2049 Inst->getOpcode() != spv::OpMemberDecorate &&
2050 Inst->getOpcode() != spv::OpExtInstImport;
2051 });
David Neto22f144c2017-06-12 14:26:21 -04002052
David Neto862b7d82018-06-14 18:48:37 -04002053 // Ops[0] = Target ID
2054 // Ops[1] = Decoration (ArrayStride)
2055 // Ops[2] = Stride Number(Literal Number)
2056 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002057
David Neto862b7d82018-06-14 18:48:37 -04002058 Ops << MkId(OpTypeRuntimeArrayID)
2059 << MkNum(spv::DecorationArrayStride)
2060 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04002061
David Neto862b7d82018-06-14 18:48:37 -04002062 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2063 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2064 }
2065 }
David Neto22f144c2017-06-12 14:26:21 -04002066
David Neto862b7d82018-06-14 18:48:37 -04002067 } else {
David Neto22f144c2017-06-12 14:26:21 -04002068
David Neto862b7d82018-06-14 18:48:37 -04002069 //
2070 // Generate OpConstant and OpTypeArray.
2071 //
2072
2073 //
2074 // Generate OpConstant for array length.
2075 //
2076 // Ops[0] = Result Type ID
2077 // Ops[1] .. Ops[n] = Values LiteralNumber
2078 SPIRVOperandList Ops;
2079
2080 Type *LengthTy = Type::getInt32Ty(Context);
2081 uint32_t ResTyID = lookupType(LengthTy);
2082 Ops << MkId(ResTyID);
2083
2084 assert(Length < UINT32_MAX);
2085 Ops << MkNum(static_cast<uint32_t>(Length));
2086
2087 // Add constant for length to constant list.
2088 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2089 AllocatedVMap[CstLength] = nextID;
2090 VMap[CstLength] = nextID;
2091 uint32_t LengthID = nextID;
2092
2093 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2094 SPIRVInstList.push_back(CstInst);
2095
2096 // Remember to generate ArrayStride later
2097 getTypesNeedingArrayStride().insert(Ty);
2098
2099 //
2100 // Generate OpTypeArray.
2101 //
2102 // Ops[0] = Element Type ID
2103 // Ops[1] = Array Length Constant ID
2104 Ops.clear();
2105
2106 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2107 Ops << MkId(EleTyID) << MkId(LengthID);
2108
2109 // Update TypeMap with nextID.
2110 TypeMap[Ty] = nextID;
2111
2112 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2113 SPIRVInstList.push_back(ArrayInst);
2114 }
David Neto22f144c2017-06-12 14:26:21 -04002115 break;
2116 }
2117 case Type::VectorTyID: {
2118 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002119 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2120 if (Ty->getVectorNumElements() == 4) {
2121 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2122 break;
2123 } else {
2124 Ty->print(errs());
2125 llvm_unreachable("Support above i8 vector type");
2126 }
2127 }
2128
2129 // Ops[0] = Component Type ID
2130 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002131 SPIRVOperandList Ops;
2132 Ops << MkId(lookupType(Ty->getVectorElementType()))
2133 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002134
David Neto87846742018-04-11 17:36:22 -04002135 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002136 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002137 break;
2138 }
2139 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002140 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002141 SPIRVInstList.push_back(Inst);
2142 break;
2143 }
2144 case Type::FunctionTyID: {
2145 // Generate SPIRV instruction for function type.
2146 FunctionType *FTy = cast<FunctionType>(Ty);
2147
2148 // Ops[0] = Return Type ID
2149 // Ops[1] ... Ops[n] = Parameter Type IDs
2150 SPIRVOperandList Ops;
2151
2152 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002153 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002154
2155 // Find SPIRV instructions for parameter types
2156 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2157 // Find SPIRV instruction for parameter type.
2158 auto ParamTy = FTy->getParamType(k);
2159 if (ParamTy->isPointerTy()) {
2160 auto PointeeTy = ParamTy->getPointerElementType();
2161 if (PointeeTy->isStructTy() &&
2162 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2163 ParamTy = PointeeTy;
2164 }
2165 }
2166
David Netoc6f3ab22018-04-06 18:02:31 -04002167 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002168 }
2169
David Neto87846742018-04-11 17:36:22 -04002170 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002171 SPIRVInstList.push_back(Inst);
2172 break;
2173 }
2174 }
2175 }
2176
2177 // Generate OpTypeSampledImage.
2178 TypeMapType &OpImageTypeMap = getImageTypeMap();
2179 for (auto &ImageType : OpImageTypeMap) {
2180 //
2181 // Generate OpTypeSampledImage.
2182 //
2183 // Ops[0] = Image Type ID
2184 //
2185 SPIRVOperandList Ops;
2186
2187 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002188 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002189
2190 // Update OpImageTypeMap.
2191 ImageType.second = nextID;
2192
David Neto87846742018-04-11 17:36:22 -04002193 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002194 SPIRVInstList.push_back(Inst);
2195 }
David Netoc6f3ab22018-04-06 18:02:31 -04002196
2197 // Generate types for pointer-to-local arguments.
2198 for (auto* arg : LocalArgs) {
2199
2200 LocalArgInfo& arg_info = LocalArgMap[arg];
2201
2202 // Generate the spec constant.
2203 SPIRVOperandList Ops;
2204 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002205 SPIRVInstList.push_back(
2206 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002207
2208 // Generate the array type.
2209 Ops.clear();
2210 // The element type must have been created.
2211 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2212 assert(elem_ty_id);
2213 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2214
2215 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002216 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002217
2218 Ops.clear();
2219 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002220 SPIRVInstList.push_back(new SPIRVInstruction(
2221 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002222 }
David Neto22f144c2017-06-12 14:26:21 -04002223}
2224
2225void SPIRVProducerPass::GenerateSPIRVConstants() {
2226 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2227 ValueMapType &VMap = getValueMap();
2228 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2229 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002230 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002231
2232 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002233 // UniqueVector ids are 1-based.
2234 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002235
2236 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002237 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002238 continue;
2239 }
2240
David Netofb9a7972017-08-25 17:08:24 -04002241 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002242 VMap[Cst] = nextID;
2243
2244 //
2245 // Generate OpConstant.
2246 //
2247
2248 // Ops[0] = Result Type ID
2249 // Ops[1] .. Ops[n] = Values LiteralNumber
2250 SPIRVOperandList Ops;
2251
David Neto257c3892018-04-11 13:19:45 -04002252 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002253
2254 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002255 spv::Op Opcode = spv::OpNop;
2256
2257 if (isa<UndefValue>(Cst)) {
2258 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002259 Opcode = spv::OpUndef;
2260 if (hack_undef) {
2261 Type *type = Cst->getType();
2262 if (type->isFPOrFPVectorTy() || type->isIntOrIntVectorTy()) {
2263 Opcode = spv::OpConstantNull;
2264 }
2265 }
David Neto22f144c2017-06-12 14:26:21 -04002266 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2267 unsigned BitWidth = CI->getBitWidth();
2268 if (BitWidth == 1) {
2269 // If the bitwidth of constant is 1, generate OpConstantTrue or
2270 // OpConstantFalse.
2271 if (CI->getZExtValue()) {
2272 // Ops[0] = Result Type ID
2273 Opcode = spv::OpConstantTrue;
2274 } else {
2275 // Ops[0] = Result Type ID
2276 Opcode = spv::OpConstantFalse;
2277 }
David Neto22f144c2017-06-12 14:26:21 -04002278 } else {
2279 auto V = CI->getZExtValue();
2280 LiteralNum.push_back(V & 0xFFFFFFFF);
2281
2282 if (BitWidth > 32) {
2283 LiteralNum.push_back(V >> 32);
2284 }
2285
2286 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002287
David Neto257c3892018-04-11 13:19:45 -04002288 Ops << MkInteger(LiteralNum);
2289
2290 if (BitWidth == 32 && V == 0) {
2291 constant_i32_zero_id_ = nextID;
2292 }
David Neto22f144c2017-06-12 14:26:21 -04002293 }
2294 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2295 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2296 Type *CFPTy = CFP->getType();
2297 if (CFPTy->isFloatTy()) {
2298 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2299 } else {
2300 CFPTy->print(errs());
2301 llvm_unreachable("Implement this ConstantFP Type");
2302 }
2303
2304 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002305
David Neto257c3892018-04-11 13:19:45 -04002306 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002307 } else if (isa<ConstantDataSequential>(Cst) &&
2308 cast<ConstantDataSequential>(Cst)->isString()) {
2309 Cst->print(errs());
2310 llvm_unreachable("Implement this Constant");
2311
2312 } else if (const ConstantDataSequential *CDS =
2313 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002314 // Let's convert <4 x i8> constant to int constant specially.
2315 // This case occurs when all the values are specified as constant
2316 // ints.
2317 Type *CstTy = Cst->getType();
2318 if (is4xi8vec(CstTy)) {
2319 LLVMContext &Context = CstTy->getContext();
2320
2321 //
2322 // Generate OpConstant with OpTypeInt 32 0.
2323 //
Neil Henning39672102017-09-29 14:33:13 +01002324 uint32_t IntValue = 0;
2325 for (unsigned k = 0; k < 4; k++) {
2326 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002327 IntValue = (IntValue << 8) | (Val & 0xffu);
2328 }
2329
2330 Type *i32 = Type::getInt32Ty(Context);
2331 Constant *CstInt = ConstantInt::get(i32, IntValue);
2332 // If this constant is already registered on VMap, use it.
2333 if (VMap.count(CstInt)) {
2334 uint32_t CstID = VMap[CstInt];
2335 VMap[Cst] = CstID;
2336 continue;
2337 }
2338
David Neto257c3892018-04-11 13:19:45 -04002339 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002340
David Neto87846742018-04-11 17:36:22 -04002341 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002342 SPIRVInstList.push_back(CstInst);
2343
2344 continue;
2345 }
2346
2347 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002348 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2349 Constant *EleCst = CDS->getElementAsConstant(k);
2350 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002351 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002352 }
2353
2354 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002355 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2356 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002357 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002358 Type *CstTy = Cst->getType();
2359 if (is4xi8vec(CstTy)) {
2360 LLVMContext &Context = CstTy->getContext();
2361
2362 //
2363 // Generate OpConstant with OpTypeInt 32 0.
2364 //
Neil Henning39672102017-09-29 14:33:13 +01002365 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002366 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2367 I != E; ++I) {
2368 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002369 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002370 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2371 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002372 }
David Neto49351ac2017-08-26 17:32:20 -04002373 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002374 }
2375
David Neto49351ac2017-08-26 17:32:20 -04002376 Type *i32 = Type::getInt32Ty(Context);
2377 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002378 // If this constant is already registered on VMap, use it.
2379 if (VMap.count(CstInt)) {
2380 uint32_t CstID = VMap[CstInt];
2381 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002382 continue;
David Neto22f144c2017-06-12 14:26:21 -04002383 }
2384
David Neto257c3892018-04-11 13:19:45 -04002385 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002386
David Neto87846742018-04-11 17:36:22 -04002387 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002388 SPIRVInstList.push_back(CstInst);
2389
David Neto19a1bad2017-08-25 15:01:41 -04002390 continue;
David Neto22f144c2017-06-12 14:26:21 -04002391 }
2392
2393 // We use a constant composite in SPIR-V for our constant aggregate in
2394 // LLVM.
2395 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002396
2397 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2398 // Look up the ID of the element of this aggregate (which we will
2399 // previously have created a constant for).
2400 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2401
2402 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002403 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002404 }
2405 } else if (Cst->isNullValue()) {
2406 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002407 } else {
2408 Cst->print(errs());
2409 llvm_unreachable("Unsupported Constant???");
2410 }
2411
David Neto87846742018-04-11 17:36:22 -04002412 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002413 SPIRVInstList.push_back(CstInst);
2414 }
2415}
2416
2417void SPIRVProducerPass::GenerateSamplers(Module &M) {
2418 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2419 ValueMapType &VMap = getValueMap();
2420
David Neto862b7d82018-06-14 18:48:37 -04002421 auto& sampler_map = getSamplerMap();
2422 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002423 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002424 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2425 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002426
David Neto862b7d82018-06-14 18:48:37 -04002427 // We might have samplers in the sampler map that are not used
2428 // in the translation unit. We need to allocate variables
2429 // for them and bindings too.
2430 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002431
David Neto862b7d82018-06-14 18:48:37 -04002432 auto* var_fn = M.getFunction("clspv.sampler.var.literal");
2433 if (!var_fn) return;
2434 for (auto user : var_fn->users()) {
2435 // Populate SamplerLiteralToDescriptorSetMap and
2436 // SamplerLiteralToBindingMap.
2437 //
2438 // Look for calls like
2439 // call %opencl.sampler_t addrspace(2)*
2440 // @clspv.sampler.var.literal(
2441 // i32 descriptor,
2442 // i32 binding,
2443 // i32 index-into-sampler-map)
2444 if (auto* call = dyn_cast<CallInst>(user)) {
2445 const auto index_into_sampler_map =
2446 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue();
2447 if (index_into_sampler_map >= sampler_map.size()) {
2448 errs() << "Out of bounds index to sampler map: " << index_into_sampler_map;
2449 llvm_unreachable("bad sampler init: out of bounds");
2450 }
2451
2452 auto sampler_value = sampler_map[index_into_sampler_map].first;
2453 const auto descriptor_set = static_cast<unsigned>(
2454 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2455 const auto binding = static_cast<unsigned>(
2456 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2457
2458 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2459 SamplerLiteralToBindingMap[sampler_value] = binding;
2460 used_bindings.insert(binding);
2461 }
2462 }
2463
2464 unsigned index = 0;
2465 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002466 // Generate OpVariable.
2467 //
2468 // GIDOps[0] : Result Type ID
2469 // GIDOps[1] : Storage Class
2470 SPIRVOperandList Ops;
2471
David Neto257c3892018-04-11 13:19:45 -04002472 Ops << MkId(lookupType(SamplerTy))
2473 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002474
David Neto862b7d82018-06-14 18:48:37 -04002475 auto sampler_var_id = nextID++;
2476 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002477 SPIRVInstList.push_back(Inst);
2478
David Neto862b7d82018-06-14 18:48:37 -04002479 SamplerMapIndexToIDMap[index] = sampler_var_id;
2480 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002481
2482 // Find Insert Point for OpDecorate.
2483 auto DecoInsertPoint =
2484 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2485 [](SPIRVInstruction *Inst) -> bool {
2486 return Inst->getOpcode() != spv::OpDecorate &&
2487 Inst->getOpcode() != spv::OpMemberDecorate &&
2488 Inst->getOpcode() != spv::OpExtInstImport;
2489 });
2490
2491 // Ops[0] = Target ID
2492 // Ops[1] = Decoration (DescriptorSet)
2493 // Ops[2] = LiteralNumber according to Decoration
2494 Ops.clear();
2495
David Neto862b7d82018-06-14 18:48:37 -04002496 unsigned descriptor_set;
2497 unsigned binding;
2498 if(SamplerLiteralToBindingMap.find(SamplerLiteral.first) == SamplerLiteralToBindingMap.end()) {
2499 // This sampler is not actually used. Find the next one.
2500 for (binding = 0; used_bindings.count(binding); binding++)
2501 ;
2502 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2503 used_bindings.insert(binding);
2504 } else {
2505 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2506 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2507 }
2508
2509 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2510 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002511
David Neto44795152017-07-13 15:45:28 -04002512 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002513 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002514 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002515
David Neto87846742018-04-11 17:36:22 -04002516 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002517 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2518
2519 // Ops[0] = Target ID
2520 // Ops[1] = Decoration (Binding)
2521 // Ops[2] = LiteralNumber according to Decoration
2522 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002523 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2524 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002525
David Neto87846742018-04-11 17:36:22 -04002526 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002527 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002528
2529 index++;
David Neto22f144c2017-06-12 14:26:21 -04002530 }
David Neto862b7d82018-06-14 18:48:37 -04002531}
David Neto22f144c2017-06-12 14:26:21 -04002532
David Neto862b7d82018-06-14 18:48:37 -04002533void SPIRVProducerPass::GenerateResourceVars(Module &M) {
2534 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2535 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002536
David Neto862b7d82018-06-14 18:48:37 -04002537 // Generate variables. Make one for each of resource var info object.
2538 for (auto *info : ModuleOrderedResourceVars) {
2539 Type *type = info->var_fn->getReturnType();
2540 // Remap the address space for opaque types.
2541 switch (info->arg_kind) {
2542 case clspv::ArgKind::Sampler:
2543 case clspv::ArgKind::ReadOnlyImage:
2544 case clspv::ArgKind::WriteOnlyImage:
2545 type = PointerType::get(type->getPointerElementType(),
2546 clspv::AddressSpace::UniformConstant);
2547 break;
2548 default:
2549 break;
2550 }
David Neto22f144c2017-06-12 14:26:21 -04002551
David Neto862b7d82018-06-14 18:48:37 -04002552 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002553
David Neto862b7d82018-06-14 18:48:37 -04002554 const auto type_id = lookupType(type);
2555 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2556 SPIRVOperandList Ops;
2557 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002558
David Neto862b7d82018-06-14 18:48:37 -04002559 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2560 SPIRVInstList.push_back(Inst);
2561
2562 // Map calls to the variable-builtin-function.
2563 for (auto &U : info->var_fn->uses()) {
2564 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2565 const auto set = unsigned(
2566 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2567 const auto binding = unsigned(
2568 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2569 if (set == info->descriptor_set && binding == info->binding) {
2570 switch (info->arg_kind) {
2571 case clspv::ArgKind::Buffer:
2572 case clspv::ArgKind::Pod:
2573 // The call maps to the variable directly.
2574 VMap[call] = info->var_id;
2575 break;
2576 case clspv::ArgKind::Sampler:
2577 case clspv::ArgKind::ReadOnlyImage:
2578 case clspv::ArgKind::WriteOnlyImage:
2579 // The call maps to a load we generate later.
2580 ResourceVarDeferredLoadCalls[call] = info->var_id;
2581 break;
2582 default:
2583 llvm_unreachable("Unhandled arg kind");
2584 }
2585 }
David Neto22f144c2017-06-12 14:26:21 -04002586 }
David Neto862b7d82018-06-14 18:48:37 -04002587 }
2588 }
David Neto22f144c2017-06-12 14:26:21 -04002589
David Neto862b7d82018-06-14 18:48:37 -04002590 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002591
David Neto862b7d82018-06-14 18:48:37 -04002592 // Find Insert Point for OpDecorate.
2593 auto DecoInsertPoint =
2594 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2595 [](SPIRVInstruction *Inst) -> bool {
2596 return Inst->getOpcode() != spv::OpDecorate &&
2597 Inst->getOpcode() != spv::OpMemberDecorate &&
2598 Inst->getOpcode() != spv::OpExtInstImport;
2599 });
2600
2601 SPIRVOperandList Ops;
2602 for (auto *info : ModuleOrderedResourceVars) {
2603 // Decorate with DescriptorSet and Binding.
2604 Ops.clear();
2605 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2606 << MkNum(info->descriptor_set);
2607 SPIRVInstList.insert(DecoInsertPoint,
2608 new SPIRVInstruction(spv::OpDecorate, Ops));
2609
2610 Ops.clear();
2611 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2612 << MkNum(info->binding);
2613 SPIRVInstList.insert(DecoInsertPoint,
2614 new SPIRVInstruction(spv::OpDecorate, Ops));
2615
2616 // Generate NonWritable and NonReadable
2617 switch (info->arg_kind) {
2618 case clspv::ArgKind::Buffer:
2619 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2620 clspv::AddressSpace::Constant) {
2621 Ops.clear();
2622 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2623 SPIRVInstList.insert(DecoInsertPoint,
2624 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002625 }
David Neto862b7d82018-06-14 18:48:37 -04002626 break;
2627 case clspv::ArgKind::ReadOnlyImage:
2628 Ops.clear();
2629 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2630 SPIRVInstList.insert(DecoInsertPoint,
2631 new SPIRVInstruction(spv::OpDecorate, Ops));
2632 break;
2633 case clspv::ArgKind::WriteOnlyImage:
2634 Ops.clear();
2635 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2636 SPIRVInstList.insert(DecoInsertPoint,
2637 new SPIRVInstruction(spv::OpDecorate, Ops));
2638 break;
2639 default:
2640 break;
David Neto22f144c2017-06-12 14:26:21 -04002641 }
2642 }
2643}
2644
2645void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto78383442018-06-15 20:31:56 -04002646 Module& M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002647 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2648 ValueMapType &VMap = getValueMap();
2649 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002650 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002651
2652 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2653 Type *Ty = GV.getType();
2654 PointerType *PTy = cast<PointerType>(Ty);
2655
2656 uint32_t InitializerID = 0;
2657
2658 // Workgroup size is handled differently (it goes into a constant)
2659 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2660 std::vector<bool> HasMDVec;
2661 uint32_t PrevXDimCst = 0xFFFFFFFF;
2662 uint32_t PrevYDimCst = 0xFFFFFFFF;
2663 uint32_t PrevZDimCst = 0xFFFFFFFF;
2664 for (Function &Func : *GV.getParent()) {
2665 if (Func.isDeclaration()) {
2666 continue;
2667 }
2668
2669 // We only need to check kernels.
2670 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2671 continue;
2672 }
2673
2674 if (const MDNode *MD =
2675 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2676 uint32_t CurXDimCst = static_cast<uint32_t>(
2677 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2678 uint32_t CurYDimCst = static_cast<uint32_t>(
2679 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2680 uint32_t CurZDimCst = static_cast<uint32_t>(
2681 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2682
2683 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2684 PrevZDimCst == 0xFFFFFFFF) {
2685 PrevXDimCst = CurXDimCst;
2686 PrevYDimCst = CurYDimCst;
2687 PrevZDimCst = CurZDimCst;
2688 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2689 CurZDimCst != PrevZDimCst) {
2690 llvm_unreachable(
2691 "reqd_work_group_size must be the same across all kernels");
2692 } else {
2693 continue;
2694 }
2695
2696 //
2697 // Generate OpConstantComposite.
2698 //
2699 // Ops[0] : Result Type ID
2700 // Ops[1] : Constant size for x dimension.
2701 // Ops[2] : Constant size for y dimension.
2702 // Ops[3] : Constant size for z dimension.
2703 SPIRVOperandList Ops;
2704
2705 uint32_t XDimCstID =
2706 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2707 uint32_t YDimCstID =
2708 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2709 uint32_t ZDimCstID =
2710 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2711
2712 InitializerID = nextID;
2713
David Neto257c3892018-04-11 13:19:45 -04002714 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2715 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002716
David Neto87846742018-04-11 17:36:22 -04002717 auto *Inst =
2718 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002719 SPIRVInstList.push_back(Inst);
2720
2721 HasMDVec.push_back(true);
2722 } else {
2723 HasMDVec.push_back(false);
2724 }
2725 }
2726
2727 // Check all kernels have same definitions for work_group_size.
2728 bool HasMD = false;
2729 if (!HasMDVec.empty()) {
2730 HasMD = HasMDVec[0];
2731 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2732 if (HasMD != HasMDVec[i]) {
2733 llvm_unreachable(
2734 "Kernels should have consistent work group size definition");
2735 }
2736 }
2737 }
2738
2739 // If all kernels do not have metadata for reqd_work_group_size, generate
2740 // OpSpecConstants for x/y/z dimension.
2741 if (!HasMD) {
2742 //
2743 // Generate OpSpecConstants for x/y/z dimension.
2744 //
2745 // Ops[0] : Result Type ID
2746 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2747 uint32_t XDimCstID = 0;
2748 uint32_t YDimCstID = 0;
2749 uint32_t ZDimCstID = 0;
2750
David Neto22f144c2017-06-12 14:26:21 -04002751 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002752 uint32_t result_type_id =
2753 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002754
David Neto257c3892018-04-11 13:19:45 -04002755 // X Dimension
2756 Ops << MkId(result_type_id) << MkNum(1);
2757 XDimCstID = nextID++;
2758 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002759 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002760
2761 // Y Dimension
2762 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002763 Ops << MkId(result_type_id) << MkNum(1);
2764 YDimCstID = nextID++;
2765 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002766 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002767
2768 // Z Dimension
2769 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002770 Ops << MkId(result_type_id) << MkNum(1);
2771 ZDimCstID = nextID++;
2772 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002773 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002774
David Neto22f144c2017-06-12 14:26:21 -04002775
David Neto257c3892018-04-11 13:19:45 -04002776 BuiltinDimVec.push_back(XDimCstID);
2777 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002778 BuiltinDimVec.push_back(ZDimCstID);
2779
David Neto22f144c2017-06-12 14:26:21 -04002780
2781 //
2782 // Generate OpSpecConstantComposite.
2783 //
2784 // Ops[0] : Result Type ID
2785 // Ops[1] : Constant size for x dimension.
2786 // Ops[2] : Constant size for y dimension.
2787 // Ops[3] : Constant size for z dimension.
2788 InitializerID = nextID;
2789
2790 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002791 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2792 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002793
David Neto87846742018-04-11 17:36:22 -04002794 auto *Inst =
2795 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002796 SPIRVInstList.push_back(Inst);
2797 }
2798 }
2799
David Neto22f144c2017-06-12 14:26:21 -04002800 VMap[&GV] = nextID;
2801
2802 //
2803 // Generate OpVariable.
2804 //
2805 // GIDOps[0] : Result Type ID
2806 // GIDOps[1] : Storage Class
2807 SPIRVOperandList Ops;
2808
David Neto85082642018-03-24 06:55:20 -07002809 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002810 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002811
David Neto85082642018-03-24 06:55:20 -07002812 if (GV.hasInitializer()) {
2813 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002814 }
2815
David Neto85082642018-03-24 06:55:20 -07002816 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002817 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002818 clspv::Option::ModuleConstantsInStorageBuffer();
2819
2820 if (0 != InitializerID) {
2821 if (!module_scope_constant_external_init) {
2822 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002823 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002824 }
2825 }
2826 const uint32_t var_id = nextID++;
2827
David Neto87846742018-04-11 17:36:22 -04002828 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002829 SPIRVInstList.push_back(Inst);
2830
2831 // If we have a builtin.
2832 if (spv::BuiltInMax != BuiltinType) {
2833 // Find Insert Point for OpDecorate.
2834 auto DecoInsertPoint =
2835 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2836 [](SPIRVInstruction *Inst) -> bool {
2837 return Inst->getOpcode() != spv::OpDecorate &&
2838 Inst->getOpcode() != spv::OpMemberDecorate &&
2839 Inst->getOpcode() != spv::OpExtInstImport;
2840 });
2841 //
2842 // Generate OpDecorate.
2843 //
2844 // DOps[0] = Target ID
2845 // DOps[1] = Decoration (Builtin)
2846 // DOps[2] = BuiltIn ID
2847 uint32_t ResultID;
2848
2849 // WorkgroupSize is different, we decorate the constant composite that has
2850 // its value, rather than the variable that we use to access the value.
2851 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2852 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002853 // Save both the value and variable IDs for later.
2854 WorkgroupSizeValueID = InitializerID;
2855 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002856 } else {
2857 ResultID = VMap[&GV];
2858 }
2859
2860 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002861 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2862 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002863
David Neto87846742018-04-11 17:36:22 -04002864 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002865 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002866 } else if (module_scope_constant_external_init) {
2867 // This module scope constant is initialized from a storage buffer with data
2868 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002869 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002870
David Neto862b7d82018-06-14 18:48:37 -04002871 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002872 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2873 // that later to other types, like uniform buffer.
2874 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2875 << ",binding,0,kind,buffer,hexbytes,";
2876 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2877 descriptorMapOut << "\n";
2878
2879 // Find Insert Point for OpDecorate.
2880 auto DecoInsertPoint =
2881 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2882 [](SPIRVInstruction *Inst) -> bool {
2883 return Inst->getOpcode() != spv::OpDecorate &&
2884 Inst->getOpcode() != spv::OpMemberDecorate &&
2885 Inst->getOpcode() != spv::OpExtInstImport;
2886 });
2887
David Neto257c3892018-04-11 13:19:45 -04002888 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002889 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002890 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2891 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002892 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002893
2894 // OpDecorate %var DescriptorSet <descriptor_set>
2895 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002896 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2897 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002898 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002899 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002900 }
2901}
2902
David Netoc6f3ab22018-04-06 18:02:31 -04002903void SPIRVProducerPass::GenerateWorkgroupVars() {
2904 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2905 for (auto* arg : LocalArgs) {
2906 const auto& info = LocalArgMap[arg];
2907
2908 // Generate OpVariable.
2909 //
2910 // GIDOps[0] : Result Type ID
2911 // GIDOps[1] : Storage Class
2912 SPIRVOperandList Ops;
2913 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2914
2915 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002916 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002917 }
2918}
2919
David Neto862b7d82018-06-14 18:48:37 -04002920void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2921 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002922 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2923 return;
2924 }
David Neto862b7d82018-06-14 18:48:37 -04002925 // Gather the list of resources that are used by this function's arguments.
2926 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2927
2928 auto remap_arg_kind = [](StringRef argKind) {
2929 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2930 ? "pod_ubo"
2931 : argKind;
2932 };
2933
2934 auto *fty = F.getType()->getPointerElementType();
2935 auto *func_ty = dyn_cast<FunctionType>(fty);
2936
2937 // If we've clustereed POD arguments, then argument details are in metadata.
2938 // If an argument maps to a resource variable, then get descriptor set and
2939 // binding from the resoure variable. Other info comes from the metadata.
2940 const auto *arg_map = F.getMetadata("kernel_arg_map");
2941 if (arg_map) {
2942 for (const auto &arg : arg_map->operands()) {
2943 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
2944 assert(arg_node->getNumOperands() == 6);
2945 const auto name =
2946 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2947 const auto old_index =
2948 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2949 // Remapped argument index
2950 const auto new_index =
2951 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2952 const auto offset =
2953 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
2954 const auto argKind = remap_arg_kind(
2955 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2956 const auto spec_id =
2957 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2958 if (spec_id > 0) {
2959 // This was a pointer-to-local argument. It is not associated with a
2960 // resource variable.
2961 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2962 << ",argOrdinal," << old_index << ",argKind,"
2963 << argKind << ",arrayElemSize,"
2964 << DL.getTypeAllocSize(
2965 func_ty->getParamType(unsigned(new_index))
2966 ->getPointerElementType())
2967 << ",arrayNumElemSpecId," << spec_id << "\n";
2968 } else {
2969 auto *info = resource_var_at_index[new_index];
2970 assert(info);
2971 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2972 << ",argOrdinal," << old_index << ",descriptorSet,"
2973 << info->descriptor_set << ",binding," << info->binding
2974 << ",offset," << offset << ",argKind," << argKind
2975 << "\n";
2976 }
2977 }
2978 } else {
2979 // There is no argument map.
2980 // Take descriptor info from the resource variable calls.
2981 // Take argument name from the arguments list.
2982
2983 SmallVector<Argument *, 4> arguments;
2984 for (auto &arg : F.args()) {
2985 arguments.push_back(&arg);
2986 }
2987
2988 unsigned arg_index = 0;
2989 for (auto *info : resource_var_at_index) {
2990 if (info) {
2991 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2992 << arguments[arg_index]->getName() << ",argOrdinal,"
2993 << arg_index << ",descriptorSet,"
2994 << info->descriptor_set << ",binding," << info->binding
2995 << ",offset," << 0 << ",argKind,"
2996 << remap_arg_kind(
2997 clspv::GetArgKindName(info->arg_kind))
2998 << "\n";
2999 }
3000 arg_index++;
3001 }
3002 // Generate mappings for pointer-to-local arguments.
3003 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3004 Argument *arg = arguments[arg_index];
3005 auto where = LocalArgMap.find(arg);
3006 if (where != LocalArgMap.end()) {
3007 auto &local_arg_info = where->second;
3008 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3009 << arg->getName() << ",argOrdinal," << arg_index
3010 << ",argKind,"
3011 << "local"
3012 << ",arrayElemSize,"
3013 << DL.getTypeAllocSize(local_arg_info.elem_type)
3014 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3015 << "\n";
3016 }
3017 }
3018 }
3019}
3020
David Neto22f144c2017-06-12 14:26:21 -04003021void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003022 Module& M = *F.getParent();
3023 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003024 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3025 ValueMapType &VMap = getValueMap();
3026 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003027 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3028 auto &GlobalConstArgSet = getGlobalConstArgSet();
3029
3030 FunctionType *FTy = F.getFunctionType();
3031
3032 //
David Neto22f144c2017-06-12 14:26:21 -04003033 // Generate OPFunction.
3034 //
3035
3036 // FOps[0] : Result Type ID
3037 // FOps[1] : Function Control
3038 // FOps[2] : Function Type ID
3039 SPIRVOperandList FOps;
3040
3041 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003042 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003043
3044 // Check function attributes for SPIRV Function Control.
3045 uint32_t FuncControl = spv::FunctionControlMaskNone;
3046 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3047 FuncControl |= spv::FunctionControlInlineMask;
3048 }
3049 if (F.hasFnAttribute(Attribute::NoInline)) {
3050 FuncControl |= spv::FunctionControlDontInlineMask;
3051 }
3052 // TODO: Check llvm attribute for Function Control Pure.
3053 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3054 FuncControl |= spv::FunctionControlPureMask;
3055 }
3056 // TODO: Check llvm attribute for Function Control Const.
3057 if (F.hasFnAttribute(Attribute::ReadNone)) {
3058 FuncControl |= spv::FunctionControlConstMask;
3059 }
3060
David Neto257c3892018-04-11 13:19:45 -04003061 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003062
3063 uint32_t FTyID;
3064 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3065 SmallVector<Type *, 4> NewFuncParamTys;
3066 FunctionType *NewFTy =
3067 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3068 FTyID = lookupType(NewFTy);
3069 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003070 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003071 if (GlobalConstFuncTyMap.count(FTy)) {
3072 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3073 } else {
3074 FTyID = lookupType(FTy);
3075 }
3076 }
3077
David Neto257c3892018-04-11 13:19:45 -04003078 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003079
3080 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3081 EntryPoints.push_back(std::make_pair(&F, nextID));
3082 }
3083
3084 VMap[&F] = nextID;
3085
David Neto482550a2018-03-24 05:21:07 -07003086 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003087 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3088 }
David Neto22f144c2017-06-12 14:26:21 -04003089 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003090 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003091 SPIRVInstList.push_back(FuncInst);
3092
3093 //
3094 // Generate OpFunctionParameter for Normal function.
3095 //
3096
3097 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3098 // Iterate Argument for name instead of param type from function type.
3099 unsigned ArgIdx = 0;
3100 for (Argument &Arg : F.args()) {
3101 VMap[&Arg] = nextID;
3102
3103 // ParamOps[0] : Result Type ID
3104 SPIRVOperandList ParamOps;
3105
3106 // Find SPIRV instruction for parameter type.
3107 uint32_t ParamTyID = lookupType(Arg.getType());
3108 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3109 if (GlobalConstFuncTyMap.count(FTy)) {
3110 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3111 Type *EleTy = PTy->getPointerElementType();
3112 Type *ArgTy =
3113 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3114 ParamTyID = lookupType(ArgTy);
3115 GlobalConstArgSet.insert(&Arg);
3116 }
3117 }
3118 }
David Neto257c3892018-04-11 13:19:45 -04003119 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003120
3121 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003122 auto *ParamInst =
3123 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003124 SPIRVInstList.push_back(ParamInst);
3125
3126 ArgIdx++;
3127 }
3128 }
3129}
3130
David Neto5c22a252018-03-15 16:07:41 -04003131void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003132 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3133 EntryPointVecType &EntryPoints = getEntryPointVec();
3134 ValueMapType &VMap = getValueMap();
3135 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3136 uint32_t &ExtInstImportID = getOpExtInstImportID();
3137 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3138
3139 // Set up insert point.
3140 auto InsertPoint = SPIRVInstList.begin();
3141
3142 //
3143 // Generate OpCapability
3144 //
3145 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3146
3147 // Ops[0] = Capability
3148 SPIRVOperandList Ops;
3149
David Neto87846742018-04-11 17:36:22 -04003150 auto *CapInst =
3151 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003152 SPIRVInstList.insert(InsertPoint, CapInst);
3153
3154 for (Type *Ty : getTypeList()) {
3155 // Find the i16 type.
3156 if (Ty->isIntegerTy(16)) {
3157 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003158 SPIRVInstList.insert(InsertPoint,
3159 new SPIRVInstruction(spv::OpCapability,
3160 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003161 } else if (Ty->isIntegerTy(64)) {
3162 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003163 SPIRVInstList.insert(InsertPoint,
3164 new SPIRVInstruction(spv::OpCapability,
3165 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003166 } else if (Ty->isHalfTy()) {
3167 // Generate OpCapability for half type.
3168 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003169 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3170 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003171 } else if (Ty->isDoubleTy()) {
3172 // Generate OpCapability for double type.
3173 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003174 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3175 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003176 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3177 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003178 if (STy->getName().equals("opencl.image2d_wo_t") ||
3179 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003180 // Generate OpCapability for write only image type.
3181 SPIRVInstList.insert(
3182 InsertPoint,
3183 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003184 spv::OpCapability,
3185 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003186 }
3187 }
3188 }
3189 }
3190
David Neto5c22a252018-03-15 16:07:41 -04003191 { // OpCapability ImageQuery
3192 bool hasImageQuery = false;
3193 for (const char *imageQuery : {
3194 "_Z15get_image_width14ocl_image2d_ro",
3195 "_Z15get_image_width14ocl_image2d_wo",
3196 "_Z16get_image_height14ocl_image2d_ro",
3197 "_Z16get_image_height14ocl_image2d_wo",
3198 }) {
3199 if (module.getFunction(imageQuery)) {
3200 hasImageQuery = true;
3201 break;
3202 }
3203 }
3204 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003205 auto *ImageQueryCapInst = new SPIRVInstruction(
3206 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003207 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3208 }
3209 }
3210
David Neto22f144c2017-06-12 14:26:21 -04003211 if (hasVariablePointers()) {
3212 //
3213 // Generate OpCapability and OpExtension
3214 //
3215
3216 //
3217 // Generate OpCapability.
3218 //
3219 // Ops[0] = Capability
3220 //
3221 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003222 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003223
David Neto87846742018-04-11 17:36:22 -04003224 SPIRVInstList.insert(InsertPoint,
3225 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003226
3227 //
3228 // Generate OpExtension.
3229 //
3230 // Ops[0] = Name (Literal String)
3231 //
David Netoa772fd12017-08-04 14:17:33 -04003232 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3233 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003234
David Neto87846742018-04-11 17:36:22 -04003235 auto *ExtensionInst =
3236 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003237 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003238 }
David Neto22f144c2017-06-12 14:26:21 -04003239 }
3240
3241 if (ExtInstImportID) {
3242 ++InsertPoint;
3243 }
3244
3245 //
3246 // Generate OpMemoryModel
3247 //
3248 // Memory model for Vulkan will always be GLSL450.
3249
3250 // Ops[0] = Addressing Model
3251 // Ops[1] = Memory Model
3252 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003253 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003254
David Neto87846742018-04-11 17:36:22 -04003255 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003256 SPIRVInstList.insert(InsertPoint, MemModelInst);
3257
3258 //
3259 // Generate OpEntryPoint
3260 //
3261 for (auto EntryPoint : EntryPoints) {
3262 // Ops[0] = Execution Model
3263 // Ops[1] = EntryPoint ID
3264 // Ops[2] = Name (Literal String)
3265 // ...
3266 //
3267 // TODO: Do we need to consider Interface ID for forward references???
3268 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003269 const StringRef& name = EntryPoint.first->getName();
3270 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3271 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003272
David Neto22f144c2017-06-12 14:26:21 -04003273 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003274 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003275 }
3276
David Neto87846742018-04-11 17:36:22 -04003277 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003278 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3279 }
3280
3281 for (auto EntryPoint : EntryPoints) {
3282 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3283 ->getMetadata("reqd_work_group_size")) {
3284
3285 if (!BuiltinDimVec.empty()) {
3286 llvm_unreachable(
3287 "Kernels should have consistent work group size definition");
3288 }
3289
3290 //
3291 // Generate OpExecutionMode
3292 //
3293
3294 // Ops[0] = Entry Point ID
3295 // Ops[1] = Execution Mode
3296 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3297 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003298 Ops << MkId(EntryPoint.second)
3299 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003300
3301 uint32_t XDim = static_cast<uint32_t>(
3302 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3303 uint32_t YDim = static_cast<uint32_t>(
3304 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3305 uint32_t ZDim = static_cast<uint32_t>(
3306 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3307
David Neto257c3892018-04-11 13:19:45 -04003308 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003309
David Neto87846742018-04-11 17:36:22 -04003310 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003311 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3312 }
3313 }
3314
3315 //
3316 // Generate OpSource.
3317 //
3318 // Ops[0] = SourceLanguage ID
3319 // Ops[1] = Version (LiteralNum)
3320 //
3321 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003322 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003323
David Neto87846742018-04-11 17:36:22 -04003324 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003325 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3326
3327 if (!BuiltinDimVec.empty()) {
3328 //
3329 // Generate OpDecorates for x/y/z dimension.
3330 //
3331 // Ops[0] = Target ID
3332 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003333 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003334
3335 // X Dimension
3336 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003337 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003338 SPIRVInstList.insert(InsertPoint,
3339 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003340
3341 // Y Dimension
3342 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003343 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003344 SPIRVInstList.insert(InsertPoint,
3345 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003346
3347 // Z Dimension
3348 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003349 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003350 SPIRVInstList.insert(InsertPoint,
3351 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003352 }
3353}
3354
3355void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3356 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3357 ValueMapType &VMap = getValueMap();
David Neto862b7d82018-06-14 18:48:37 -04003358 LLVMContext &Context = F.getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003359
David Neto862b7d82018-06-14 18:48:37 -04003360 // Do remaining instruction generation for kernel arguments.
3361 // If an argument maps to a module-scope resource variables (i.e. it has
3362 // a descriptor set and binding), then its code generation is already
3363 // handled by the logic to handle the ResourceVarInfo objects we
3364 // found earlier in the flow.
3365 //
3366 // All that remains is to generate the access chain instruction to get the
3367 // first element of each pointer-to-local argument.
David Neto22f144c2017-06-12 14:26:21 -04003368 for (Argument &Arg : F.args()) {
3369 if (Arg.use_empty()) {
3370 continue;
3371 }
3372
David Netoc6f3ab22018-04-06 18:02:31 -04003373 Type *ArgTy = Arg.getType();
3374 if (IsLocalPtr(ArgTy)) {
3375 // Generate OpAccessChain to point to the first element of the array.
3376 const LocalArgInfo &info = LocalArgMap[&Arg];
3377 VMap[&Arg] = info.first_elem_ptr_id;
3378
3379 SPIRVOperandList Ops;
3380 uint32_t zeroId = VMap[ConstantInt::get(Type::getInt32Ty(Context), 0)];
3381 Ops << MkId(lookupType(ArgTy)) << MkId(info.variable_id) << MkId(zeroId);
3382 SPIRVInstList.push_back(new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003383 spv::OpAccessChain, info.first_elem_ptr_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003384
3385 continue;
3386 }
3387
David Neto862b7d82018-06-14 18:48:37 -04003388 errs() << "Old algorithm for resource vars for kernel args should be dead "
3389 "code.\n";
3390 assert(false && "Expected this to be dead code");
David Neto22f144c2017-06-12 14:26:21 -04003391 }
3392}
3393
David Netob6e2e062018-04-25 10:32:06 -04003394void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3395 // Work around a driver bug. Initializers on Private variables might not
3396 // work. So the start of the kernel should store the initializer value to the
3397 // variables. Yes, *every* entry point pays this cost if *any* entry point
3398 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3399 // of complexity vs. runtime, for a broken driver.
3400 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3401 if (WorkgroupSizeVarID) {
3402 assert(WorkgroupSizeValueID);
3403
3404 SPIRVOperandList Ops;
3405 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3406
3407 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3408 getSPIRVInstList().push_back(Inst);
3409 }
3410}
3411
David Neto22f144c2017-06-12 14:26:21 -04003412void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3413 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3414 ValueMapType &VMap = getValueMap();
3415
David Netob6e2e062018-04-25 10:32:06 -04003416 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003417
3418 for (BasicBlock &BB : F) {
3419 // Register BasicBlock to ValueMap.
3420 VMap[&BB] = nextID;
3421
3422 //
3423 // Generate OpLabel for Basic Block.
3424 //
3425 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003426 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003427 SPIRVInstList.push_back(Inst);
3428
David Neto6dcd4712017-06-23 11:06:47 -04003429 // OpVariable instructions must come first.
3430 for (Instruction &I : BB) {
3431 if (isa<AllocaInst>(I)) {
3432 GenerateInstruction(I);
3433 }
3434 }
3435
David Neto22f144c2017-06-12 14:26:21 -04003436 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003437 if (clspv::Option::HackInitializers()) {
3438 GenerateEntryPointInitialStores();
3439 }
David Neto22f144c2017-06-12 14:26:21 -04003440 GenerateInstForArg(F);
3441 }
3442
3443 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003444 if (!isa<AllocaInst>(I)) {
3445 GenerateInstruction(I);
3446 }
David Neto22f144c2017-06-12 14:26:21 -04003447 }
3448 }
3449}
3450
3451spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3452 const std::map<CmpInst::Predicate, spv::Op> Map = {
3453 {CmpInst::ICMP_EQ, spv::OpIEqual},
3454 {CmpInst::ICMP_NE, spv::OpINotEqual},
3455 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3456 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3457 {CmpInst::ICMP_ULT, spv::OpULessThan},
3458 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3459 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3460 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3461 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3462 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3463 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3464 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3465 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3466 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3467 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3468 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3469 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3470 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3471 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3472 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3473 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3474 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3475
3476 assert(0 != Map.count(I->getPredicate()));
3477
3478 return Map.at(I->getPredicate());
3479}
3480
3481spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3482 const std::map<unsigned, spv::Op> Map{
3483 {Instruction::Trunc, spv::OpUConvert},
3484 {Instruction::ZExt, spv::OpUConvert},
3485 {Instruction::SExt, spv::OpSConvert},
3486 {Instruction::FPToUI, spv::OpConvertFToU},
3487 {Instruction::FPToSI, spv::OpConvertFToS},
3488 {Instruction::UIToFP, spv::OpConvertUToF},
3489 {Instruction::SIToFP, spv::OpConvertSToF},
3490 {Instruction::FPTrunc, spv::OpFConvert},
3491 {Instruction::FPExt, spv::OpFConvert},
3492 {Instruction::BitCast, spv::OpBitcast}};
3493
3494 assert(0 != Map.count(I.getOpcode()));
3495
3496 return Map.at(I.getOpcode());
3497}
3498
3499spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3500 if (I.getType()->isIntegerTy(1)) {
3501 switch (I.getOpcode()) {
3502 default:
3503 break;
3504 case Instruction::Or:
3505 return spv::OpLogicalOr;
3506 case Instruction::And:
3507 return spv::OpLogicalAnd;
3508 case Instruction::Xor:
3509 return spv::OpLogicalNotEqual;
3510 }
3511 }
3512
3513 const std::map<unsigned, spv::Op> Map {
3514 {Instruction::Add, spv::OpIAdd},
3515 {Instruction::FAdd, spv::OpFAdd},
3516 {Instruction::Sub, spv::OpISub},
3517 {Instruction::FSub, spv::OpFSub},
3518 {Instruction::Mul, spv::OpIMul},
3519 {Instruction::FMul, spv::OpFMul},
3520 {Instruction::UDiv, spv::OpUDiv},
3521 {Instruction::SDiv, spv::OpSDiv},
3522 {Instruction::FDiv, spv::OpFDiv},
3523 {Instruction::URem, spv::OpUMod},
3524 {Instruction::SRem, spv::OpSRem},
3525 {Instruction::FRem, spv::OpFRem},
3526 {Instruction::Or, spv::OpBitwiseOr},
3527 {Instruction::Xor, spv::OpBitwiseXor},
3528 {Instruction::And, spv::OpBitwiseAnd},
3529 {Instruction::Shl, spv::OpShiftLeftLogical},
3530 {Instruction::LShr, spv::OpShiftRightLogical},
3531 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3532
3533 assert(0 != Map.count(I.getOpcode()));
3534
3535 return Map.at(I.getOpcode());
3536}
3537
3538void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3539 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3540 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003541 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3542 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3543
3544 // Register Instruction to ValueMap.
3545 if (0 == VMap[&I]) {
3546 VMap[&I] = nextID;
3547 }
3548
3549 switch (I.getOpcode()) {
3550 default: {
3551 if (Instruction::isCast(I.getOpcode())) {
3552 //
3553 // Generate SPIRV instructions for cast operators.
3554 //
3555
David Netod2de94a2017-08-28 17:27:47 -04003556
3557 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003558 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003559 auto toI8 = Ty == Type::getInt8Ty(Context);
3560 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003561 // Handle zext, sext and uitofp with i1 type specially.
3562 if ((I.getOpcode() == Instruction::ZExt ||
3563 I.getOpcode() == Instruction::SExt ||
3564 I.getOpcode() == Instruction::UIToFP) &&
3565 (OpTy->isIntegerTy(1) ||
3566 (OpTy->isVectorTy() &&
3567 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3568 //
3569 // Generate OpSelect.
3570 //
3571
3572 // Ops[0] = Result Type ID
3573 // Ops[1] = Condition ID
3574 // Ops[2] = True Constant ID
3575 // Ops[3] = False Constant ID
3576 SPIRVOperandList Ops;
3577
David Neto257c3892018-04-11 13:19:45 -04003578 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003579
David Neto22f144c2017-06-12 14:26:21 -04003580 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003581 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003582
3583 uint32_t TrueID = 0;
3584 if (I.getOpcode() == Instruction::ZExt) {
3585 APInt One(32, 1);
3586 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3587 } else if (I.getOpcode() == Instruction::SExt) {
3588 APInt MinusOne(32, UINT64_MAX, true);
3589 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3590 } else {
3591 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3592 }
David Neto257c3892018-04-11 13:19:45 -04003593 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003594
3595 uint32_t FalseID = 0;
3596 if (I.getOpcode() == Instruction::ZExt) {
3597 FalseID = VMap[Constant::getNullValue(I.getType())];
3598 } else if (I.getOpcode() == Instruction::SExt) {
3599 FalseID = VMap[Constant::getNullValue(I.getType())];
3600 } else {
3601 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3602 }
David Neto257c3892018-04-11 13:19:45 -04003603 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003604
David Neto87846742018-04-11 17:36:22 -04003605 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003606 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003607 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3608 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3609 // 8 bits.
3610 // Before:
3611 // %result = trunc i32 %a to i8
3612 // After
3613 // %result = OpBitwiseAnd %uint %a %uint_255
3614
3615 SPIRVOperandList Ops;
3616
David Neto257c3892018-04-11 13:19:45 -04003617 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003618
3619 Type *UintTy = Type::getInt32Ty(Context);
3620 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003621 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003622
David Neto87846742018-04-11 17:36:22 -04003623 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003624 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003625 } else {
3626 // Ops[0] = Result Type ID
3627 // Ops[1] = Source Value ID
3628 SPIRVOperandList Ops;
3629
David Neto257c3892018-04-11 13:19:45 -04003630 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003631
David Neto87846742018-04-11 17:36:22 -04003632 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003633 SPIRVInstList.push_back(Inst);
3634 }
3635 } else if (isa<BinaryOperator>(I)) {
3636 //
3637 // Generate SPIRV instructions for binary operators.
3638 //
3639
3640 // Handle xor with i1 type specially.
3641 if (I.getOpcode() == Instruction::Xor &&
3642 I.getType() == Type::getInt1Ty(Context) &&
3643 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3644 //
3645 // Generate OpLogicalNot.
3646 //
3647 // Ops[0] = Result Type ID
3648 // Ops[1] = Operand
3649 SPIRVOperandList Ops;
3650
David Neto257c3892018-04-11 13:19:45 -04003651 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003652
3653 Value *CondV = I.getOperand(0);
3654 if (isa<Constant>(I.getOperand(0))) {
3655 CondV = I.getOperand(1);
3656 }
David Neto257c3892018-04-11 13:19:45 -04003657 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003658
David Neto87846742018-04-11 17:36:22 -04003659 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003660 SPIRVInstList.push_back(Inst);
3661 } else {
3662 // Ops[0] = Result Type ID
3663 // Ops[1] = Operand 0
3664 // Ops[2] = Operand 1
3665 SPIRVOperandList Ops;
3666
David Neto257c3892018-04-11 13:19:45 -04003667 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3668 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003669
David Neto87846742018-04-11 17:36:22 -04003670 auto *Inst =
3671 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003672 SPIRVInstList.push_back(Inst);
3673 }
3674 } else {
3675 I.print(errs());
3676 llvm_unreachable("Unsupported instruction???");
3677 }
3678 break;
3679 }
3680 case Instruction::GetElementPtr: {
3681 auto &GlobalConstArgSet = getGlobalConstArgSet();
3682
3683 //
3684 // Generate OpAccessChain.
3685 //
3686 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3687
3688 //
3689 // Generate OpAccessChain.
3690 //
3691
3692 // Ops[0] = Result Type ID
3693 // Ops[1] = Base ID
3694 // Ops[2] ... Ops[n] = Indexes ID
3695 SPIRVOperandList Ops;
3696
David Neto1a1a0582017-07-07 12:01:44 -04003697 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003698 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3699 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3700 // Use pointer type with private address space for global constant.
3701 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003702 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003703 }
David Neto257c3892018-04-11 13:19:45 -04003704
3705 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003706
David Neto862b7d82018-06-14 18:48:37 -04003707 // Generate the base pointer.
3708 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003709
David Neto862b7d82018-06-14 18:48:37 -04003710 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003711
3712 //
3713 // Follows below rules for gep.
3714 //
David Neto862b7d82018-06-14 18:48:37 -04003715 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3716 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003717 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3718 // first index.
3719 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3720 // use gep's first index.
3721 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3722 // gep's first index.
3723 //
3724 spv::Op Opcode = spv::OpAccessChain;
3725 unsigned offset = 0;
3726 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003727 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003728 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003729 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003730 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003731 }
David Neto862b7d82018-06-14 18:48:37 -04003732 } else {
David Neto22f144c2017-06-12 14:26:21 -04003733 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003734 }
3735
3736 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003737 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003738 // Do we need to generate ArrayStride? Check against the GEP result type
3739 // rather than the pointer type of the base because when indexing into
3740 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3741 // for something else in the SPIR-V.
3742 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3743 if (GetStorageClass(ResultType->getAddressSpace()) ==
3744 spv::StorageClassStorageBuffer) {
3745 // Save the need to generate an ArrayStride decoration. But defer
3746 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003747 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003748 }
David Neto22f144c2017-06-12 14:26:21 -04003749 }
3750
3751 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003752 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003753 }
3754
David Neto87846742018-04-11 17:36:22 -04003755 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003756 SPIRVInstList.push_back(Inst);
3757 break;
3758 }
3759 case Instruction::ExtractValue: {
3760 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3761 // Ops[0] = Result Type ID
3762 // Ops[1] = Composite ID
3763 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3764 SPIRVOperandList Ops;
3765
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003767
3768 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003769 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003770
3771 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003772 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003773 }
3774
David Neto87846742018-04-11 17:36:22 -04003775 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003776 SPIRVInstList.push_back(Inst);
3777 break;
3778 }
3779 case Instruction::InsertValue: {
3780 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3781 // Ops[0] = Result Type ID
3782 // Ops[1] = Object ID
3783 // Ops[2] = Composite ID
3784 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3785 SPIRVOperandList Ops;
3786
3787 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003788 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003789
3790 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003791 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003792
3793 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003794 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003795
3796 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003797 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003798 }
3799
David Neto87846742018-04-11 17:36:22 -04003800 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003801 SPIRVInstList.push_back(Inst);
3802 break;
3803 }
3804 case Instruction::Select: {
3805 //
3806 // Generate OpSelect.
3807 //
3808
3809 // Ops[0] = Result Type ID
3810 // Ops[1] = Condition ID
3811 // Ops[2] = True Constant ID
3812 // Ops[3] = False Constant ID
3813 SPIRVOperandList Ops;
3814
3815 // Find SPIRV instruction for parameter type.
3816 auto Ty = I.getType();
3817 if (Ty->isPointerTy()) {
3818 auto PointeeTy = Ty->getPointerElementType();
3819 if (PointeeTy->isStructTy() &&
3820 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3821 Ty = PointeeTy;
3822 }
3823 }
3824
David Neto257c3892018-04-11 13:19:45 -04003825 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3826 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003827
David Neto87846742018-04-11 17:36:22 -04003828 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003829 SPIRVInstList.push_back(Inst);
3830 break;
3831 }
3832 case Instruction::ExtractElement: {
3833 // Handle <4 x i8> type manually.
3834 Type *CompositeTy = I.getOperand(0)->getType();
3835 if (is4xi8vec(CompositeTy)) {
3836 //
3837 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3838 // <4 x i8>.
3839 //
3840
3841 //
3842 // Generate OpShiftRightLogical
3843 //
3844 // Ops[0] = Result Type ID
3845 // Ops[1] = Operand 0
3846 // Ops[2] = Operand 1
3847 //
3848 SPIRVOperandList Ops;
3849
David Neto257c3892018-04-11 13:19:45 -04003850 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003851
3852 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003853 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003854
3855 uint32_t Op1ID = 0;
3856 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3857 // Handle constant index.
3858 uint64_t Idx = CI->getZExtValue();
3859 Value *ShiftAmount =
3860 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3861 Op1ID = VMap[ShiftAmount];
3862 } else {
3863 // Handle variable index.
3864 SPIRVOperandList TmpOps;
3865
David Neto257c3892018-04-11 13:19:45 -04003866 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3867 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003868
3869 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003870 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003871
3872 Op1ID = nextID;
3873
David Neto87846742018-04-11 17:36:22 -04003874 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003875 SPIRVInstList.push_back(TmpInst);
3876 }
David Neto257c3892018-04-11 13:19:45 -04003877 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003878
3879 uint32_t ShiftID = nextID;
3880
David Neto87846742018-04-11 17:36:22 -04003881 auto *Inst =
3882 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003883 SPIRVInstList.push_back(Inst);
3884
3885 //
3886 // Generate OpBitwiseAnd
3887 //
3888 // Ops[0] = Result Type ID
3889 // Ops[1] = Operand 0
3890 // Ops[2] = Operand 1
3891 //
3892 Ops.clear();
3893
David Neto257c3892018-04-11 13:19:45 -04003894 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003895
3896 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003897 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003898
David Neto9b2d6252017-09-06 15:47:37 -04003899 // Reset mapping for this value to the result of the bitwise and.
3900 VMap[&I] = nextID;
3901
David Neto87846742018-04-11 17:36:22 -04003902 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003903 SPIRVInstList.push_back(Inst);
3904 break;
3905 }
3906
3907 // Ops[0] = Result Type ID
3908 // Ops[1] = Composite ID
3909 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3910 SPIRVOperandList Ops;
3911
David Neto257c3892018-04-11 13:19:45 -04003912 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003913
3914 spv::Op Opcode = spv::OpCompositeExtract;
3915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003916 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003917 } else {
David Neto257c3892018-04-11 13:19:45 -04003918 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003919 Opcode = spv::OpVectorExtractDynamic;
3920 }
3921
David Neto87846742018-04-11 17:36:22 -04003922 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003923 SPIRVInstList.push_back(Inst);
3924 break;
3925 }
3926 case Instruction::InsertElement: {
3927 // Handle <4 x i8> type manually.
3928 Type *CompositeTy = I.getOperand(0)->getType();
3929 if (is4xi8vec(CompositeTy)) {
3930 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3931 uint32_t CstFFID = VMap[CstFF];
3932
3933 uint32_t ShiftAmountID = 0;
3934 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3935 // Handle constant index.
3936 uint64_t Idx = CI->getZExtValue();
3937 Value *ShiftAmount =
3938 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3939 ShiftAmountID = VMap[ShiftAmount];
3940 } else {
3941 // Handle variable index.
3942 SPIRVOperandList TmpOps;
3943
David Neto257c3892018-04-11 13:19:45 -04003944 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3945 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003946
3947 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003948 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003949
3950 ShiftAmountID = nextID;
3951
David Neto87846742018-04-11 17:36:22 -04003952 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003953 SPIRVInstList.push_back(TmpInst);
3954 }
3955
3956 //
3957 // Generate mask operations.
3958 //
3959
3960 // ShiftLeft mask according to index of insertelement.
3961 SPIRVOperandList Ops;
3962
David Neto257c3892018-04-11 13:19:45 -04003963 const uint32_t ResTyID = lookupType(CompositeTy);
3964 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003965
3966 uint32_t MaskID = nextID;
3967
David Neto87846742018-04-11 17:36:22 -04003968 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003969 SPIRVInstList.push_back(Inst);
3970
3971 // Inverse mask.
3972 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003973 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003974
3975 uint32_t InvMaskID = nextID;
3976
David Neto87846742018-04-11 17:36:22 -04003977 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003978 SPIRVInstList.push_back(Inst);
3979
3980 // Apply mask.
3981 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003982 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003983
3984 uint32_t OrgValID = nextID;
3985
David Neto87846742018-04-11 17:36:22 -04003986 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003987 SPIRVInstList.push_back(Inst);
3988
3989 // Create correct value according to index of insertelement.
3990 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003991 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003992
3993 uint32_t InsertValID = nextID;
3994
David Neto87846742018-04-11 17:36:22 -04003995 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003996 SPIRVInstList.push_back(Inst);
3997
3998 // Insert value to original value.
3999 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004000 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004001
David Netoa394f392017-08-26 20:45:29 -04004002 VMap[&I] = nextID;
4003
David Neto87846742018-04-11 17:36:22 -04004004 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004005 SPIRVInstList.push_back(Inst);
4006
4007 break;
4008 }
4009
David Neto22f144c2017-06-12 14:26:21 -04004010 SPIRVOperandList Ops;
4011
James Priced26efea2018-06-09 23:28:32 +01004012 // Ops[0] = Result Type ID
4013 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004014
4015 spv::Op Opcode = spv::OpCompositeInsert;
4016 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004017 const auto value = CI->getZExtValue();
4018 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004019 // Ops[1] = Object ID
4020 // Ops[2] = Composite ID
4021 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4022 Ops << MkId(VMap[I.getOperand(1)])
4023 << MkId(VMap[I.getOperand(0)])
4024 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004025 } else {
James Priced26efea2018-06-09 23:28:32 +01004026 // Ops[1] = Composite ID
4027 // Ops[2] = Object ID
4028 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4029 Ops << MkId(VMap[I.getOperand(0)])
4030 << MkId(VMap[I.getOperand(1)])
4031 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004032 Opcode = spv::OpVectorInsertDynamic;
4033 }
4034
David Neto87846742018-04-11 17:36:22 -04004035 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004036 SPIRVInstList.push_back(Inst);
4037 break;
4038 }
4039 case Instruction::ShuffleVector: {
4040 // Ops[0] = Result Type ID
4041 // Ops[1] = Vector 1 ID
4042 // Ops[2] = Vector 2 ID
4043 // Ops[3] ... Ops[n] = Components (Literal Number)
4044 SPIRVOperandList Ops;
4045
David Neto257c3892018-04-11 13:19:45 -04004046 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4047 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004048
4049 uint64_t NumElements = 0;
4050 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4051 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4052
4053 if (Cst->isNullValue()) {
4054 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004055 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004056 }
4057 } else if (const ConstantDataSequential *CDS =
4058 dyn_cast<ConstantDataSequential>(Cst)) {
4059 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4060 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004061 const auto value = CDS->getElementAsInteger(i);
4062 assert(value <= UINT32_MAX);
4063 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004064 }
4065 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4066 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4067 auto Op = CV->getOperand(i);
4068
4069 uint32_t literal = 0;
4070
4071 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4072 literal = static_cast<uint32_t>(CI->getZExtValue());
4073 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4074 literal = 0xFFFFFFFFu;
4075 } else {
4076 Op->print(errs());
4077 llvm_unreachable("Unsupported element in ConstantVector!");
4078 }
4079
David Neto257c3892018-04-11 13:19:45 -04004080 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004081 }
4082 } else {
4083 Cst->print(errs());
4084 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4085 }
4086 }
4087
David Neto87846742018-04-11 17:36:22 -04004088 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004089 SPIRVInstList.push_back(Inst);
4090 break;
4091 }
4092 case Instruction::ICmp:
4093 case Instruction::FCmp: {
4094 CmpInst *CmpI = cast<CmpInst>(&I);
4095
David Netod4ca2e62017-07-06 18:47:35 -04004096 // Pointer equality is invalid.
4097 Type* ArgTy = CmpI->getOperand(0)->getType();
4098 if (isa<PointerType>(ArgTy)) {
4099 CmpI->print(errs());
4100 std::string name = I.getParent()->getParent()->getName();
4101 errs()
4102 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4103 << "in function " << name << "\n";
4104 llvm_unreachable("Pointer equality check is invalid");
4105 break;
4106 }
4107
David Neto257c3892018-04-11 13:19:45 -04004108 // Ops[0] = Result Type ID
4109 // Ops[1] = Operand 1 ID
4110 // Ops[2] = Operand 2 ID
4111 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004112
David Neto257c3892018-04-11 13:19:45 -04004113 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4114 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004115
4116 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004117 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004118 SPIRVInstList.push_back(Inst);
4119 break;
4120 }
4121 case Instruction::Br: {
4122 // Branch instrucion is deferred because it needs label's ID. Record slot's
4123 // location on SPIRVInstructionList.
4124 DeferredInsts.push_back(
4125 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4126 break;
4127 }
4128 case Instruction::Switch: {
4129 I.print(errs());
4130 llvm_unreachable("Unsupported instruction???");
4131 break;
4132 }
4133 case Instruction::IndirectBr: {
4134 I.print(errs());
4135 llvm_unreachable("Unsupported instruction???");
4136 break;
4137 }
4138 case Instruction::PHI: {
4139 // Branch instrucion is deferred because it needs label's ID. Record slot's
4140 // location on SPIRVInstructionList.
4141 DeferredInsts.push_back(
4142 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4143 break;
4144 }
4145 case Instruction::Alloca: {
4146 //
4147 // Generate OpVariable.
4148 //
4149 // Ops[0] : Result Type ID
4150 // Ops[1] : Storage Class
4151 SPIRVOperandList Ops;
4152
David Neto257c3892018-04-11 13:19:45 -04004153 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004154
David Neto87846742018-04-11 17:36:22 -04004155 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004156 SPIRVInstList.push_back(Inst);
4157 break;
4158 }
4159 case Instruction::Load: {
4160 LoadInst *LD = cast<LoadInst>(&I);
4161 //
4162 // Generate OpLoad.
4163 //
4164
David Neto0a2f98d2017-09-15 19:38:40 -04004165 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004166 uint32_t PointerID = VMap[LD->getPointerOperand()];
4167
4168 // This is a hack to work around what looks like a driver bug.
4169 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004170 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4171 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004172 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004173 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004174 // Generate a bitwise-and of the original value with itself.
4175 // We should have been able to get away with just an OpCopyObject,
4176 // but we need something more complex to get past certain driver bugs.
4177 // This is ridiculous, but necessary.
4178 // TODO(dneto): Revisit this once drivers fix their bugs.
4179
4180 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004181 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4182 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004183
David Neto87846742018-04-11 17:36:22 -04004184 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004185 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004186 break;
4187 }
4188
4189 // This is the normal path. Generate a load.
4190
David Neto22f144c2017-06-12 14:26:21 -04004191 // Ops[0] = Result Type ID
4192 // Ops[1] = Pointer ID
4193 // Ops[2] ... Ops[n] = Optional Memory Access
4194 //
4195 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004196
David Neto22f144c2017-06-12 14:26:21 -04004197 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004198 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004199
David Neto87846742018-04-11 17:36:22 -04004200 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004201 SPIRVInstList.push_back(Inst);
4202 break;
4203 }
4204 case Instruction::Store: {
4205 StoreInst *ST = cast<StoreInst>(&I);
4206 //
4207 // Generate OpStore.
4208 //
4209
4210 // Ops[0] = Pointer ID
4211 // Ops[1] = Object ID
4212 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4213 //
4214 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004215 SPIRVOperandList Ops;
4216 Ops << MkId(VMap[ST->getPointerOperand()])
4217 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004218
David Neto87846742018-04-11 17:36:22 -04004219 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004220 SPIRVInstList.push_back(Inst);
4221 break;
4222 }
4223 case Instruction::AtomicCmpXchg: {
4224 I.print(errs());
4225 llvm_unreachable("Unsupported instruction???");
4226 break;
4227 }
4228 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004229 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4230
4231 spv::Op opcode;
4232
4233 switch (AtomicRMW->getOperation()) {
4234 default:
4235 I.print(errs());
4236 llvm_unreachable("Unsupported instruction???");
4237 case llvm::AtomicRMWInst::Add:
4238 opcode = spv::OpAtomicIAdd;
4239 break;
4240 case llvm::AtomicRMWInst::Sub:
4241 opcode = spv::OpAtomicISub;
4242 break;
4243 case llvm::AtomicRMWInst::Xchg:
4244 opcode = spv::OpAtomicExchange;
4245 break;
4246 case llvm::AtomicRMWInst::Min:
4247 opcode = spv::OpAtomicSMin;
4248 break;
4249 case llvm::AtomicRMWInst::Max:
4250 opcode = spv::OpAtomicSMax;
4251 break;
4252 case llvm::AtomicRMWInst::UMin:
4253 opcode = spv::OpAtomicUMin;
4254 break;
4255 case llvm::AtomicRMWInst::UMax:
4256 opcode = spv::OpAtomicUMax;
4257 break;
4258 case llvm::AtomicRMWInst::And:
4259 opcode = spv::OpAtomicAnd;
4260 break;
4261 case llvm::AtomicRMWInst::Or:
4262 opcode = spv::OpAtomicOr;
4263 break;
4264 case llvm::AtomicRMWInst::Xor:
4265 opcode = spv::OpAtomicXor;
4266 break;
4267 }
4268
4269 //
4270 // Generate OpAtomic*.
4271 //
4272 SPIRVOperandList Ops;
4273
David Neto257c3892018-04-11 13:19:45 -04004274 Ops << MkId(lookupType(I.getType()))
4275 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004276
4277 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004278 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004279 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004280
4281 const auto ConstantMemorySemantics = ConstantInt::get(
4282 IntTy, spv::MemorySemanticsUniformMemoryMask |
4283 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004284 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004285
David Neto257c3892018-04-11 13:19:45 -04004286 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004287
4288 VMap[&I] = nextID;
4289
David Neto87846742018-04-11 17:36:22 -04004290 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004291 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004292 break;
4293 }
4294 case Instruction::Fence: {
4295 I.print(errs());
4296 llvm_unreachable("Unsupported instruction???");
4297 break;
4298 }
4299 case Instruction::Call: {
4300 CallInst *Call = dyn_cast<CallInst>(&I);
4301 Function *Callee = Call->getCalledFunction();
4302
David Neto862b7d82018-06-14 18:48:37 -04004303 if (Callee->getName().startswith("clspv.resource.var.")) {
4304 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4305 // Generate an OpLoad
4306 SPIRVOperandList Ops;
4307 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004308
David Neto862b7d82018-06-14 18:48:37 -04004309 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4310 << MkId(ResourceVarDeferredLoadCalls[Call]);
4311
4312 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4313 SPIRVInstList.push_back(Inst);
4314 VMap[Call] = load_id;
4315 break;
4316
4317 } else {
4318 // This maps to an OpVariable we've already generated.
4319 // No code is generated for the call.
4320 }
4321 break;
4322 }
4323
4324 // Sampler initializers become a load of the corresponding sampler.
4325
4326 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4327 // Map this to a load from the variable.
4328 const auto index_into_sampler_map =
4329 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4330
4331 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004332 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004333 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004334
David Neto257c3892018-04-11 13:19:45 -04004335 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004336 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004337
David Neto862b7d82018-06-14 18:48:37 -04004338 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004339 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004340 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004341 break;
4342 }
4343
4344 if (Callee->getName().startswith("spirv.atomic")) {
4345 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4346 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4347 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4348 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4349 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4350 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4351 .Case("spirv.atomic_compare_exchange",
4352 spv::OpAtomicCompareExchange)
4353 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4354 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4355 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4356 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4357 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4358 .Case("spirv.atomic_or", spv::OpAtomicOr)
4359 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4360 .Default(spv::OpNop);
4361
4362 //
4363 // Generate OpAtomic*.
4364 //
4365 SPIRVOperandList Ops;
4366
David Neto257c3892018-04-11 13:19:45 -04004367 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004368
4369 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004370 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004371 }
4372
4373 VMap[&I] = nextID;
4374
David Neto87846742018-04-11 17:36:22 -04004375 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004376 SPIRVInstList.push_back(Inst);
4377 break;
4378 }
4379
4380 if (Callee->getName().startswith("_Z3dot")) {
4381 // If the argument is a vector type, generate OpDot
4382 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4383 //
4384 // Generate OpDot.
4385 //
4386 SPIRVOperandList Ops;
4387
David Neto257c3892018-04-11 13:19:45 -04004388 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004389
4390 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004391 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004392 }
4393
4394 VMap[&I] = nextID;
4395
David Neto87846742018-04-11 17:36:22 -04004396 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004397 SPIRVInstList.push_back(Inst);
4398 } else {
4399 //
4400 // Generate OpFMul.
4401 //
4402 SPIRVOperandList Ops;
4403
David Neto257c3892018-04-11 13:19:45 -04004404 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004405
4406 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004407 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004408 }
4409
4410 VMap[&I] = nextID;
4411
David Neto87846742018-04-11 17:36:22 -04004412 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004413 SPIRVInstList.push_back(Inst);
4414 }
4415 break;
4416 }
4417
David Neto8505ebf2017-10-13 18:50:50 -04004418 if (Callee->getName().startswith("_Z4fmod")) {
4419 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4420 // The sign for a non-zero result is taken from x.
4421 // (Try an example.)
4422 // So translate to OpFRem
4423
4424 SPIRVOperandList Ops;
4425
David Neto257c3892018-04-11 13:19:45 -04004426 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004427
4428 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004429 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004430 }
4431
4432 VMap[&I] = nextID;
4433
David Neto87846742018-04-11 17:36:22 -04004434 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004435 SPIRVInstList.push_back(Inst);
4436 break;
4437 }
4438
David Neto22f144c2017-06-12 14:26:21 -04004439 // spirv.store_null.* intrinsics become OpStore's.
4440 if (Callee->getName().startswith("spirv.store_null")) {
4441 //
4442 // Generate OpStore.
4443 //
4444
4445 // Ops[0] = Pointer ID
4446 // Ops[1] = Object ID
4447 // Ops[2] ... Ops[n]
4448 SPIRVOperandList Ops;
4449
4450 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004451 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004452 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004453
David Neto87846742018-04-11 17:36:22 -04004454 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004455
4456 break;
4457 }
4458
4459 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4460 if (Callee->getName().startswith("spirv.copy_memory")) {
4461 //
4462 // Generate OpCopyMemory.
4463 //
4464
4465 // Ops[0] = Dst ID
4466 // Ops[1] = Src ID
4467 // Ops[2] = Memory Access
4468 // Ops[3] = Alignment
4469
4470 auto IsVolatile =
4471 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4472
4473 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4474 : spv::MemoryAccessMaskNone;
4475
4476 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4477
4478 auto Alignment =
4479 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4480
David Neto257c3892018-04-11 13:19:45 -04004481 SPIRVOperandList Ops;
4482 Ops << MkId(VMap[Call->getArgOperand(0)])
4483 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4484 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004485
David Neto87846742018-04-11 17:36:22 -04004486 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004487
4488 SPIRVInstList.push_back(Inst);
4489
4490 break;
4491 }
4492
4493 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4494 // with unit.
4495 if (Callee->getName().equals("_Z3absj") ||
4496 Callee->getName().equals("_Z3absDv2_j") ||
4497 Callee->getName().equals("_Z3absDv3_j") ||
4498 Callee->getName().equals("_Z3absDv4_j")) {
4499 VMap[&I] = VMap[Call->getOperand(0)];
4500 break;
4501 }
4502
4503 // barrier is converted to OpControlBarrier
4504 if (Callee->getName().equals("__spirv_control_barrier")) {
4505 //
4506 // Generate OpControlBarrier.
4507 //
4508 // Ops[0] = Execution Scope ID
4509 // Ops[1] = Memory Scope ID
4510 // Ops[2] = Memory Semantics ID
4511 //
4512 Value *ExecutionScope = Call->getArgOperand(0);
4513 Value *MemoryScope = Call->getArgOperand(1);
4514 Value *MemorySemantics = Call->getArgOperand(2);
4515
David Neto257c3892018-04-11 13:19:45 -04004516 SPIRVOperandList Ops;
4517 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4518 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004519
David Neto87846742018-04-11 17:36:22 -04004520 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004521 break;
4522 }
4523
4524 // memory barrier is converted to OpMemoryBarrier
4525 if (Callee->getName().equals("__spirv_memory_barrier")) {
4526 //
4527 // Generate OpMemoryBarrier.
4528 //
4529 // Ops[0] = Memory Scope ID
4530 // Ops[1] = Memory Semantics ID
4531 //
4532 SPIRVOperandList Ops;
4533
David Neto257c3892018-04-11 13:19:45 -04004534 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4535 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004536
David Neto257c3892018-04-11 13:19:45 -04004537 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004538
David Neto87846742018-04-11 17:36:22 -04004539 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004540 SPIRVInstList.push_back(Inst);
4541 break;
4542 }
4543
4544 // isinf is converted to OpIsInf
4545 if (Callee->getName().equals("__spirv_isinff") ||
4546 Callee->getName().equals("__spirv_isinfDv2_f") ||
4547 Callee->getName().equals("__spirv_isinfDv3_f") ||
4548 Callee->getName().equals("__spirv_isinfDv4_f")) {
4549 //
4550 // Generate OpIsInf.
4551 //
4552 // Ops[0] = Result Type ID
4553 // Ops[1] = X ID
4554 //
4555 SPIRVOperandList Ops;
4556
David Neto257c3892018-04-11 13:19:45 -04004557 Ops << MkId(lookupType(I.getType()))
4558 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004559
4560 VMap[&I] = nextID;
4561
David Neto87846742018-04-11 17:36:22 -04004562 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004563 SPIRVInstList.push_back(Inst);
4564 break;
4565 }
4566
4567 // isnan is converted to OpIsNan
4568 if (Callee->getName().equals("__spirv_isnanf") ||
4569 Callee->getName().equals("__spirv_isnanDv2_f") ||
4570 Callee->getName().equals("__spirv_isnanDv3_f") ||
4571 Callee->getName().equals("__spirv_isnanDv4_f")) {
4572 //
4573 // Generate OpIsInf.
4574 //
4575 // Ops[0] = Result Type ID
4576 // Ops[1] = X ID
4577 //
4578 SPIRVOperandList Ops;
4579
David Neto257c3892018-04-11 13:19:45 -04004580 Ops << MkId(lookupType(I.getType()))
4581 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004582
4583 VMap[&I] = nextID;
4584
David Neto87846742018-04-11 17:36:22 -04004585 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004586 SPIRVInstList.push_back(Inst);
4587 break;
4588 }
4589
4590 // all is converted to OpAll
4591 if (Callee->getName().equals("__spirv_allDv2_i") ||
4592 Callee->getName().equals("__spirv_allDv3_i") ||
4593 Callee->getName().equals("__spirv_allDv4_i")) {
4594 //
4595 // Generate OpAll.
4596 //
4597 // Ops[0] = Result Type ID
4598 // Ops[1] = Vector ID
4599 //
4600 SPIRVOperandList Ops;
4601
David Neto257c3892018-04-11 13:19:45 -04004602 Ops << MkId(lookupType(I.getType()))
4603 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004604
4605 VMap[&I] = nextID;
4606
David Neto87846742018-04-11 17:36:22 -04004607 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004608 SPIRVInstList.push_back(Inst);
4609 break;
4610 }
4611
4612 // any is converted to OpAny
4613 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4614 Callee->getName().equals("__spirv_anyDv3_i") ||
4615 Callee->getName().equals("__spirv_anyDv4_i")) {
4616 //
4617 // Generate OpAny.
4618 //
4619 // Ops[0] = Result Type ID
4620 // Ops[1] = Vector ID
4621 //
4622 SPIRVOperandList Ops;
4623
David Neto257c3892018-04-11 13:19:45 -04004624 Ops << MkId(lookupType(I.getType()))
4625 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004626
4627 VMap[&I] = nextID;
4628
David Neto87846742018-04-11 17:36:22 -04004629 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004630 SPIRVInstList.push_back(Inst);
4631 break;
4632 }
4633
4634 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4635 // Additionally, OpTypeSampledImage is generated.
4636 if (Callee->getName().equals(
4637 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4638 Callee->getName().equals(
4639 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4640 //
4641 // Generate OpSampledImage.
4642 //
4643 // Ops[0] = Result Type ID
4644 // Ops[1] = Image ID
4645 // Ops[2] = Sampler ID
4646 //
4647 SPIRVOperandList Ops;
4648
4649 Value *Image = Call->getArgOperand(0);
4650 Value *Sampler = Call->getArgOperand(1);
4651 Value *Coordinate = Call->getArgOperand(2);
4652
4653 TypeMapType &OpImageTypeMap = getImageTypeMap();
4654 Type *ImageTy = Image->getType()->getPointerElementType();
4655 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004656 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004657 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004658
4659 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004660
4661 uint32_t SampledImageID = nextID;
4662
David Neto87846742018-04-11 17:36:22 -04004663 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004664 SPIRVInstList.push_back(Inst);
4665
4666 //
4667 // Generate OpImageSampleExplicitLod.
4668 //
4669 // Ops[0] = Result Type ID
4670 // Ops[1] = Sampled Image ID
4671 // Ops[2] = Coordinate ID
4672 // Ops[3] = Image Operands Type ID
4673 // Ops[4] ... Ops[n] = Operands ID
4674 //
4675 Ops.clear();
4676
David Neto257c3892018-04-11 13:19:45 -04004677 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4678 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004679
4680 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004681 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004682
4683 VMap[&I] = nextID;
4684
David Neto87846742018-04-11 17:36:22 -04004685 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004686 SPIRVInstList.push_back(Inst);
4687 break;
4688 }
4689
4690 // write_imagef is mapped to OpImageWrite.
4691 if (Callee->getName().equals(
4692 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4693 Callee->getName().equals(
4694 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4695 //
4696 // Generate OpImageWrite.
4697 //
4698 // Ops[0] = Image ID
4699 // Ops[1] = Coordinate ID
4700 // Ops[2] = Texel ID
4701 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4702 // Ops[4] ... Ops[n] = (Optional) Operands ID
4703 //
4704 SPIRVOperandList Ops;
4705
4706 Value *Image = Call->getArgOperand(0);
4707 Value *Coordinate = Call->getArgOperand(1);
4708 Value *Texel = Call->getArgOperand(2);
4709
4710 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004711 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004712 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004713 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004714
David Neto87846742018-04-11 17:36:22 -04004715 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004716 SPIRVInstList.push_back(Inst);
4717 break;
4718 }
4719
David Neto5c22a252018-03-15 16:07:41 -04004720 // get_image_width is mapped to OpImageQuerySize
4721 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4722 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4723 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4724 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4725 //
4726 // Generate OpImageQuerySize, then pull out the right component.
4727 // Assume 2D image for now.
4728 //
4729 // Ops[0] = Image ID
4730 //
4731 // %sizes = OpImageQuerySizes %uint2 %im
4732 // %result = OpCompositeExtract %uint %sizes 0-or-1
4733 SPIRVOperandList Ops;
4734
4735 // Implement:
4736 // %sizes = OpImageQuerySizes %uint2 %im
4737 uint32_t SizesTypeID =
4738 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004739 Value *Image = Call->getArgOperand(0);
4740 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004741 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004742
4743 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004744 auto *QueryInst =
4745 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004746 SPIRVInstList.push_back(QueryInst);
4747
4748 // Reset value map entry since we generated an intermediate instruction.
4749 VMap[&I] = nextID;
4750
4751 // Implement:
4752 // %result = OpCompositeExtract %uint %sizes 0-or-1
4753 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004754 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004755
4756 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004757 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004758
David Neto87846742018-04-11 17:36:22 -04004759 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004760 SPIRVInstList.push_back(Inst);
4761 break;
4762 }
4763
David Neto22f144c2017-06-12 14:26:21 -04004764 // Call instrucion is deferred because it needs function's ID. Record
4765 // slot's location on SPIRVInstructionList.
4766 DeferredInsts.push_back(
4767 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4768
David Neto3fbb4072017-10-16 11:28:14 -04004769 // Check whether the implementation of this call uses an extended
4770 // instruction plus one more value-producing instruction. If so, then
4771 // reserve the id for the extra value-producing slot.
4772 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4773 if (EInst != kGlslExtInstBad) {
4774 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004775 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004776 VMap[&I] = nextID;
4777 nextID++;
4778 }
4779 break;
4780 }
4781 case Instruction::Ret: {
4782 unsigned NumOps = I.getNumOperands();
4783 if (NumOps == 0) {
4784 //
4785 // Generate OpReturn.
4786 //
David Neto87846742018-04-11 17:36:22 -04004787 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004788 } else {
4789 //
4790 // Generate OpReturnValue.
4791 //
4792
4793 // Ops[0] = Return Value ID
4794 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004795
4796 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004797
David Neto87846742018-04-11 17:36:22 -04004798 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004799 SPIRVInstList.push_back(Inst);
4800 break;
4801 }
4802 break;
4803 }
4804 }
4805}
4806
4807void SPIRVProducerPass::GenerateFuncEpilogue() {
4808 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4809
4810 //
4811 // Generate OpFunctionEnd
4812 //
4813
David Neto87846742018-04-11 17:36:22 -04004814 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004815 SPIRVInstList.push_back(Inst);
4816}
4817
4818bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4819 LLVMContext &Context = Ty->getContext();
4820 if (Ty->isVectorTy()) {
4821 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4822 Ty->getVectorNumElements() == 4) {
4823 return true;
4824 }
4825 }
4826
4827 return false;
4828}
4829
David Neto257c3892018-04-11 13:19:45 -04004830uint32_t SPIRVProducerPass::GetI32Zero() {
4831 if (0 == constant_i32_zero_id_) {
4832 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4833 "defined in the SPIR-V module");
4834 }
4835 return constant_i32_zero_id_;
4836}
4837
David Neto22f144c2017-06-12 14:26:21 -04004838void SPIRVProducerPass::HandleDeferredInstruction() {
4839 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4840 ValueMapType &VMap = getValueMap();
4841 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4842
4843 for (auto DeferredInst = DeferredInsts.rbegin();
4844 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4845 Value *Inst = std::get<0>(*DeferredInst);
4846 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4847 if (InsertPoint != SPIRVInstList.end()) {
4848 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4849 ++InsertPoint;
4850 }
4851 }
4852
4853 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4854 // Check whether basic block, which has this branch instruction, is loop
4855 // header or not. If it is loop header, generate OpLoopMerge and
4856 // OpBranchConditional.
4857 Function *Func = Br->getParent()->getParent();
4858 DominatorTree &DT =
4859 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4860 const LoopInfo &LI =
4861 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4862
4863 BasicBlock *BrBB = Br->getParent();
4864 if (LI.isLoopHeader(BrBB)) {
4865 Value *ContinueBB = nullptr;
4866 Value *MergeBB = nullptr;
4867
4868 Loop *L = LI.getLoopFor(BrBB);
4869 MergeBB = L->getExitBlock();
4870 if (!MergeBB) {
4871 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4872 // has regions with single entry/exit. As a result, loop should not
4873 // have multiple exits.
4874 llvm_unreachable("Loop has multiple exits???");
4875 }
4876
4877 if (L->isLoopLatch(BrBB)) {
4878 ContinueBB = BrBB;
4879 } else {
4880 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4881 // block.
4882 BasicBlock *Header = L->getHeader();
4883 BasicBlock *Latch = L->getLoopLatch();
4884 for (BasicBlock *BB : L->blocks()) {
4885 if (BB == Header) {
4886 continue;
4887 }
4888
4889 // Check whether block dominates block with back-edge.
4890 if (DT.dominates(BB, Latch)) {
4891 ContinueBB = BB;
4892 }
4893 }
4894
4895 if (!ContinueBB) {
4896 llvm_unreachable("Wrong continue block from loop");
4897 }
4898 }
4899
4900 //
4901 // Generate OpLoopMerge.
4902 //
4903 // Ops[0] = Merge Block ID
4904 // Ops[1] = Continue Target ID
4905 // Ops[2] = Selection Control
4906 SPIRVOperandList Ops;
4907
4908 // StructurizeCFG pass already manipulated CFG. Just use false block of
4909 // branch instruction as merge block.
4910 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004911 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004912 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4913 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004914
David Neto87846742018-04-11 17:36:22 -04004915 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004916 SPIRVInstList.insert(InsertPoint, MergeInst);
4917
4918 } else if (Br->isConditional()) {
4919 bool HasBackEdge = false;
4920
4921 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4922 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4923 HasBackEdge = true;
4924 }
4925 }
4926 if (!HasBackEdge) {
4927 //
4928 // Generate OpSelectionMerge.
4929 //
4930 // Ops[0] = Merge Block ID
4931 // Ops[1] = Selection Control
4932 SPIRVOperandList Ops;
4933
4934 // StructurizeCFG pass already manipulated CFG. Just use false block
4935 // of branch instruction as merge block.
4936 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004937 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004938
David Neto87846742018-04-11 17:36:22 -04004939 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004940 SPIRVInstList.insert(InsertPoint, MergeInst);
4941 }
4942 }
4943
4944 if (Br->isConditional()) {
4945 //
4946 // Generate OpBranchConditional.
4947 //
4948 // Ops[0] = Condition ID
4949 // Ops[1] = True Label ID
4950 // Ops[2] = False Label ID
4951 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4952 SPIRVOperandList Ops;
4953
4954 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004955 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004956 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004957
4958 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004959
David Neto87846742018-04-11 17:36:22 -04004960 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004961 SPIRVInstList.insert(InsertPoint, BrInst);
4962 } else {
4963 //
4964 // Generate OpBranch.
4965 //
4966 // Ops[0] = Target Label ID
4967 SPIRVOperandList Ops;
4968
4969 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004970 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004971
David Neto87846742018-04-11 17:36:22 -04004972 SPIRVInstList.insert(InsertPoint,
4973 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004974 }
4975 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4976 //
4977 // Generate OpPhi.
4978 //
4979 // Ops[0] = Result Type ID
4980 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4981 SPIRVOperandList Ops;
4982
David Neto257c3892018-04-11 13:19:45 -04004983 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004984
David Neto22f144c2017-06-12 14:26:21 -04004985 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4986 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004987 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004988 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004989 }
4990
4991 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004992 InsertPoint,
4993 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004994 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4995 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004996 auto callee_name = Callee->getName();
4997 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004998
4999 if (EInst) {
5000 uint32_t &ExtInstImportID = getOpExtInstImportID();
5001
5002 //
5003 // Generate OpExtInst.
5004 //
5005
5006 // Ops[0] = Result Type ID
5007 // Ops[1] = Set ID (OpExtInstImport ID)
5008 // Ops[2] = Instruction Number (Literal Number)
5009 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5010 SPIRVOperandList Ops;
5011
David Neto862b7d82018-06-14 18:48:37 -04005012 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5013 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005014
David Neto22f144c2017-06-12 14:26:21 -04005015 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5016 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005017 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005018 }
5019
David Neto87846742018-04-11 17:36:22 -04005020 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5021 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005022 SPIRVInstList.insert(InsertPoint, ExtInst);
5023
David Neto3fbb4072017-10-16 11:28:14 -04005024 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5025 if (IndirectExtInst != kGlslExtInstBad) {
5026 // Generate one more instruction that uses the result of the extended
5027 // instruction. Its result id is one more than the id of the
5028 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005029 LLVMContext &Context =
5030 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005031
David Neto3fbb4072017-10-16 11:28:14 -04005032 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5033 &VMap, &SPIRVInstList, &InsertPoint](
5034 spv::Op opcode, Constant *constant) {
5035 //
5036 // Generate instruction like:
5037 // result = opcode constant <extinst-result>
5038 //
5039 // Ops[0] = Result Type ID
5040 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5041 // Ops[2] = Operand 1 ;; the result of the extended instruction
5042 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005043
David Neto3fbb4072017-10-16 11:28:14 -04005044 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005045 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005046
5047 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5048 constant = ConstantVector::getSplat(
5049 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5050 }
David Neto257c3892018-04-11 13:19:45 -04005051 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005052
5053 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005054 InsertPoint, new SPIRVInstruction(
5055 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005056 };
5057
5058 switch (IndirectExtInst) {
5059 case glsl::ExtInstFindUMsb: // Implementing clz
5060 generate_extra_inst(
5061 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5062 break;
5063 case glsl::ExtInstAcos: // Implementing acospi
5064 case glsl::ExtInstAsin: // Implementing asinpi
5065 case glsl::ExtInstAtan2: // Implementing atan2pi
5066 generate_extra_inst(
5067 spv::OpFMul,
5068 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5069 break;
5070
5071 default:
5072 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005073 }
David Neto22f144c2017-06-12 14:26:21 -04005074 }
David Neto3fbb4072017-10-16 11:28:14 -04005075
David Neto862b7d82018-06-14 18:48:37 -04005076 } else if (callee_name.equals("_Z8popcounti") ||
5077 callee_name.equals("_Z8popcountj") ||
5078 callee_name.equals("_Z8popcountDv2_i") ||
5079 callee_name.equals("_Z8popcountDv3_i") ||
5080 callee_name.equals("_Z8popcountDv4_i") ||
5081 callee_name.equals("_Z8popcountDv2_j") ||
5082 callee_name.equals("_Z8popcountDv3_j") ||
5083 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005084 //
5085 // Generate OpBitCount
5086 //
5087 // Ops[0] = Result Type ID
5088 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005089 SPIRVOperandList Ops;
5090 Ops << MkId(lookupType(Call->getType()))
5091 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005092
5093 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005094 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005095 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005096
David Neto862b7d82018-06-14 18:48:37 -04005097 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005098
5099 // Generate an OpCompositeConstruct
5100 SPIRVOperandList Ops;
5101
5102 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005103 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005104
5105 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005106 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005107 }
5108
5109 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005110 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5111 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005112
David Neto862b7d82018-06-14 18:48:37 -04005113 } else if (callee_name.startswith("clspv.resource.var.")) {
5114
5115 // We have already mapped the call's result value to an ID.
5116 // Don't generate any code now.
5117
David Neto22f144c2017-06-12 14:26:21 -04005118 } else {
5119 //
5120 // Generate OpFunctionCall.
5121 //
5122
5123 // Ops[0] = Result Type ID
5124 // Ops[1] = Callee Function ID
5125 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5126 SPIRVOperandList Ops;
5127
David Neto862b7d82018-06-14 18:48:37 -04005128 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005129
5130 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005131 if (CalleeID == 0) {
5132 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005133 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005134 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5135 // causes an infinite loop. Instead, go ahead and generate
5136 // the bad function call. A validator will catch the 0-Id.
5137 // llvm_unreachable("Can't translate function call");
5138 }
David Neto22f144c2017-06-12 14:26:21 -04005139
David Neto257c3892018-04-11 13:19:45 -04005140 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005141
David Neto22f144c2017-06-12 14:26:21 -04005142 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5143 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005144 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005145 }
5146
David Neto87846742018-04-11 17:36:22 -04005147 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5148 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005149 SPIRVInstList.insert(InsertPoint, CallInst);
5150 }
5151 }
5152 }
5153}
5154
David Neto1a1a0582017-07-07 12:01:44 -04005155void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
David Netoc6f3ab22018-04-06 18:02:31 -04005156 if (getTypesNeedingArrayStride().empty() && LocalArgs.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005157 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005158 }
David Neto1a1a0582017-07-07 12:01:44 -04005159
5160 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005161
5162 // Find an iterator pointing just past the last decoration.
5163 bool seen_decorations = false;
5164 auto DecoInsertPoint =
5165 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5166 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5167 const bool is_decoration =
5168 Inst->getOpcode() == spv::OpDecorate ||
5169 Inst->getOpcode() == spv::OpMemberDecorate;
5170 if (is_decoration) {
5171 seen_decorations = true;
5172 return false;
5173 } else {
5174 return seen_decorations;
5175 }
5176 });
5177
David Netoc6f3ab22018-04-06 18:02:31 -04005178 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5179 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005180 for (auto *type : getTypesNeedingArrayStride()) {
5181 Type *elemTy = nullptr;
5182 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5183 elemTy = ptrTy->getElementType();
5184 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5185 elemTy = arrayTy->getArrayElementType();
5186 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5187 elemTy = seqTy->getSequentialElementType();
5188 } else {
5189 errs() << "Unhandled strided type " << *type << "\n";
5190 llvm_unreachable("Unhandled strided type");
5191 }
David Neto1a1a0582017-07-07 12:01:44 -04005192
5193 // Ops[0] = Target ID
5194 // Ops[1] = Decoration (ArrayStride)
5195 // Ops[2] = Stride number (Literal Number)
5196 SPIRVOperandList Ops;
5197
David Neto85082642018-03-24 06:55:20 -07005198 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005199 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005200
5201 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5202 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005203
David Neto87846742018-04-11 17:36:22 -04005204 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005205 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5206 }
David Netoc6f3ab22018-04-06 18:02:31 -04005207
5208 // Emit SpecId decorations targeting the array size value.
5209 for (const Argument *arg : LocalArgs) {
5210 const LocalArgInfo &arg_info = LocalArgMap[arg];
5211 SPIRVOperandList Ops;
5212 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5213 << MkNum(arg_info.spec_id);
5214 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005215 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005216 }
David Neto1a1a0582017-07-07 12:01:44 -04005217}
5218
David Neto22f144c2017-06-12 14:26:21 -04005219glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5220 return StringSwitch<glsl::ExtInst>(Name)
5221 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5222 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5223 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5224 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5225 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5226 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5227 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5228 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5229 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5230 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5231 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5232 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5233 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5234 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5235 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5236 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005237 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5238 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5239 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5240 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5241 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5242 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5243 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5244 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5245 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5246 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5247 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5248 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5249 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5250 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5251 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5252 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5253 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5254 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5255 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5256 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5257 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5258 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5259 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5260 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5261 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5262 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5263 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5264 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5265 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5266 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5267 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5268 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5269 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5270 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5271 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5272 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5273 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5274 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5275 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5276 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5277 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5278 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5279 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5280 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5281 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5282 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5283 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5284 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5285 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5286 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5287 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5288 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5289 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5290 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5291 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5292 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5293 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5294 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5295 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5296 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5297 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5298 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5299 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5300 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5301 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5302 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5303 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5304 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5305 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5306 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5307 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5308 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5309 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5310 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5311 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5312 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5313 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5314 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5315 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5316 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005317 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005318 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5319 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5320 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5321 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5322 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005323 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5324 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5325 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5326 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005327 .Default(kGlslExtInstBad);
5328}
5329
5330glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5331 // Check indirect cases.
5332 return StringSwitch<glsl::ExtInst>(Name)
5333 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5334 // Use exact match on float arg because these need a multiply
5335 // of a constant of the right floating point type.
5336 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5337 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5338 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5339 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5340 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5341 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5342 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5343 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5344 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5345 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5346 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5347 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5348 .Default(kGlslExtInstBad);
5349}
5350
5351glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5352 auto direct = getExtInstEnum(Name);
5353 if (direct != kGlslExtInstBad)
5354 return direct;
5355 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005356}
5357
5358void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5359 out << "%" << Inst->getResultID();
5360}
5361
5362void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5363 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5364 out << "\t" << spv::getOpName(Opcode);
5365}
5366
5367void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5368 SPIRVOperandType OpTy = Op->getType();
5369 switch (OpTy) {
5370 default: {
5371 llvm_unreachable("Unsupported SPIRV Operand Type???");
5372 break;
5373 }
5374 case SPIRVOperandType::NUMBERID: {
5375 out << "%" << Op->getNumID();
5376 break;
5377 }
5378 case SPIRVOperandType::LITERAL_STRING: {
5379 out << "\"" << Op->getLiteralStr() << "\"";
5380 break;
5381 }
5382 case SPIRVOperandType::LITERAL_INTEGER: {
5383 // TODO: Handle LiteralNum carefully.
5384 for (auto Word : Op->getLiteralNum()) {
5385 out << Word;
5386 }
5387 break;
5388 }
5389 case SPIRVOperandType::LITERAL_FLOAT: {
5390 // TODO: Handle LiteralNum carefully.
5391 for (auto Word : Op->getLiteralNum()) {
5392 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5393 SmallString<8> Str;
5394 APF.toString(Str, 6, 2);
5395 out << Str;
5396 }
5397 break;
5398 }
5399 }
5400}
5401
5402void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5403 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5404 out << spv::getCapabilityName(Cap);
5405}
5406
5407void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5408 auto LiteralNum = Op->getLiteralNum();
5409 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5410 out << glsl::getExtInstName(Ext);
5411}
5412
5413void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5414 spv::AddressingModel AddrModel =
5415 static_cast<spv::AddressingModel>(Op->getNumID());
5416 out << spv::getAddressingModelName(AddrModel);
5417}
5418
5419void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5420 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5421 out << spv::getMemoryModelName(MemModel);
5422}
5423
5424void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5425 spv::ExecutionModel ExecModel =
5426 static_cast<spv::ExecutionModel>(Op->getNumID());
5427 out << spv::getExecutionModelName(ExecModel);
5428}
5429
5430void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5431 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5432 out << spv::getExecutionModeName(ExecMode);
5433}
5434
5435void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5436 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5437 out << spv::getSourceLanguageName(SourceLang);
5438}
5439
5440void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5441 spv::FunctionControlMask FuncCtrl =
5442 static_cast<spv::FunctionControlMask>(Op->getNumID());
5443 out << spv::getFunctionControlName(FuncCtrl);
5444}
5445
5446void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5447 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5448 out << getStorageClassName(StClass);
5449}
5450
5451void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5452 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5453 out << getDecorationName(Deco);
5454}
5455
5456void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5457 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5458 out << getBuiltInName(BIn);
5459}
5460
5461void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5462 spv::SelectionControlMask BIn =
5463 static_cast<spv::SelectionControlMask>(Op->getNumID());
5464 out << getSelectionControlName(BIn);
5465}
5466
5467void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5468 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5469 out << getLoopControlName(BIn);
5470}
5471
5472void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5473 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5474 out << getDimName(DIM);
5475}
5476
5477void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5478 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5479 out << getImageFormatName(Format);
5480}
5481
5482void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5483 out << spv::getMemoryAccessName(
5484 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5485}
5486
5487void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5488 auto LiteralNum = Op->getLiteralNum();
5489 spv::ImageOperandsMask Type =
5490 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5491 out << getImageOperandsName(Type);
5492}
5493
5494void SPIRVProducerPass::WriteSPIRVAssembly() {
5495 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5496
5497 for (auto Inst : SPIRVInstList) {
5498 SPIRVOperandList Ops = Inst->getOperands();
5499 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5500
5501 switch (Opcode) {
5502 default: {
5503 llvm_unreachable("Unsupported SPIRV instruction");
5504 break;
5505 }
5506 case spv::OpCapability: {
5507 // Ops[0] = Capability
5508 PrintOpcode(Inst);
5509 out << " ";
5510 PrintCapability(Ops[0]);
5511 out << "\n";
5512 break;
5513 }
5514 case spv::OpMemoryModel: {
5515 // Ops[0] = Addressing Model
5516 // Ops[1] = Memory Model
5517 PrintOpcode(Inst);
5518 out << " ";
5519 PrintAddrModel(Ops[0]);
5520 out << " ";
5521 PrintMemModel(Ops[1]);
5522 out << "\n";
5523 break;
5524 }
5525 case spv::OpEntryPoint: {
5526 // Ops[0] = Execution Model
5527 // Ops[1] = EntryPoint ID
5528 // Ops[2] = Name (Literal String)
5529 // Ops[3] ... Ops[n] = Interface ID
5530 PrintOpcode(Inst);
5531 out << " ";
5532 PrintExecModel(Ops[0]);
5533 for (uint32_t i = 1; i < Ops.size(); i++) {
5534 out << " ";
5535 PrintOperand(Ops[i]);
5536 }
5537 out << "\n";
5538 break;
5539 }
5540 case spv::OpExecutionMode: {
5541 // Ops[0] = Entry Point ID
5542 // Ops[1] = Execution Mode
5543 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5544 PrintOpcode(Inst);
5545 out << " ";
5546 PrintOperand(Ops[0]);
5547 out << " ";
5548 PrintExecMode(Ops[1]);
5549 for (uint32_t i = 2; i < Ops.size(); i++) {
5550 out << " ";
5551 PrintOperand(Ops[i]);
5552 }
5553 out << "\n";
5554 break;
5555 }
5556 case spv::OpSource: {
5557 // Ops[0] = SourceLanguage ID
5558 // Ops[1] = Version (LiteralNum)
5559 PrintOpcode(Inst);
5560 out << " ";
5561 PrintSourceLanguage(Ops[0]);
5562 out << " ";
5563 PrintOperand(Ops[1]);
5564 out << "\n";
5565 break;
5566 }
5567 case spv::OpDecorate: {
5568 // Ops[0] = Target ID
5569 // Ops[1] = Decoration (Block or BufferBlock)
5570 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5571 PrintOpcode(Inst);
5572 out << " ";
5573 PrintOperand(Ops[0]);
5574 out << " ";
5575 PrintDecoration(Ops[1]);
5576 // Handle BuiltIn OpDecorate specially.
5577 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5578 out << " ";
5579 PrintBuiltIn(Ops[2]);
5580 } else {
5581 for (uint32_t i = 2; i < Ops.size(); i++) {
5582 out << " ";
5583 PrintOperand(Ops[i]);
5584 }
5585 }
5586 out << "\n";
5587 break;
5588 }
5589 case spv::OpMemberDecorate: {
5590 // Ops[0] = Structure Type ID
5591 // Ops[1] = Member Index(Literal Number)
5592 // Ops[2] = Decoration
5593 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5594 PrintOpcode(Inst);
5595 out << " ";
5596 PrintOperand(Ops[0]);
5597 out << " ";
5598 PrintOperand(Ops[1]);
5599 out << " ";
5600 PrintDecoration(Ops[2]);
5601 for (uint32_t i = 3; i < Ops.size(); i++) {
5602 out << " ";
5603 PrintOperand(Ops[i]);
5604 }
5605 out << "\n";
5606 break;
5607 }
5608 case spv::OpTypePointer: {
5609 // Ops[0] = Storage Class
5610 // Ops[1] = Element Type ID
5611 PrintResID(Inst);
5612 out << " = ";
5613 PrintOpcode(Inst);
5614 out << " ";
5615 PrintStorageClass(Ops[0]);
5616 out << " ";
5617 PrintOperand(Ops[1]);
5618 out << "\n";
5619 break;
5620 }
5621 case spv::OpTypeImage: {
5622 // Ops[0] = Sampled Type ID
5623 // Ops[1] = Dim ID
5624 // Ops[2] = Depth (Literal Number)
5625 // Ops[3] = Arrayed (Literal Number)
5626 // Ops[4] = MS (Literal Number)
5627 // Ops[5] = Sampled (Literal Number)
5628 // Ops[6] = Image Format ID
5629 PrintResID(Inst);
5630 out << " = ";
5631 PrintOpcode(Inst);
5632 out << " ";
5633 PrintOperand(Ops[0]);
5634 out << " ";
5635 PrintDimensionality(Ops[1]);
5636 out << " ";
5637 PrintOperand(Ops[2]);
5638 out << " ";
5639 PrintOperand(Ops[3]);
5640 out << " ";
5641 PrintOperand(Ops[4]);
5642 out << " ";
5643 PrintOperand(Ops[5]);
5644 out << " ";
5645 PrintImageFormat(Ops[6]);
5646 out << "\n";
5647 break;
5648 }
5649 case spv::OpFunction: {
5650 // Ops[0] : Result Type ID
5651 // Ops[1] : Function Control
5652 // Ops[2] : Function Type ID
5653 PrintResID(Inst);
5654 out << " = ";
5655 PrintOpcode(Inst);
5656 out << " ";
5657 PrintOperand(Ops[0]);
5658 out << " ";
5659 PrintFuncCtrl(Ops[1]);
5660 out << " ";
5661 PrintOperand(Ops[2]);
5662 out << "\n";
5663 break;
5664 }
5665 case spv::OpSelectionMerge: {
5666 // Ops[0] = Merge Block ID
5667 // Ops[1] = Selection Control
5668 PrintOpcode(Inst);
5669 out << " ";
5670 PrintOperand(Ops[0]);
5671 out << " ";
5672 PrintSelectionControl(Ops[1]);
5673 out << "\n";
5674 break;
5675 }
5676 case spv::OpLoopMerge: {
5677 // Ops[0] = Merge Block ID
5678 // Ops[1] = Continue Target ID
5679 // Ops[2] = Selection Control
5680 PrintOpcode(Inst);
5681 out << " ";
5682 PrintOperand(Ops[0]);
5683 out << " ";
5684 PrintOperand(Ops[1]);
5685 out << " ";
5686 PrintLoopControl(Ops[2]);
5687 out << "\n";
5688 break;
5689 }
5690 case spv::OpImageSampleExplicitLod: {
5691 // Ops[0] = Result Type ID
5692 // Ops[1] = Sampled Image ID
5693 // Ops[2] = Coordinate ID
5694 // Ops[3] = Image Operands Type ID
5695 // Ops[4] ... Ops[n] = Operands ID
5696 PrintResID(Inst);
5697 out << " = ";
5698 PrintOpcode(Inst);
5699 for (uint32_t i = 0; i < 3; i++) {
5700 out << " ";
5701 PrintOperand(Ops[i]);
5702 }
5703 out << " ";
5704 PrintImageOperandsType(Ops[3]);
5705 for (uint32_t i = 4; i < Ops.size(); i++) {
5706 out << " ";
5707 PrintOperand(Ops[i]);
5708 }
5709 out << "\n";
5710 break;
5711 }
5712 case spv::OpVariable: {
5713 // Ops[0] : Result Type ID
5714 // Ops[1] : Storage Class
5715 // Ops[2] ... Ops[n] = Initializer IDs
5716 PrintResID(Inst);
5717 out << " = ";
5718 PrintOpcode(Inst);
5719 out << " ";
5720 PrintOperand(Ops[0]);
5721 out << " ";
5722 PrintStorageClass(Ops[1]);
5723 for (uint32_t i = 2; i < Ops.size(); i++) {
5724 out << " ";
5725 PrintOperand(Ops[i]);
5726 }
5727 out << "\n";
5728 break;
5729 }
5730 case spv::OpExtInst: {
5731 // Ops[0] = Result Type ID
5732 // Ops[1] = Set ID (OpExtInstImport ID)
5733 // Ops[2] = Instruction Number (Literal Number)
5734 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5735 PrintResID(Inst);
5736 out << " = ";
5737 PrintOpcode(Inst);
5738 out << " ";
5739 PrintOperand(Ops[0]);
5740 out << " ";
5741 PrintOperand(Ops[1]);
5742 out << " ";
5743 PrintExtInst(Ops[2]);
5744 for (uint32_t i = 3; i < Ops.size(); i++) {
5745 out << " ";
5746 PrintOperand(Ops[i]);
5747 }
5748 out << "\n";
5749 break;
5750 }
5751 case spv::OpCopyMemory: {
5752 // Ops[0] = Addressing Model
5753 // Ops[1] = Memory Model
5754 PrintOpcode(Inst);
5755 out << " ";
5756 PrintOperand(Ops[0]);
5757 out << " ";
5758 PrintOperand(Ops[1]);
5759 out << " ";
5760 PrintMemoryAccess(Ops[2]);
5761 out << " ";
5762 PrintOperand(Ops[3]);
5763 out << "\n";
5764 break;
5765 }
5766 case spv::OpExtension:
5767 case spv::OpControlBarrier:
5768 case spv::OpMemoryBarrier:
5769 case spv::OpBranch:
5770 case spv::OpBranchConditional:
5771 case spv::OpStore:
5772 case spv::OpImageWrite:
5773 case spv::OpReturnValue:
5774 case spv::OpReturn:
5775 case spv::OpFunctionEnd: {
5776 PrintOpcode(Inst);
5777 for (uint32_t i = 0; i < Ops.size(); i++) {
5778 out << " ";
5779 PrintOperand(Ops[i]);
5780 }
5781 out << "\n";
5782 break;
5783 }
5784 case spv::OpExtInstImport:
5785 case spv::OpTypeRuntimeArray:
5786 case spv::OpTypeStruct:
5787 case spv::OpTypeSampler:
5788 case spv::OpTypeSampledImage:
5789 case spv::OpTypeInt:
5790 case spv::OpTypeFloat:
5791 case spv::OpTypeArray:
5792 case spv::OpTypeVector:
5793 case spv::OpTypeBool:
5794 case spv::OpTypeVoid:
5795 case spv::OpTypeFunction:
5796 case spv::OpFunctionParameter:
5797 case spv::OpLabel:
5798 case spv::OpPhi:
5799 case spv::OpLoad:
5800 case spv::OpSelect:
5801 case spv::OpAccessChain:
5802 case spv::OpPtrAccessChain:
5803 case spv::OpInBoundsAccessChain:
5804 case spv::OpUConvert:
5805 case spv::OpSConvert:
5806 case spv::OpConvertFToU:
5807 case spv::OpConvertFToS:
5808 case spv::OpConvertUToF:
5809 case spv::OpConvertSToF:
5810 case spv::OpFConvert:
5811 case spv::OpConvertPtrToU:
5812 case spv::OpConvertUToPtr:
5813 case spv::OpBitcast:
5814 case spv::OpIAdd:
5815 case spv::OpFAdd:
5816 case spv::OpISub:
5817 case spv::OpFSub:
5818 case spv::OpIMul:
5819 case spv::OpFMul:
5820 case spv::OpUDiv:
5821 case spv::OpSDiv:
5822 case spv::OpFDiv:
5823 case spv::OpUMod:
5824 case spv::OpSRem:
5825 case spv::OpFRem:
5826 case spv::OpBitwiseOr:
5827 case spv::OpBitwiseXor:
5828 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005829 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005830 case spv::OpShiftLeftLogical:
5831 case spv::OpShiftRightLogical:
5832 case spv::OpShiftRightArithmetic:
5833 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005834 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005835 case spv::OpCompositeExtract:
5836 case spv::OpVectorExtractDynamic:
5837 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005838 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005839 case spv::OpVectorInsertDynamic:
5840 case spv::OpVectorShuffle:
5841 case spv::OpIEqual:
5842 case spv::OpINotEqual:
5843 case spv::OpUGreaterThan:
5844 case spv::OpUGreaterThanEqual:
5845 case spv::OpULessThan:
5846 case spv::OpULessThanEqual:
5847 case spv::OpSGreaterThan:
5848 case spv::OpSGreaterThanEqual:
5849 case spv::OpSLessThan:
5850 case spv::OpSLessThanEqual:
5851 case spv::OpFOrdEqual:
5852 case spv::OpFOrdGreaterThan:
5853 case spv::OpFOrdGreaterThanEqual:
5854 case spv::OpFOrdLessThan:
5855 case spv::OpFOrdLessThanEqual:
5856 case spv::OpFOrdNotEqual:
5857 case spv::OpFUnordEqual:
5858 case spv::OpFUnordGreaterThan:
5859 case spv::OpFUnordGreaterThanEqual:
5860 case spv::OpFUnordLessThan:
5861 case spv::OpFUnordLessThanEqual:
5862 case spv::OpFUnordNotEqual:
5863 case spv::OpSampledImage:
5864 case spv::OpFunctionCall:
5865 case spv::OpConstantTrue:
5866 case spv::OpConstantFalse:
5867 case spv::OpConstant:
5868 case spv::OpSpecConstant:
5869 case spv::OpConstantComposite:
5870 case spv::OpSpecConstantComposite:
5871 case spv::OpConstantNull:
5872 case spv::OpLogicalOr:
5873 case spv::OpLogicalAnd:
5874 case spv::OpLogicalNot:
5875 case spv::OpLogicalNotEqual:
5876 case spv::OpUndef:
5877 case spv::OpIsInf:
5878 case spv::OpIsNan:
5879 case spv::OpAny:
5880 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005881 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005882 case spv::OpAtomicIAdd:
5883 case spv::OpAtomicISub:
5884 case spv::OpAtomicExchange:
5885 case spv::OpAtomicIIncrement:
5886 case spv::OpAtomicIDecrement:
5887 case spv::OpAtomicCompareExchange:
5888 case spv::OpAtomicUMin:
5889 case spv::OpAtomicSMin:
5890 case spv::OpAtomicUMax:
5891 case spv::OpAtomicSMax:
5892 case spv::OpAtomicAnd:
5893 case spv::OpAtomicOr:
5894 case spv::OpAtomicXor:
5895 case spv::OpDot: {
5896 PrintResID(Inst);
5897 out << " = ";
5898 PrintOpcode(Inst);
5899 for (uint32_t i = 0; i < Ops.size(); i++) {
5900 out << " ";
5901 PrintOperand(Ops[i]);
5902 }
5903 out << "\n";
5904 break;
5905 }
5906 }
5907 }
5908}
5909
5910void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005911 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005912}
5913
5914void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5915 WriteOneWord(Inst->getResultID());
5916}
5917
5918void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5919 // High 16 bit : Word Count
5920 // Low 16 bit : Opcode
5921 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005922 const uint32_t count = Inst->getWordCount();
5923 if (count > 65535) {
5924 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5925 llvm_unreachable("Word count too high");
5926 }
David Neto22f144c2017-06-12 14:26:21 -04005927 Word |= Inst->getWordCount() << 16;
5928 WriteOneWord(Word);
5929}
5930
5931void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5932 SPIRVOperandType OpTy = Op->getType();
5933 switch (OpTy) {
5934 default: {
5935 llvm_unreachable("Unsupported SPIRV Operand Type???");
5936 break;
5937 }
5938 case SPIRVOperandType::NUMBERID: {
5939 WriteOneWord(Op->getNumID());
5940 break;
5941 }
5942 case SPIRVOperandType::LITERAL_STRING: {
5943 std::string Str = Op->getLiteralStr();
5944 const char *Data = Str.c_str();
5945 size_t WordSize = Str.size() / 4;
5946 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5947 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5948 }
5949
5950 uint32_t Remainder = Str.size() % 4;
5951 uint32_t LastWord = 0;
5952 if (Remainder) {
5953 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5954 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5955 }
5956 }
5957
5958 WriteOneWord(LastWord);
5959 break;
5960 }
5961 case SPIRVOperandType::LITERAL_INTEGER:
5962 case SPIRVOperandType::LITERAL_FLOAT: {
5963 auto LiteralNum = Op->getLiteralNum();
5964 // TODO: Handle LiteranNum carefully.
5965 for (auto Word : LiteralNum) {
5966 WriteOneWord(Word);
5967 }
5968 break;
5969 }
5970 }
5971}
5972
5973void SPIRVProducerPass::WriteSPIRVBinary() {
5974 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5975
5976 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005977 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005978 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5979
5980 switch (Opcode) {
5981 default: {
David Neto5c22a252018-03-15 16:07:41 -04005982 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005983 llvm_unreachable("Unsupported SPIRV instruction");
5984 break;
5985 }
5986 case spv::OpCapability:
5987 case spv::OpExtension:
5988 case spv::OpMemoryModel:
5989 case spv::OpEntryPoint:
5990 case spv::OpExecutionMode:
5991 case spv::OpSource:
5992 case spv::OpDecorate:
5993 case spv::OpMemberDecorate:
5994 case spv::OpBranch:
5995 case spv::OpBranchConditional:
5996 case spv::OpSelectionMerge:
5997 case spv::OpLoopMerge:
5998 case spv::OpStore:
5999 case spv::OpImageWrite:
6000 case spv::OpReturnValue:
6001 case spv::OpControlBarrier:
6002 case spv::OpMemoryBarrier:
6003 case spv::OpReturn:
6004 case spv::OpFunctionEnd:
6005 case spv::OpCopyMemory: {
6006 WriteWordCountAndOpcode(Inst);
6007 for (uint32_t i = 0; i < Ops.size(); i++) {
6008 WriteOperand(Ops[i]);
6009 }
6010 break;
6011 }
6012 case spv::OpTypeBool:
6013 case spv::OpTypeVoid:
6014 case spv::OpTypeSampler:
6015 case spv::OpLabel:
6016 case spv::OpExtInstImport:
6017 case spv::OpTypePointer:
6018 case spv::OpTypeRuntimeArray:
6019 case spv::OpTypeStruct:
6020 case spv::OpTypeImage:
6021 case spv::OpTypeSampledImage:
6022 case spv::OpTypeInt:
6023 case spv::OpTypeFloat:
6024 case spv::OpTypeArray:
6025 case spv::OpTypeVector:
6026 case spv::OpTypeFunction: {
6027 WriteWordCountAndOpcode(Inst);
6028 WriteResultID(Inst);
6029 for (uint32_t i = 0; i < Ops.size(); i++) {
6030 WriteOperand(Ops[i]);
6031 }
6032 break;
6033 }
6034 case spv::OpFunction:
6035 case spv::OpFunctionParameter:
6036 case spv::OpAccessChain:
6037 case spv::OpPtrAccessChain:
6038 case spv::OpInBoundsAccessChain:
6039 case spv::OpUConvert:
6040 case spv::OpSConvert:
6041 case spv::OpConvertFToU:
6042 case spv::OpConvertFToS:
6043 case spv::OpConvertUToF:
6044 case spv::OpConvertSToF:
6045 case spv::OpFConvert:
6046 case spv::OpConvertPtrToU:
6047 case spv::OpConvertUToPtr:
6048 case spv::OpBitcast:
6049 case spv::OpIAdd:
6050 case spv::OpFAdd:
6051 case spv::OpISub:
6052 case spv::OpFSub:
6053 case spv::OpIMul:
6054 case spv::OpFMul:
6055 case spv::OpUDiv:
6056 case spv::OpSDiv:
6057 case spv::OpFDiv:
6058 case spv::OpUMod:
6059 case spv::OpSRem:
6060 case spv::OpFRem:
6061 case spv::OpBitwiseOr:
6062 case spv::OpBitwiseXor:
6063 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006064 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006065 case spv::OpShiftLeftLogical:
6066 case spv::OpShiftRightLogical:
6067 case spv::OpShiftRightArithmetic:
6068 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006069 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006070 case spv::OpCompositeExtract:
6071 case spv::OpVectorExtractDynamic:
6072 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006073 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006074 case spv::OpVectorInsertDynamic:
6075 case spv::OpVectorShuffle:
6076 case spv::OpIEqual:
6077 case spv::OpINotEqual:
6078 case spv::OpUGreaterThan:
6079 case spv::OpUGreaterThanEqual:
6080 case spv::OpULessThan:
6081 case spv::OpULessThanEqual:
6082 case spv::OpSGreaterThan:
6083 case spv::OpSGreaterThanEqual:
6084 case spv::OpSLessThan:
6085 case spv::OpSLessThanEqual:
6086 case spv::OpFOrdEqual:
6087 case spv::OpFOrdGreaterThan:
6088 case spv::OpFOrdGreaterThanEqual:
6089 case spv::OpFOrdLessThan:
6090 case spv::OpFOrdLessThanEqual:
6091 case spv::OpFOrdNotEqual:
6092 case spv::OpFUnordEqual:
6093 case spv::OpFUnordGreaterThan:
6094 case spv::OpFUnordGreaterThanEqual:
6095 case spv::OpFUnordLessThan:
6096 case spv::OpFUnordLessThanEqual:
6097 case spv::OpFUnordNotEqual:
6098 case spv::OpExtInst:
6099 case spv::OpIsInf:
6100 case spv::OpIsNan:
6101 case spv::OpAny:
6102 case spv::OpAll:
6103 case spv::OpUndef:
6104 case spv::OpConstantNull:
6105 case spv::OpLogicalOr:
6106 case spv::OpLogicalAnd:
6107 case spv::OpLogicalNot:
6108 case spv::OpLogicalNotEqual:
6109 case spv::OpConstantComposite:
6110 case spv::OpSpecConstantComposite:
6111 case spv::OpConstantTrue:
6112 case spv::OpConstantFalse:
6113 case spv::OpConstant:
6114 case spv::OpSpecConstant:
6115 case spv::OpVariable:
6116 case spv::OpFunctionCall:
6117 case spv::OpSampledImage:
6118 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006119 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006120 case spv::OpSelect:
6121 case spv::OpPhi:
6122 case spv::OpLoad:
6123 case spv::OpAtomicIAdd:
6124 case spv::OpAtomicISub:
6125 case spv::OpAtomicExchange:
6126 case spv::OpAtomicIIncrement:
6127 case spv::OpAtomicIDecrement:
6128 case spv::OpAtomicCompareExchange:
6129 case spv::OpAtomicUMin:
6130 case spv::OpAtomicSMin:
6131 case spv::OpAtomicUMax:
6132 case spv::OpAtomicSMax:
6133 case spv::OpAtomicAnd:
6134 case spv::OpAtomicOr:
6135 case spv::OpAtomicXor:
6136 case spv::OpDot: {
6137 WriteWordCountAndOpcode(Inst);
6138 WriteOperand(Ops[0]);
6139 WriteResultID(Inst);
6140 for (uint32_t i = 1; i < Ops.size(); i++) {
6141 WriteOperand(Ops[i]);
6142 }
6143 break;
6144 }
6145 }
6146 }
6147}