blob: 853eeebeca2119804cb6f99d71979bbf78f6c42c [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) {
2922 // Gather the list of resources that are used by this function's arguments.
2923 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2924
2925 auto remap_arg_kind = [](StringRef argKind) {
2926 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2927 ? "pod_ubo"
2928 : argKind;
2929 };
2930
2931 auto *fty = F.getType()->getPointerElementType();
2932 auto *func_ty = dyn_cast<FunctionType>(fty);
2933
2934 // If we've clustereed POD arguments, then argument details are in metadata.
2935 // If an argument maps to a resource variable, then get descriptor set and
2936 // binding from the resoure variable. Other info comes from the metadata.
2937 const auto *arg_map = F.getMetadata("kernel_arg_map");
2938 if (arg_map) {
2939 for (const auto &arg : arg_map->operands()) {
2940 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
2941 assert(arg_node->getNumOperands() == 6);
2942 const auto name =
2943 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2944 const auto old_index =
2945 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2946 // Remapped argument index
2947 const auto new_index =
2948 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2949 const auto offset =
2950 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
2951 const auto argKind = remap_arg_kind(
2952 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2953 const auto spec_id =
2954 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2955 if (spec_id > 0) {
2956 // This was a pointer-to-local argument. It is not associated with a
2957 // resource variable.
2958 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2959 << ",argOrdinal," << old_index << ",argKind,"
2960 << argKind << ",arrayElemSize,"
2961 << DL.getTypeAllocSize(
2962 func_ty->getParamType(unsigned(new_index))
2963 ->getPointerElementType())
2964 << ",arrayNumElemSpecId," << spec_id << "\n";
2965 } else {
2966 auto *info = resource_var_at_index[new_index];
2967 assert(info);
2968 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2969 << ",argOrdinal," << old_index << ",descriptorSet,"
2970 << info->descriptor_set << ",binding," << info->binding
2971 << ",offset," << offset << ",argKind," << argKind
2972 << "\n";
2973 }
2974 }
2975 } else {
2976 // There is no argument map.
2977 // Take descriptor info from the resource variable calls.
2978 // Take argument name from the arguments list.
2979
2980 SmallVector<Argument *, 4> arguments;
2981 for (auto &arg : F.args()) {
2982 arguments.push_back(&arg);
2983 }
2984
2985 unsigned arg_index = 0;
2986 for (auto *info : resource_var_at_index) {
2987 if (info) {
2988 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2989 << arguments[arg_index]->getName() << ",argOrdinal,"
2990 << arg_index << ",descriptorSet,"
2991 << info->descriptor_set << ",binding," << info->binding
2992 << ",offset," << 0 << ",argKind,"
2993 << remap_arg_kind(
2994 clspv::GetArgKindName(info->arg_kind))
2995 << "\n";
2996 }
2997 arg_index++;
2998 }
2999 // Generate mappings for pointer-to-local arguments.
3000 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3001 Argument *arg = arguments[arg_index];
3002 auto where = LocalArgMap.find(arg);
3003 if (where != LocalArgMap.end()) {
3004 auto &local_arg_info = where->second;
3005 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3006 << arg->getName() << ",argOrdinal," << arg_index
3007 << ",argKind,"
3008 << "local"
3009 << ",arrayElemSize,"
3010 << DL.getTypeAllocSize(local_arg_info.elem_type)
3011 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3012 << "\n";
3013 }
3014 }
3015 }
3016}
3017
David Neto22f144c2017-06-12 14:26:21 -04003018void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003019 Module& M = *F.getParent();
3020 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003021 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3022 ValueMapType &VMap = getValueMap();
3023 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003024 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3025 auto &GlobalConstArgSet = getGlobalConstArgSet();
3026
3027 FunctionType *FTy = F.getFunctionType();
3028
3029 //
David Neto22f144c2017-06-12 14:26:21 -04003030 // Generate OPFunction.
3031 //
3032
3033 // FOps[0] : Result Type ID
3034 // FOps[1] : Function Control
3035 // FOps[2] : Function Type ID
3036 SPIRVOperandList FOps;
3037
3038 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003039 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003040
3041 // Check function attributes for SPIRV Function Control.
3042 uint32_t FuncControl = spv::FunctionControlMaskNone;
3043 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3044 FuncControl |= spv::FunctionControlInlineMask;
3045 }
3046 if (F.hasFnAttribute(Attribute::NoInline)) {
3047 FuncControl |= spv::FunctionControlDontInlineMask;
3048 }
3049 // TODO: Check llvm attribute for Function Control Pure.
3050 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3051 FuncControl |= spv::FunctionControlPureMask;
3052 }
3053 // TODO: Check llvm attribute for Function Control Const.
3054 if (F.hasFnAttribute(Attribute::ReadNone)) {
3055 FuncControl |= spv::FunctionControlConstMask;
3056 }
3057
David Neto257c3892018-04-11 13:19:45 -04003058 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003059
3060 uint32_t FTyID;
3061 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3062 SmallVector<Type *, 4> NewFuncParamTys;
3063 FunctionType *NewFTy =
3064 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3065 FTyID = lookupType(NewFTy);
3066 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003067 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003068 if (GlobalConstFuncTyMap.count(FTy)) {
3069 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3070 } else {
3071 FTyID = lookupType(FTy);
3072 }
3073 }
3074
David Neto257c3892018-04-11 13:19:45 -04003075 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003076
3077 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3078 EntryPoints.push_back(std::make_pair(&F, nextID));
3079 }
3080
3081 VMap[&F] = nextID;
3082
David Neto482550a2018-03-24 05:21:07 -07003083 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003084 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3085 }
David Neto22f144c2017-06-12 14:26:21 -04003086 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003087 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003088 SPIRVInstList.push_back(FuncInst);
3089
3090 //
3091 // Generate OpFunctionParameter for Normal function.
3092 //
3093
3094 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3095 // Iterate Argument for name instead of param type from function type.
3096 unsigned ArgIdx = 0;
3097 for (Argument &Arg : F.args()) {
3098 VMap[&Arg] = nextID;
3099
3100 // ParamOps[0] : Result Type ID
3101 SPIRVOperandList ParamOps;
3102
3103 // Find SPIRV instruction for parameter type.
3104 uint32_t ParamTyID = lookupType(Arg.getType());
3105 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3106 if (GlobalConstFuncTyMap.count(FTy)) {
3107 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3108 Type *EleTy = PTy->getPointerElementType();
3109 Type *ArgTy =
3110 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3111 ParamTyID = lookupType(ArgTy);
3112 GlobalConstArgSet.insert(&Arg);
3113 }
3114 }
3115 }
David Neto257c3892018-04-11 13:19:45 -04003116 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003117
3118 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003119 auto *ParamInst =
3120 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003121 SPIRVInstList.push_back(ParamInst);
3122
3123 ArgIdx++;
3124 }
3125 }
3126}
3127
David Neto5c22a252018-03-15 16:07:41 -04003128void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003129 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3130 EntryPointVecType &EntryPoints = getEntryPointVec();
3131 ValueMapType &VMap = getValueMap();
3132 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3133 uint32_t &ExtInstImportID = getOpExtInstImportID();
3134 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3135
3136 // Set up insert point.
3137 auto InsertPoint = SPIRVInstList.begin();
3138
3139 //
3140 // Generate OpCapability
3141 //
3142 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3143
3144 // Ops[0] = Capability
3145 SPIRVOperandList Ops;
3146
David Neto87846742018-04-11 17:36:22 -04003147 auto *CapInst =
3148 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003149 SPIRVInstList.insert(InsertPoint, CapInst);
3150
3151 for (Type *Ty : getTypeList()) {
3152 // Find the i16 type.
3153 if (Ty->isIntegerTy(16)) {
3154 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003155 SPIRVInstList.insert(InsertPoint,
3156 new SPIRVInstruction(spv::OpCapability,
3157 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003158 } else if (Ty->isIntegerTy(64)) {
3159 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003160 SPIRVInstList.insert(InsertPoint,
3161 new SPIRVInstruction(spv::OpCapability,
3162 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003163 } else if (Ty->isHalfTy()) {
3164 // Generate OpCapability for half type.
3165 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003166 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3167 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003168 } else if (Ty->isDoubleTy()) {
3169 // Generate OpCapability for double type.
3170 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003171 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3172 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003173 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3174 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003175 if (STy->getName().equals("opencl.image2d_wo_t") ||
3176 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003177 // Generate OpCapability for write only image type.
3178 SPIRVInstList.insert(
3179 InsertPoint,
3180 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003181 spv::OpCapability,
3182 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003183 }
3184 }
3185 }
3186 }
3187
David Neto5c22a252018-03-15 16:07:41 -04003188 { // OpCapability ImageQuery
3189 bool hasImageQuery = false;
3190 for (const char *imageQuery : {
3191 "_Z15get_image_width14ocl_image2d_ro",
3192 "_Z15get_image_width14ocl_image2d_wo",
3193 "_Z16get_image_height14ocl_image2d_ro",
3194 "_Z16get_image_height14ocl_image2d_wo",
3195 }) {
3196 if (module.getFunction(imageQuery)) {
3197 hasImageQuery = true;
3198 break;
3199 }
3200 }
3201 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003202 auto *ImageQueryCapInst = new SPIRVInstruction(
3203 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003204 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3205 }
3206 }
3207
David Neto22f144c2017-06-12 14:26:21 -04003208 if (hasVariablePointers()) {
3209 //
3210 // Generate OpCapability and OpExtension
3211 //
3212
3213 //
3214 // Generate OpCapability.
3215 //
3216 // Ops[0] = Capability
3217 //
3218 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003219 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003220
David Neto87846742018-04-11 17:36:22 -04003221 SPIRVInstList.insert(InsertPoint,
3222 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003223
3224 //
3225 // Generate OpExtension.
3226 //
3227 // Ops[0] = Name (Literal String)
3228 //
David Netoa772fd12017-08-04 14:17:33 -04003229 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3230 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003231
David Neto87846742018-04-11 17:36:22 -04003232 auto *ExtensionInst =
3233 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003234 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003235 }
David Neto22f144c2017-06-12 14:26:21 -04003236 }
3237
3238 if (ExtInstImportID) {
3239 ++InsertPoint;
3240 }
3241
3242 //
3243 // Generate OpMemoryModel
3244 //
3245 // Memory model for Vulkan will always be GLSL450.
3246
3247 // Ops[0] = Addressing Model
3248 // Ops[1] = Memory Model
3249 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003250 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003251
David Neto87846742018-04-11 17:36:22 -04003252 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003253 SPIRVInstList.insert(InsertPoint, MemModelInst);
3254
3255 //
3256 // Generate OpEntryPoint
3257 //
3258 for (auto EntryPoint : EntryPoints) {
3259 // Ops[0] = Execution Model
3260 // Ops[1] = EntryPoint ID
3261 // Ops[2] = Name (Literal String)
3262 // ...
3263 //
3264 // TODO: Do we need to consider Interface ID for forward references???
3265 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003266 const StringRef& name = EntryPoint.first->getName();
3267 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3268 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003269
David Neto22f144c2017-06-12 14:26:21 -04003270 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003271 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003272 }
3273
David Neto87846742018-04-11 17:36:22 -04003274 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003275 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3276 }
3277
3278 for (auto EntryPoint : EntryPoints) {
3279 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3280 ->getMetadata("reqd_work_group_size")) {
3281
3282 if (!BuiltinDimVec.empty()) {
3283 llvm_unreachable(
3284 "Kernels should have consistent work group size definition");
3285 }
3286
3287 //
3288 // Generate OpExecutionMode
3289 //
3290
3291 // Ops[0] = Entry Point ID
3292 // Ops[1] = Execution Mode
3293 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3294 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003295 Ops << MkId(EntryPoint.second)
3296 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003297
3298 uint32_t XDim = static_cast<uint32_t>(
3299 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3300 uint32_t YDim = static_cast<uint32_t>(
3301 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3302 uint32_t ZDim = static_cast<uint32_t>(
3303 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3304
David Neto257c3892018-04-11 13:19:45 -04003305 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003306
David Neto87846742018-04-11 17:36:22 -04003307 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003308 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3309 }
3310 }
3311
3312 //
3313 // Generate OpSource.
3314 //
3315 // Ops[0] = SourceLanguage ID
3316 // Ops[1] = Version (LiteralNum)
3317 //
3318 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003319 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003320
David Neto87846742018-04-11 17:36:22 -04003321 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003322 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3323
3324 if (!BuiltinDimVec.empty()) {
3325 //
3326 // Generate OpDecorates for x/y/z dimension.
3327 //
3328 // Ops[0] = Target ID
3329 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003330 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003331
3332 // X Dimension
3333 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003334 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003335 SPIRVInstList.insert(InsertPoint,
3336 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003337
3338 // Y Dimension
3339 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003340 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003341 SPIRVInstList.insert(InsertPoint,
3342 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003343
3344 // Z Dimension
3345 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003346 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003347 SPIRVInstList.insert(InsertPoint,
3348 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003349 }
3350}
3351
3352void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3353 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3354 ValueMapType &VMap = getValueMap();
David Neto862b7d82018-06-14 18:48:37 -04003355 LLVMContext &Context = F.getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04003356
David Neto862b7d82018-06-14 18:48:37 -04003357 // Do remaining instruction generation for kernel arguments.
3358 // If an argument maps to a module-scope resource variables (i.e. it has
3359 // a descriptor set and binding), then its code generation is already
3360 // handled by the logic to handle the ResourceVarInfo objects we
3361 // found earlier in the flow.
3362 //
3363 // All that remains is to generate the access chain instruction to get the
3364 // first element of each pointer-to-local argument.
David Neto22f144c2017-06-12 14:26:21 -04003365 for (Argument &Arg : F.args()) {
3366 if (Arg.use_empty()) {
3367 continue;
3368 }
3369
David Netoc6f3ab22018-04-06 18:02:31 -04003370 Type *ArgTy = Arg.getType();
3371 if (IsLocalPtr(ArgTy)) {
3372 // Generate OpAccessChain to point to the first element of the array.
3373 const LocalArgInfo &info = LocalArgMap[&Arg];
3374 VMap[&Arg] = info.first_elem_ptr_id;
3375
3376 SPIRVOperandList Ops;
3377 uint32_t zeroId = VMap[ConstantInt::get(Type::getInt32Ty(Context), 0)];
3378 Ops << MkId(lookupType(ArgTy)) << MkId(info.variable_id) << MkId(zeroId);
3379 SPIRVInstList.push_back(new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003380 spv::OpAccessChain, info.first_elem_ptr_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04003381
3382 continue;
3383 }
3384
David Neto862b7d82018-06-14 18:48:37 -04003385 errs() << "Old algorithm for resource vars for kernel args should be dead "
3386 "code.\n";
3387 assert(false && "Expected this to be dead code");
David Neto22f144c2017-06-12 14:26:21 -04003388 }
3389}
3390
David Netob6e2e062018-04-25 10:32:06 -04003391void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3392 // Work around a driver bug. Initializers on Private variables might not
3393 // work. So the start of the kernel should store the initializer value to the
3394 // variables. Yes, *every* entry point pays this cost if *any* entry point
3395 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3396 // of complexity vs. runtime, for a broken driver.
3397 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3398 if (WorkgroupSizeVarID) {
3399 assert(WorkgroupSizeValueID);
3400
3401 SPIRVOperandList Ops;
3402 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3403
3404 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3405 getSPIRVInstList().push_back(Inst);
3406 }
3407}
3408
David Neto22f144c2017-06-12 14:26:21 -04003409void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3410 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3411 ValueMapType &VMap = getValueMap();
3412
David Netob6e2e062018-04-25 10:32:06 -04003413 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003414
3415 for (BasicBlock &BB : F) {
3416 // Register BasicBlock to ValueMap.
3417 VMap[&BB] = nextID;
3418
3419 //
3420 // Generate OpLabel for Basic Block.
3421 //
3422 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003423 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003424 SPIRVInstList.push_back(Inst);
3425
David Neto6dcd4712017-06-23 11:06:47 -04003426 // OpVariable instructions must come first.
3427 for (Instruction &I : BB) {
3428 if (isa<AllocaInst>(I)) {
3429 GenerateInstruction(I);
3430 }
3431 }
3432
David Neto22f144c2017-06-12 14:26:21 -04003433 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003434 if (clspv::Option::HackInitializers()) {
3435 GenerateEntryPointInitialStores();
3436 }
David Neto22f144c2017-06-12 14:26:21 -04003437 GenerateInstForArg(F);
3438 }
3439
3440 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003441 if (!isa<AllocaInst>(I)) {
3442 GenerateInstruction(I);
3443 }
David Neto22f144c2017-06-12 14:26:21 -04003444 }
3445 }
3446}
3447
3448spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3449 const std::map<CmpInst::Predicate, spv::Op> Map = {
3450 {CmpInst::ICMP_EQ, spv::OpIEqual},
3451 {CmpInst::ICMP_NE, spv::OpINotEqual},
3452 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3453 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3454 {CmpInst::ICMP_ULT, spv::OpULessThan},
3455 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3456 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3457 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3458 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3459 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3460 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3461 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3462 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3463 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3464 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3465 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3466 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3467 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3468 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3469 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3470 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3471 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3472
3473 assert(0 != Map.count(I->getPredicate()));
3474
3475 return Map.at(I->getPredicate());
3476}
3477
3478spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3479 const std::map<unsigned, spv::Op> Map{
3480 {Instruction::Trunc, spv::OpUConvert},
3481 {Instruction::ZExt, spv::OpUConvert},
3482 {Instruction::SExt, spv::OpSConvert},
3483 {Instruction::FPToUI, spv::OpConvertFToU},
3484 {Instruction::FPToSI, spv::OpConvertFToS},
3485 {Instruction::UIToFP, spv::OpConvertUToF},
3486 {Instruction::SIToFP, spv::OpConvertSToF},
3487 {Instruction::FPTrunc, spv::OpFConvert},
3488 {Instruction::FPExt, spv::OpFConvert},
3489 {Instruction::BitCast, spv::OpBitcast}};
3490
3491 assert(0 != Map.count(I.getOpcode()));
3492
3493 return Map.at(I.getOpcode());
3494}
3495
3496spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3497 if (I.getType()->isIntegerTy(1)) {
3498 switch (I.getOpcode()) {
3499 default:
3500 break;
3501 case Instruction::Or:
3502 return spv::OpLogicalOr;
3503 case Instruction::And:
3504 return spv::OpLogicalAnd;
3505 case Instruction::Xor:
3506 return spv::OpLogicalNotEqual;
3507 }
3508 }
3509
3510 const std::map<unsigned, spv::Op> Map {
3511 {Instruction::Add, spv::OpIAdd},
3512 {Instruction::FAdd, spv::OpFAdd},
3513 {Instruction::Sub, spv::OpISub},
3514 {Instruction::FSub, spv::OpFSub},
3515 {Instruction::Mul, spv::OpIMul},
3516 {Instruction::FMul, spv::OpFMul},
3517 {Instruction::UDiv, spv::OpUDiv},
3518 {Instruction::SDiv, spv::OpSDiv},
3519 {Instruction::FDiv, spv::OpFDiv},
3520 {Instruction::URem, spv::OpUMod},
3521 {Instruction::SRem, spv::OpSRem},
3522 {Instruction::FRem, spv::OpFRem},
3523 {Instruction::Or, spv::OpBitwiseOr},
3524 {Instruction::Xor, spv::OpBitwiseXor},
3525 {Instruction::And, spv::OpBitwiseAnd},
3526 {Instruction::Shl, spv::OpShiftLeftLogical},
3527 {Instruction::LShr, spv::OpShiftRightLogical},
3528 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3529
3530 assert(0 != Map.count(I.getOpcode()));
3531
3532 return Map.at(I.getOpcode());
3533}
3534
3535void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3536 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3537 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003538 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3539 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3540
3541 // Register Instruction to ValueMap.
3542 if (0 == VMap[&I]) {
3543 VMap[&I] = nextID;
3544 }
3545
3546 switch (I.getOpcode()) {
3547 default: {
3548 if (Instruction::isCast(I.getOpcode())) {
3549 //
3550 // Generate SPIRV instructions for cast operators.
3551 //
3552
David Netod2de94a2017-08-28 17:27:47 -04003553
3554 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003555 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003556 auto toI8 = Ty == Type::getInt8Ty(Context);
3557 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003558 // Handle zext, sext and uitofp with i1 type specially.
3559 if ((I.getOpcode() == Instruction::ZExt ||
3560 I.getOpcode() == Instruction::SExt ||
3561 I.getOpcode() == Instruction::UIToFP) &&
3562 (OpTy->isIntegerTy(1) ||
3563 (OpTy->isVectorTy() &&
3564 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3565 //
3566 // Generate OpSelect.
3567 //
3568
3569 // Ops[0] = Result Type ID
3570 // Ops[1] = Condition ID
3571 // Ops[2] = True Constant ID
3572 // Ops[3] = False Constant ID
3573 SPIRVOperandList Ops;
3574
David Neto257c3892018-04-11 13:19:45 -04003575 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003576
David Neto22f144c2017-06-12 14:26:21 -04003577 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003578 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003579
3580 uint32_t TrueID = 0;
3581 if (I.getOpcode() == Instruction::ZExt) {
3582 APInt One(32, 1);
3583 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3584 } else if (I.getOpcode() == Instruction::SExt) {
3585 APInt MinusOne(32, UINT64_MAX, true);
3586 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3587 } else {
3588 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3589 }
David Neto257c3892018-04-11 13:19:45 -04003590 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003591
3592 uint32_t FalseID = 0;
3593 if (I.getOpcode() == Instruction::ZExt) {
3594 FalseID = VMap[Constant::getNullValue(I.getType())];
3595 } else if (I.getOpcode() == Instruction::SExt) {
3596 FalseID = VMap[Constant::getNullValue(I.getType())];
3597 } else {
3598 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3599 }
David Neto257c3892018-04-11 13:19:45 -04003600 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003601
David Neto87846742018-04-11 17:36:22 -04003602 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003603 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003604 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3605 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3606 // 8 bits.
3607 // Before:
3608 // %result = trunc i32 %a to i8
3609 // After
3610 // %result = OpBitwiseAnd %uint %a %uint_255
3611
3612 SPIRVOperandList Ops;
3613
David Neto257c3892018-04-11 13:19:45 -04003614 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003615
3616 Type *UintTy = Type::getInt32Ty(Context);
3617 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003618 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003619
David Neto87846742018-04-11 17:36:22 -04003620 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003621 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003622 } else {
3623 // Ops[0] = Result Type ID
3624 // Ops[1] = Source Value ID
3625 SPIRVOperandList Ops;
3626
David Neto257c3892018-04-11 13:19:45 -04003627 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003628
David Neto87846742018-04-11 17:36:22 -04003629 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003630 SPIRVInstList.push_back(Inst);
3631 }
3632 } else if (isa<BinaryOperator>(I)) {
3633 //
3634 // Generate SPIRV instructions for binary operators.
3635 //
3636
3637 // Handle xor with i1 type specially.
3638 if (I.getOpcode() == Instruction::Xor &&
3639 I.getType() == Type::getInt1Ty(Context) &&
3640 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3641 //
3642 // Generate OpLogicalNot.
3643 //
3644 // Ops[0] = Result Type ID
3645 // Ops[1] = Operand
3646 SPIRVOperandList Ops;
3647
David Neto257c3892018-04-11 13:19:45 -04003648 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003649
3650 Value *CondV = I.getOperand(0);
3651 if (isa<Constant>(I.getOperand(0))) {
3652 CondV = I.getOperand(1);
3653 }
David Neto257c3892018-04-11 13:19:45 -04003654 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003655
David Neto87846742018-04-11 17:36:22 -04003656 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003657 SPIRVInstList.push_back(Inst);
3658 } else {
3659 // Ops[0] = Result Type ID
3660 // Ops[1] = Operand 0
3661 // Ops[2] = Operand 1
3662 SPIRVOperandList Ops;
3663
David Neto257c3892018-04-11 13:19:45 -04003664 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3665 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003666
David Neto87846742018-04-11 17:36:22 -04003667 auto *Inst =
3668 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003669 SPIRVInstList.push_back(Inst);
3670 }
3671 } else {
3672 I.print(errs());
3673 llvm_unreachable("Unsupported instruction???");
3674 }
3675 break;
3676 }
3677 case Instruction::GetElementPtr: {
3678 auto &GlobalConstArgSet = getGlobalConstArgSet();
3679
3680 //
3681 // Generate OpAccessChain.
3682 //
3683 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3684
3685 //
3686 // Generate OpAccessChain.
3687 //
3688
3689 // Ops[0] = Result Type ID
3690 // Ops[1] = Base ID
3691 // Ops[2] ... Ops[n] = Indexes ID
3692 SPIRVOperandList Ops;
3693
David Neto1a1a0582017-07-07 12:01:44 -04003694 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003695 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3696 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3697 // Use pointer type with private address space for global constant.
3698 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003699 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003700 }
David Neto257c3892018-04-11 13:19:45 -04003701
3702 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003703
David Neto862b7d82018-06-14 18:48:37 -04003704 // Generate the base pointer.
3705 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003706
David Neto862b7d82018-06-14 18:48:37 -04003707 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003708
3709 //
3710 // Follows below rules for gep.
3711 //
David Neto862b7d82018-06-14 18:48:37 -04003712 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3713 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003714 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3715 // first index.
3716 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3717 // use gep's first index.
3718 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3719 // gep's first index.
3720 //
3721 spv::Op Opcode = spv::OpAccessChain;
3722 unsigned offset = 0;
3723 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003724 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003725 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003726 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003727 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003728 }
David Neto862b7d82018-06-14 18:48:37 -04003729 } else {
David Neto22f144c2017-06-12 14:26:21 -04003730 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003731 }
3732
3733 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003734 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003735 // Do we need to generate ArrayStride? Check against the GEP result type
3736 // rather than the pointer type of the base because when indexing into
3737 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3738 // for something else in the SPIR-V.
3739 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3740 if (GetStorageClass(ResultType->getAddressSpace()) ==
3741 spv::StorageClassStorageBuffer) {
3742 // Save the need to generate an ArrayStride decoration. But defer
3743 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003744 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003745 }
David Neto22f144c2017-06-12 14:26:21 -04003746 }
3747
3748 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003749 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003750 }
3751
David Neto87846742018-04-11 17:36:22 -04003752 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003753 SPIRVInstList.push_back(Inst);
3754 break;
3755 }
3756 case Instruction::ExtractValue: {
3757 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3758 // Ops[0] = Result Type ID
3759 // Ops[1] = Composite ID
3760 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3761 SPIRVOperandList Ops;
3762
David Neto257c3892018-04-11 13:19:45 -04003763 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003764
3765 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003767
3768 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003769 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003770 }
3771
David Neto87846742018-04-11 17:36:22 -04003772 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003773 SPIRVInstList.push_back(Inst);
3774 break;
3775 }
3776 case Instruction::InsertValue: {
3777 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3778 // Ops[0] = Result Type ID
3779 // Ops[1] = Object ID
3780 // Ops[2] = Composite ID
3781 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3782 SPIRVOperandList Ops;
3783
3784 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003785 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003786
3787 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003788 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003789
3790 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003791 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003792
3793 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003794 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003795 }
3796
David Neto87846742018-04-11 17:36:22 -04003797 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003798 SPIRVInstList.push_back(Inst);
3799 break;
3800 }
3801 case Instruction::Select: {
3802 //
3803 // Generate OpSelect.
3804 //
3805
3806 // Ops[0] = Result Type ID
3807 // Ops[1] = Condition ID
3808 // Ops[2] = True Constant ID
3809 // Ops[3] = False Constant ID
3810 SPIRVOperandList Ops;
3811
3812 // Find SPIRV instruction for parameter type.
3813 auto Ty = I.getType();
3814 if (Ty->isPointerTy()) {
3815 auto PointeeTy = Ty->getPointerElementType();
3816 if (PointeeTy->isStructTy() &&
3817 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3818 Ty = PointeeTy;
3819 }
3820 }
3821
David Neto257c3892018-04-11 13:19:45 -04003822 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3823 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003824
David Neto87846742018-04-11 17:36:22 -04003825 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003826 SPIRVInstList.push_back(Inst);
3827 break;
3828 }
3829 case Instruction::ExtractElement: {
3830 // Handle <4 x i8> type manually.
3831 Type *CompositeTy = I.getOperand(0)->getType();
3832 if (is4xi8vec(CompositeTy)) {
3833 //
3834 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3835 // <4 x i8>.
3836 //
3837
3838 //
3839 // Generate OpShiftRightLogical
3840 //
3841 // Ops[0] = Result Type ID
3842 // Ops[1] = Operand 0
3843 // Ops[2] = Operand 1
3844 //
3845 SPIRVOperandList Ops;
3846
David Neto257c3892018-04-11 13:19:45 -04003847 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003848
3849 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003850 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003851
3852 uint32_t Op1ID = 0;
3853 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3854 // Handle constant index.
3855 uint64_t Idx = CI->getZExtValue();
3856 Value *ShiftAmount =
3857 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3858 Op1ID = VMap[ShiftAmount];
3859 } else {
3860 // Handle variable index.
3861 SPIRVOperandList TmpOps;
3862
David Neto257c3892018-04-11 13:19:45 -04003863 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3864 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003865
3866 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003867 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003868
3869 Op1ID = nextID;
3870
David Neto87846742018-04-11 17:36:22 -04003871 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003872 SPIRVInstList.push_back(TmpInst);
3873 }
David Neto257c3892018-04-11 13:19:45 -04003874 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003875
3876 uint32_t ShiftID = nextID;
3877
David Neto87846742018-04-11 17:36:22 -04003878 auto *Inst =
3879 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003880 SPIRVInstList.push_back(Inst);
3881
3882 //
3883 // Generate OpBitwiseAnd
3884 //
3885 // Ops[0] = Result Type ID
3886 // Ops[1] = Operand 0
3887 // Ops[2] = Operand 1
3888 //
3889 Ops.clear();
3890
David Neto257c3892018-04-11 13:19:45 -04003891 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003892
3893 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003894 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003895
David Neto9b2d6252017-09-06 15:47:37 -04003896 // Reset mapping for this value to the result of the bitwise and.
3897 VMap[&I] = nextID;
3898
David Neto87846742018-04-11 17:36:22 -04003899 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003900 SPIRVInstList.push_back(Inst);
3901 break;
3902 }
3903
3904 // Ops[0] = Result Type ID
3905 // Ops[1] = Composite ID
3906 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3907 SPIRVOperandList Ops;
3908
David Neto257c3892018-04-11 13:19:45 -04003909 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003910
3911 spv::Op Opcode = spv::OpCompositeExtract;
3912 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003913 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003914 } else {
David Neto257c3892018-04-11 13:19:45 -04003915 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003916 Opcode = spv::OpVectorExtractDynamic;
3917 }
3918
David Neto87846742018-04-11 17:36:22 -04003919 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003920 SPIRVInstList.push_back(Inst);
3921 break;
3922 }
3923 case Instruction::InsertElement: {
3924 // Handle <4 x i8> type manually.
3925 Type *CompositeTy = I.getOperand(0)->getType();
3926 if (is4xi8vec(CompositeTy)) {
3927 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3928 uint32_t CstFFID = VMap[CstFF];
3929
3930 uint32_t ShiftAmountID = 0;
3931 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3932 // Handle constant index.
3933 uint64_t Idx = CI->getZExtValue();
3934 Value *ShiftAmount =
3935 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3936 ShiftAmountID = VMap[ShiftAmount];
3937 } else {
3938 // Handle variable index.
3939 SPIRVOperandList TmpOps;
3940
David Neto257c3892018-04-11 13:19:45 -04003941 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3942 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003943
3944 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003945 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003946
3947 ShiftAmountID = nextID;
3948
David Neto87846742018-04-11 17:36:22 -04003949 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003950 SPIRVInstList.push_back(TmpInst);
3951 }
3952
3953 //
3954 // Generate mask operations.
3955 //
3956
3957 // ShiftLeft mask according to index of insertelement.
3958 SPIRVOperandList Ops;
3959
David Neto257c3892018-04-11 13:19:45 -04003960 const uint32_t ResTyID = lookupType(CompositeTy);
3961 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003962
3963 uint32_t MaskID = nextID;
3964
David Neto87846742018-04-11 17:36:22 -04003965 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003966 SPIRVInstList.push_back(Inst);
3967
3968 // Inverse mask.
3969 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003970 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003971
3972 uint32_t InvMaskID = nextID;
3973
David Neto87846742018-04-11 17:36:22 -04003974 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003975 SPIRVInstList.push_back(Inst);
3976
3977 // Apply mask.
3978 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003979 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04003980
3981 uint32_t OrgValID = nextID;
3982
David Neto87846742018-04-11 17:36:22 -04003983 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003984 SPIRVInstList.push_back(Inst);
3985
3986 // Create correct value according to index of insertelement.
3987 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003988 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003989
3990 uint32_t InsertValID = nextID;
3991
David Neto87846742018-04-11 17:36:22 -04003992 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003993 SPIRVInstList.push_back(Inst);
3994
3995 // Insert value to original value.
3996 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003997 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04003998
David Netoa394f392017-08-26 20:45:29 -04003999 VMap[&I] = nextID;
4000
David Neto87846742018-04-11 17:36:22 -04004001 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004002 SPIRVInstList.push_back(Inst);
4003
4004 break;
4005 }
4006
David Neto22f144c2017-06-12 14:26:21 -04004007 SPIRVOperandList Ops;
4008
James Priced26efea2018-06-09 23:28:32 +01004009 // Ops[0] = Result Type ID
4010 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004011
4012 spv::Op Opcode = spv::OpCompositeInsert;
4013 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004014 const auto value = CI->getZExtValue();
4015 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004016 // Ops[1] = Object ID
4017 // Ops[2] = Composite ID
4018 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4019 Ops << MkId(VMap[I.getOperand(1)])
4020 << MkId(VMap[I.getOperand(0)])
4021 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004022 } else {
James Priced26efea2018-06-09 23:28:32 +01004023 // Ops[1] = Composite ID
4024 // Ops[2] = Object ID
4025 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4026 Ops << MkId(VMap[I.getOperand(0)])
4027 << MkId(VMap[I.getOperand(1)])
4028 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004029 Opcode = spv::OpVectorInsertDynamic;
4030 }
4031
David Neto87846742018-04-11 17:36:22 -04004032 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004033 SPIRVInstList.push_back(Inst);
4034 break;
4035 }
4036 case Instruction::ShuffleVector: {
4037 // Ops[0] = Result Type ID
4038 // Ops[1] = Vector 1 ID
4039 // Ops[2] = Vector 2 ID
4040 // Ops[3] ... Ops[n] = Components (Literal Number)
4041 SPIRVOperandList Ops;
4042
David Neto257c3892018-04-11 13:19:45 -04004043 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4044 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004045
4046 uint64_t NumElements = 0;
4047 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4048 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4049
4050 if (Cst->isNullValue()) {
4051 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004052 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004053 }
4054 } else if (const ConstantDataSequential *CDS =
4055 dyn_cast<ConstantDataSequential>(Cst)) {
4056 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4057 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004058 const auto value = CDS->getElementAsInteger(i);
4059 assert(value <= UINT32_MAX);
4060 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004061 }
4062 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4063 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4064 auto Op = CV->getOperand(i);
4065
4066 uint32_t literal = 0;
4067
4068 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4069 literal = static_cast<uint32_t>(CI->getZExtValue());
4070 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4071 literal = 0xFFFFFFFFu;
4072 } else {
4073 Op->print(errs());
4074 llvm_unreachable("Unsupported element in ConstantVector!");
4075 }
4076
David Neto257c3892018-04-11 13:19:45 -04004077 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004078 }
4079 } else {
4080 Cst->print(errs());
4081 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4082 }
4083 }
4084
David Neto87846742018-04-11 17:36:22 -04004085 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004086 SPIRVInstList.push_back(Inst);
4087 break;
4088 }
4089 case Instruction::ICmp:
4090 case Instruction::FCmp: {
4091 CmpInst *CmpI = cast<CmpInst>(&I);
4092
David Netod4ca2e62017-07-06 18:47:35 -04004093 // Pointer equality is invalid.
4094 Type* ArgTy = CmpI->getOperand(0)->getType();
4095 if (isa<PointerType>(ArgTy)) {
4096 CmpI->print(errs());
4097 std::string name = I.getParent()->getParent()->getName();
4098 errs()
4099 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4100 << "in function " << name << "\n";
4101 llvm_unreachable("Pointer equality check is invalid");
4102 break;
4103 }
4104
David Neto257c3892018-04-11 13:19:45 -04004105 // Ops[0] = Result Type ID
4106 // Ops[1] = Operand 1 ID
4107 // Ops[2] = Operand 2 ID
4108 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004109
David Neto257c3892018-04-11 13:19:45 -04004110 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4111 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004112
4113 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004114 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004115 SPIRVInstList.push_back(Inst);
4116 break;
4117 }
4118 case Instruction::Br: {
4119 // Branch instrucion is deferred because it needs label's ID. Record slot's
4120 // location on SPIRVInstructionList.
4121 DeferredInsts.push_back(
4122 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4123 break;
4124 }
4125 case Instruction::Switch: {
4126 I.print(errs());
4127 llvm_unreachable("Unsupported instruction???");
4128 break;
4129 }
4130 case Instruction::IndirectBr: {
4131 I.print(errs());
4132 llvm_unreachable("Unsupported instruction???");
4133 break;
4134 }
4135 case Instruction::PHI: {
4136 // Branch instrucion is deferred because it needs label's ID. Record slot's
4137 // location on SPIRVInstructionList.
4138 DeferredInsts.push_back(
4139 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4140 break;
4141 }
4142 case Instruction::Alloca: {
4143 //
4144 // Generate OpVariable.
4145 //
4146 // Ops[0] : Result Type ID
4147 // Ops[1] : Storage Class
4148 SPIRVOperandList Ops;
4149
David Neto257c3892018-04-11 13:19:45 -04004150 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004151
David Neto87846742018-04-11 17:36:22 -04004152 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004153 SPIRVInstList.push_back(Inst);
4154 break;
4155 }
4156 case Instruction::Load: {
4157 LoadInst *LD = cast<LoadInst>(&I);
4158 //
4159 // Generate OpLoad.
4160 //
4161
David Neto0a2f98d2017-09-15 19:38:40 -04004162 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004163 uint32_t PointerID = VMap[LD->getPointerOperand()];
4164
4165 // This is a hack to work around what looks like a driver bug.
4166 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004167 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4168 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004169 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004170 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004171 // Generate a bitwise-and of the original value with itself.
4172 // We should have been able to get away with just an OpCopyObject,
4173 // but we need something more complex to get past certain driver bugs.
4174 // This is ridiculous, but necessary.
4175 // TODO(dneto): Revisit this once drivers fix their bugs.
4176
4177 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004178 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4179 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004180
David Neto87846742018-04-11 17:36:22 -04004181 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004182 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004183 break;
4184 }
4185
4186 // This is the normal path. Generate a load.
4187
David Neto22f144c2017-06-12 14:26:21 -04004188 // Ops[0] = Result Type ID
4189 // Ops[1] = Pointer ID
4190 // Ops[2] ... Ops[n] = Optional Memory Access
4191 //
4192 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004193
David Neto22f144c2017-06-12 14:26:21 -04004194 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004195 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004196
David Neto87846742018-04-11 17:36:22 -04004197 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004198 SPIRVInstList.push_back(Inst);
4199 break;
4200 }
4201 case Instruction::Store: {
4202 StoreInst *ST = cast<StoreInst>(&I);
4203 //
4204 // Generate OpStore.
4205 //
4206
4207 // Ops[0] = Pointer ID
4208 // Ops[1] = Object ID
4209 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4210 //
4211 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004212 SPIRVOperandList Ops;
4213 Ops << MkId(VMap[ST->getPointerOperand()])
4214 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004215
David Neto87846742018-04-11 17:36:22 -04004216 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004217 SPIRVInstList.push_back(Inst);
4218 break;
4219 }
4220 case Instruction::AtomicCmpXchg: {
4221 I.print(errs());
4222 llvm_unreachable("Unsupported instruction???");
4223 break;
4224 }
4225 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004226 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4227
4228 spv::Op opcode;
4229
4230 switch (AtomicRMW->getOperation()) {
4231 default:
4232 I.print(errs());
4233 llvm_unreachable("Unsupported instruction???");
4234 case llvm::AtomicRMWInst::Add:
4235 opcode = spv::OpAtomicIAdd;
4236 break;
4237 case llvm::AtomicRMWInst::Sub:
4238 opcode = spv::OpAtomicISub;
4239 break;
4240 case llvm::AtomicRMWInst::Xchg:
4241 opcode = spv::OpAtomicExchange;
4242 break;
4243 case llvm::AtomicRMWInst::Min:
4244 opcode = spv::OpAtomicSMin;
4245 break;
4246 case llvm::AtomicRMWInst::Max:
4247 opcode = spv::OpAtomicSMax;
4248 break;
4249 case llvm::AtomicRMWInst::UMin:
4250 opcode = spv::OpAtomicUMin;
4251 break;
4252 case llvm::AtomicRMWInst::UMax:
4253 opcode = spv::OpAtomicUMax;
4254 break;
4255 case llvm::AtomicRMWInst::And:
4256 opcode = spv::OpAtomicAnd;
4257 break;
4258 case llvm::AtomicRMWInst::Or:
4259 opcode = spv::OpAtomicOr;
4260 break;
4261 case llvm::AtomicRMWInst::Xor:
4262 opcode = spv::OpAtomicXor;
4263 break;
4264 }
4265
4266 //
4267 // Generate OpAtomic*.
4268 //
4269 SPIRVOperandList Ops;
4270
David Neto257c3892018-04-11 13:19:45 -04004271 Ops << MkId(lookupType(I.getType()))
4272 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004273
4274 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004275 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004276 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004277
4278 const auto ConstantMemorySemantics = ConstantInt::get(
4279 IntTy, spv::MemorySemanticsUniformMemoryMask |
4280 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004281 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004282
David Neto257c3892018-04-11 13:19:45 -04004283 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004284
4285 VMap[&I] = nextID;
4286
David Neto87846742018-04-11 17:36:22 -04004287 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004288 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004289 break;
4290 }
4291 case Instruction::Fence: {
4292 I.print(errs());
4293 llvm_unreachable("Unsupported instruction???");
4294 break;
4295 }
4296 case Instruction::Call: {
4297 CallInst *Call = dyn_cast<CallInst>(&I);
4298 Function *Callee = Call->getCalledFunction();
4299
David Neto862b7d82018-06-14 18:48:37 -04004300 if (Callee->getName().startswith("clspv.resource.var.")) {
4301 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4302 // Generate an OpLoad
4303 SPIRVOperandList Ops;
4304 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004305
David Neto862b7d82018-06-14 18:48:37 -04004306 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4307 << MkId(ResourceVarDeferredLoadCalls[Call]);
4308
4309 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4310 SPIRVInstList.push_back(Inst);
4311 VMap[Call] = load_id;
4312 break;
4313
4314 } else {
4315 // This maps to an OpVariable we've already generated.
4316 // No code is generated for the call.
4317 }
4318 break;
4319 }
4320
4321 // Sampler initializers become a load of the corresponding sampler.
4322
4323 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4324 // Map this to a load from the variable.
4325 const auto index_into_sampler_map =
4326 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4327
4328 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004329 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004330 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004331
David Neto257c3892018-04-11 13:19:45 -04004332 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004333 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004334
David Neto862b7d82018-06-14 18:48:37 -04004335 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004336 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004337 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004338 break;
4339 }
4340
4341 if (Callee->getName().startswith("spirv.atomic")) {
4342 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4343 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4344 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4345 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4346 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4347 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4348 .Case("spirv.atomic_compare_exchange",
4349 spv::OpAtomicCompareExchange)
4350 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4351 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4352 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4353 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4354 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4355 .Case("spirv.atomic_or", spv::OpAtomicOr)
4356 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4357 .Default(spv::OpNop);
4358
4359 //
4360 // Generate OpAtomic*.
4361 //
4362 SPIRVOperandList Ops;
4363
David Neto257c3892018-04-11 13:19:45 -04004364 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004365
4366 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004367 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004368 }
4369
4370 VMap[&I] = nextID;
4371
David Neto87846742018-04-11 17:36:22 -04004372 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004373 SPIRVInstList.push_back(Inst);
4374 break;
4375 }
4376
4377 if (Callee->getName().startswith("_Z3dot")) {
4378 // If the argument is a vector type, generate OpDot
4379 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4380 //
4381 // Generate OpDot.
4382 //
4383 SPIRVOperandList Ops;
4384
David Neto257c3892018-04-11 13:19:45 -04004385 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004386
4387 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004388 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004389 }
4390
4391 VMap[&I] = nextID;
4392
David Neto87846742018-04-11 17:36:22 -04004393 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004394 SPIRVInstList.push_back(Inst);
4395 } else {
4396 //
4397 // Generate OpFMul.
4398 //
4399 SPIRVOperandList Ops;
4400
David Neto257c3892018-04-11 13:19:45 -04004401 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004402
4403 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004404 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004405 }
4406
4407 VMap[&I] = nextID;
4408
David Neto87846742018-04-11 17:36:22 -04004409 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004410 SPIRVInstList.push_back(Inst);
4411 }
4412 break;
4413 }
4414
David Neto8505ebf2017-10-13 18:50:50 -04004415 if (Callee->getName().startswith("_Z4fmod")) {
4416 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4417 // The sign for a non-zero result is taken from x.
4418 // (Try an example.)
4419 // So translate to OpFRem
4420
4421 SPIRVOperandList Ops;
4422
David Neto257c3892018-04-11 13:19:45 -04004423 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004424
4425 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004426 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004427 }
4428
4429 VMap[&I] = nextID;
4430
David Neto87846742018-04-11 17:36:22 -04004431 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004432 SPIRVInstList.push_back(Inst);
4433 break;
4434 }
4435
David Neto22f144c2017-06-12 14:26:21 -04004436 // spirv.store_null.* intrinsics become OpStore's.
4437 if (Callee->getName().startswith("spirv.store_null")) {
4438 //
4439 // Generate OpStore.
4440 //
4441
4442 // Ops[0] = Pointer ID
4443 // Ops[1] = Object ID
4444 // Ops[2] ... Ops[n]
4445 SPIRVOperandList Ops;
4446
4447 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004448 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004449 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004450
David Neto87846742018-04-11 17:36:22 -04004451 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004452
4453 break;
4454 }
4455
4456 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4457 if (Callee->getName().startswith("spirv.copy_memory")) {
4458 //
4459 // Generate OpCopyMemory.
4460 //
4461
4462 // Ops[0] = Dst ID
4463 // Ops[1] = Src ID
4464 // Ops[2] = Memory Access
4465 // Ops[3] = Alignment
4466
4467 auto IsVolatile =
4468 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4469
4470 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4471 : spv::MemoryAccessMaskNone;
4472
4473 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4474
4475 auto Alignment =
4476 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4477
David Neto257c3892018-04-11 13:19:45 -04004478 SPIRVOperandList Ops;
4479 Ops << MkId(VMap[Call->getArgOperand(0)])
4480 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4481 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004482
David Neto87846742018-04-11 17:36:22 -04004483 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004484
4485 SPIRVInstList.push_back(Inst);
4486
4487 break;
4488 }
4489
4490 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4491 // with unit.
4492 if (Callee->getName().equals("_Z3absj") ||
4493 Callee->getName().equals("_Z3absDv2_j") ||
4494 Callee->getName().equals("_Z3absDv3_j") ||
4495 Callee->getName().equals("_Z3absDv4_j")) {
4496 VMap[&I] = VMap[Call->getOperand(0)];
4497 break;
4498 }
4499
4500 // barrier is converted to OpControlBarrier
4501 if (Callee->getName().equals("__spirv_control_barrier")) {
4502 //
4503 // Generate OpControlBarrier.
4504 //
4505 // Ops[0] = Execution Scope ID
4506 // Ops[1] = Memory Scope ID
4507 // Ops[2] = Memory Semantics ID
4508 //
4509 Value *ExecutionScope = Call->getArgOperand(0);
4510 Value *MemoryScope = Call->getArgOperand(1);
4511 Value *MemorySemantics = Call->getArgOperand(2);
4512
David Neto257c3892018-04-11 13:19:45 -04004513 SPIRVOperandList Ops;
4514 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4515 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004516
David Neto87846742018-04-11 17:36:22 -04004517 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004518 break;
4519 }
4520
4521 // memory barrier is converted to OpMemoryBarrier
4522 if (Callee->getName().equals("__spirv_memory_barrier")) {
4523 //
4524 // Generate OpMemoryBarrier.
4525 //
4526 // Ops[0] = Memory Scope ID
4527 // Ops[1] = Memory Semantics ID
4528 //
4529 SPIRVOperandList Ops;
4530
David Neto257c3892018-04-11 13:19:45 -04004531 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4532 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004533
David Neto257c3892018-04-11 13:19:45 -04004534 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004535
David Neto87846742018-04-11 17:36:22 -04004536 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004537 SPIRVInstList.push_back(Inst);
4538 break;
4539 }
4540
4541 // isinf is converted to OpIsInf
4542 if (Callee->getName().equals("__spirv_isinff") ||
4543 Callee->getName().equals("__spirv_isinfDv2_f") ||
4544 Callee->getName().equals("__spirv_isinfDv3_f") ||
4545 Callee->getName().equals("__spirv_isinfDv4_f")) {
4546 //
4547 // Generate OpIsInf.
4548 //
4549 // Ops[0] = Result Type ID
4550 // Ops[1] = X ID
4551 //
4552 SPIRVOperandList Ops;
4553
David Neto257c3892018-04-11 13:19:45 -04004554 Ops << MkId(lookupType(I.getType()))
4555 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004556
4557 VMap[&I] = nextID;
4558
David Neto87846742018-04-11 17:36:22 -04004559 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004560 SPIRVInstList.push_back(Inst);
4561 break;
4562 }
4563
4564 // isnan is converted to OpIsNan
4565 if (Callee->getName().equals("__spirv_isnanf") ||
4566 Callee->getName().equals("__spirv_isnanDv2_f") ||
4567 Callee->getName().equals("__spirv_isnanDv3_f") ||
4568 Callee->getName().equals("__spirv_isnanDv4_f")) {
4569 //
4570 // Generate OpIsInf.
4571 //
4572 // Ops[0] = Result Type ID
4573 // Ops[1] = X ID
4574 //
4575 SPIRVOperandList Ops;
4576
David Neto257c3892018-04-11 13:19:45 -04004577 Ops << MkId(lookupType(I.getType()))
4578 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004579
4580 VMap[&I] = nextID;
4581
David Neto87846742018-04-11 17:36:22 -04004582 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004583 SPIRVInstList.push_back(Inst);
4584 break;
4585 }
4586
4587 // all is converted to OpAll
4588 if (Callee->getName().equals("__spirv_allDv2_i") ||
4589 Callee->getName().equals("__spirv_allDv3_i") ||
4590 Callee->getName().equals("__spirv_allDv4_i")) {
4591 //
4592 // Generate OpAll.
4593 //
4594 // Ops[0] = Result Type ID
4595 // Ops[1] = Vector ID
4596 //
4597 SPIRVOperandList Ops;
4598
David Neto257c3892018-04-11 13:19:45 -04004599 Ops << MkId(lookupType(I.getType()))
4600 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004601
4602 VMap[&I] = nextID;
4603
David Neto87846742018-04-11 17:36:22 -04004604 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004605 SPIRVInstList.push_back(Inst);
4606 break;
4607 }
4608
4609 // any is converted to OpAny
4610 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4611 Callee->getName().equals("__spirv_anyDv3_i") ||
4612 Callee->getName().equals("__spirv_anyDv4_i")) {
4613 //
4614 // Generate OpAny.
4615 //
4616 // Ops[0] = Result Type ID
4617 // Ops[1] = Vector ID
4618 //
4619 SPIRVOperandList Ops;
4620
David Neto257c3892018-04-11 13:19:45 -04004621 Ops << MkId(lookupType(I.getType()))
4622 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004623
4624 VMap[&I] = nextID;
4625
David Neto87846742018-04-11 17:36:22 -04004626 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004627 SPIRVInstList.push_back(Inst);
4628 break;
4629 }
4630
4631 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4632 // Additionally, OpTypeSampledImage is generated.
4633 if (Callee->getName().equals(
4634 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4635 Callee->getName().equals(
4636 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4637 //
4638 // Generate OpSampledImage.
4639 //
4640 // Ops[0] = Result Type ID
4641 // Ops[1] = Image ID
4642 // Ops[2] = Sampler ID
4643 //
4644 SPIRVOperandList Ops;
4645
4646 Value *Image = Call->getArgOperand(0);
4647 Value *Sampler = Call->getArgOperand(1);
4648 Value *Coordinate = Call->getArgOperand(2);
4649
4650 TypeMapType &OpImageTypeMap = getImageTypeMap();
4651 Type *ImageTy = Image->getType()->getPointerElementType();
4652 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004653 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004654 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004655
4656 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004657
4658 uint32_t SampledImageID = nextID;
4659
David Neto87846742018-04-11 17:36:22 -04004660 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004661 SPIRVInstList.push_back(Inst);
4662
4663 //
4664 // Generate OpImageSampleExplicitLod.
4665 //
4666 // Ops[0] = Result Type ID
4667 // Ops[1] = Sampled Image ID
4668 // Ops[2] = Coordinate ID
4669 // Ops[3] = Image Operands Type ID
4670 // Ops[4] ... Ops[n] = Operands ID
4671 //
4672 Ops.clear();
4673
David Neto257c3892018-04-11 13:19:45 -04004674 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4675 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004676
4677 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004678 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004679
4680 VMap[&I] = nextID;
4681
David Neto87846742018-04-11 17:36:22 -04004682 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004683 SPIRVInstList.push_back(Inst);
4684 break;
4685 }
4686
4687 // write_imagef is mapped to OpImageWrite.
4688 if (Callee->getName().equals(
4689 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4690 Callee->getName().equals(
4691 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4692 //
4693 // Generate OpImageWrite.
4694 //
4695 // Ops[0] = Image ID
4696 // Ops[1] = Coordinate ID
4697 // Ops[2] = Texel ID
4698 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4699 // Ops[4] ... Ops[n] = (Optional) Operands ID
4700 //
4701 SPIRVOperandList Ops;
4702
4703 Value *Image = Call->getArgOperand(0);
4704 Value *Coordinate = Call->getArgOperand(1);
4705 Value *Texel = Call->getArgOperand(2);
4706
4707 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004708 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004709 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004710 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004711
David Neto87846742018-04-11 17:36:22 -04004712 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004713 SPIRVInstList.push_back(Inst);
4714 break;
4715 }
4716
David Neto5c22a252018-03-15 16:07:41 -04004717 // get_image_width is mapped to OpImageQuerySize
4718 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4719 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4720 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4721 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4722 //
4723 // Generate OpImageQuerySize, then pull out the right component.
4724 // Assume 2D image for now.
4725 //
4726 // Ops[0] = Image ID
4727 //
4728 // %sizes = OpImageQuerySizes %uint2 %im
4729 // %result = OpCompositeExtract %uint %sizes 0-or-1
4730 SPIRVOperandList Ops;
4731
4732 // Implement:
4733 // %sizes = OpImageQuerySizes %uint2 %im
4734 uint32_t SizesTypeID =
4735 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004736 Value *Image = Call->getArgOperand(0);
4737 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004738 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004739
4740 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004741 auto *QueryInst =
4742 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004743 SPIRVInstList.push_back(QueryInst);
4744
4745 // Reset value map entry since we generated an intermediate instruction.
4746 VMap[&I] = nextID;
4747
4748 // Implement:
4749 // %result = OpCompositeExtract %uint %sizes 0-or-1
4750 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004751 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004752
4753 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004754 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004755
David Neto87846742018-04-11 17:36:22 -04004756 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004757 SPIRVInstList.push_back(Inst);
4758 break;
4759 }
4760
David Neto22f144c2017-06-12 14:26:21 -04004761 // Call instrucion is deferred because it needs function's ID. Record
4762 // slot's location on SPIRVInstructionList.
4763 DeferredInsts.push_back(
4764 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4765
David Neto3fbb4072017-10-16 11:28:14 -04004766 // Check whether the implementation of this call uses an extended
4767 // instruction plus one more value-producing instruction. If so, then
4768 // reserve the id for the extra value-producing slot.
4769 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4770 if (EInst != kGlslExtInstBad) {
4771 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004772 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004773 VMap[&I] = nextID;
4774 nextID++;
4775 }
4776 break;
4777 }
4778 case Instruction::Ret: {
4779 unsigned NumOps = I.getNumOperands();
4780 if (NumOps == 0) {
4781 //
4782 // Generate OpReturn.
4783 //
David Neto87846742018-04-11 17:36:22 -04004784 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004785 } else {
4786 //
4787 // Generate OpReturnValue.
4788 //
4789
4790 // Ops[0] = Return Value ID
4791 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004792
4793 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004794
David Neto87846742018-04-11 17:36:22 -04004795 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004796 SPIRVInstList.push_back(Inst);
4797 break;
4798 }
4799 break;
4800 }
4801 }
4802}
4803
4804void SPIRVProducerPass::GenerateFuncEpilogue() {
4805 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4806
4807 //
4808 // Generate OpFunctionEnd
4809 //
4810
David Neto87846742018-04-11 17:36:22 -04004811 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004812 SPIRVInstList.push_back(Inst);
4813}
4814
4815bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4816 LLVMContext &Context = Ty->getContext();
4817 if (Ty->isVectorTy()) {
4818 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4819 Ty->getVectorNumElements() == 4) {
4820 return true;
4821 }
4822 }
4823
4824 return false;
4825}
4826
David Neto257c3892018-04-11 13:19:45 -04004827uint32_t SPIRVProducerPass::GetI32Zero() {
4828 if (0 == constant_i32_zero_id_) {
4829 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4830 "defined in the SPIR-V module");
4831 }
4832 return constant_i32_zero_id_;
4833}
4834
David Neto22f144c2017-06-12 14:26:21 -04004835void SPIRVProducerPass::HandleDeferredInstruction() {
4836 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4837 ValueMapType &VMap = getValueMap();
4838 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4839
4840 for (auto DeferredInst = DeferredInsts.rbegin();
4841 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4842 Value *Inst = std::get<0>(*DeferredInst);
4843 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4844 if (InsertPoint != SPIRVInstList.end()) {
4845 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4846 ++InsertPoint;
4847 }
4848 }
4849
4850 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4851 // Check whether basic block, which has this branch instruction, is loop
4852 // header or not. If it is loop header, generate OpLoopMerge and
4853 // OpBranchConditional.
4854 Function *Func = Br->getParent()->getParent();
4855 DominatorTree &DT =
4856 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4857 const LoopInfo &LI =
4858 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4859
4860 BasicBlock *BrBB = Br->getParent();
4861 if (LI.isLoopHeader(BrBB)) {
4862 Value *ContinueBB = nullptr;
4863 Value *MergeBB = nullptr;
4864
4865 Loop *L = LI.getLoopFor(BrBB);
4866 MergeBB = L->getExitBlock();
4867 if (!MergeBB) {
4868 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4869 // has regions with single entry/exit. As a result, loop should not
4870 // have multiple exits.
4871 llvm_unreachable("Loop has multiple exits???");
4872 }
4873
4874 if (L->isLoopLatch(BrBB)) {
4875 ContinueBB = BrBB;
4876 } else {
4877 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4878 // block.
4879 BasicBlock *Header = L->getHeader();
4880 BasicBlock *Latch = L->getLoopLatch();
4881 for (BasicBlock *BB : L->blocks()) {
4882 if (BB == Header) {
4883 continue;
4884 }
4885
4886 // Check whether block dominates block with back-edge.
4887 if (DT.dominates(BB, Latch)) {
4888 ContinueBB = BB;
4889 }
4890 }
4891
4892 if (!ContinueBB) {
4893 llvm_unreachable("Wrong continue block from loop");
4894 }
4895 }
4896
4897 //
4898 // Generate OpLoopMerge.
4899 //
4900 // Ops[0] = Merge Block ID
4901 // Ops[1] = Continue Target ID
4902 // Ops[2] = Selection Control
4903 SPIRVOperandList Ops;
4904
4905 // StructurizeCFG pass already manipulated CFG. Just use false block of
4906 // branch instruction as merge block.
4907 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004908 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004909 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4910 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004911
David Neto87846742018-04-11 17:36:22 -04004912 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004913 SPIRVInstList.insert(InsertPoint, MergeInst);
4914
4915 } else if (Br->isConditional()) {
4916 bool HasBackEdge = false;
4917
4918 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4919 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4920 HasBackEdge = true;
4921 }
4922 }
4923 if (!HasBackEdge) {
4924 //
4925 // Generate OpSelectionMerge.
4926 //
4927 // Ops[0] = Merge Block ID
4928 // Ops[1] = Selection Control
4929 SPIRVOperandList Ops;
4930
4931 // StructurizeCFG pass already manipulated CFG. Just use false block
4932 // of branch instruction as merge block.
4933 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004934 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004935
David Neto87846742018-04-11 17:36:22 -04004936 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004937 SPIRVInstList.insert(InsertPoint, MergeInst);
4938 }
4939 }
4940
4941 if (Br->isConditional()) {
4942 //
4943 // Generate OpBranchConditional.
4944 //
4945 // Ops[0] = Condition ID
4946 // Ops[1] = True Label ID
4947 // Ops[2] = False Label ID
4948 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4949 SPIRVOperandList Ops;
4950
4951 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004952 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004953 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004954
4955 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004956
David Neto87846742018-04-11 17:36:22 -04004957 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004958 SPIRVInstList.insert(InsertPoint, BrInst);
4959 } else {
4960 //
4961 // Generate OpBranch.
4962 //
4963 // Ops[0] = Target Label ID
4964 SPIRVOperandList Ops;
4965
4966 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004967 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004968
David Neto87846742018-04-11 17:36:22 -04004969 SPIRVInstList.insert(InsertPoint,
4970 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004971 }
4972 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4973 //
4974 // Generate OpPhi.
4975 //
4976 // Ops[0] = Result Type ID
4977 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4978 SPIRVOperandList Ops;
4979
David Neto257c3892018-04-11 13:19:45 -04004980 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04004981
David Neto22f144c2017-06-12 14:26:21 -04004982 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4983 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04004984 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04004985 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04004986 }
4987
4988 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04004989 InsertPoint,
4990 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04004991 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4992 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04004993 auto callee_name = Callee->getName();
4994 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04004995
4996 if (EInst) {
4997 uint32_t &ExtInstImportID = getOpExtInstImportID();
4998
4999 //
5000 // Generate OpExtInst.
5001 //
5002
5003 // Ops[0] = Result Type ID
5004 // Ops[1] = Set ID (OpExtInstImport ID)
5005 // Ops[2] = Instruction Number (Literal Number)
5006 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5007 SPIRVOperandList Ops;
5008
David Neto862b7d82018-06-14 18:48:37 -04005009 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5010 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005011
David Neto22f144c2017-06-12 14:26:21 -04005012 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5013 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005014 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005015 }
5016
David Neto87846742018-04-11 17:36:22 -04005017 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5018 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005019 SPIRVInstList.insert(InsertPoint, ExtInst);
5020
David Neto3fbb4072017-10-16 11:28:14 -04005021 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5022 if (IndirectExtInst != kGlslExtInstBad) {
5023 // Generate one more instruction that uses the result of the extended
5024 // instruction. Its result id is one more than the id of the
5025 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005026 LLVMContext &Context =
5027 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005028
David Neto3fbb4072017-10-16 11:28:14 -04005029 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5030 &VMap, &SPIRVInstList, &InsertPoint](
5031 spv::Op opcode, Constant *constant) {
5032 //
5033 // Generate instruction like:
5034 // result = opcode constant <extinst-result>
5035 //
5036 // Ops[0] = Result Type ID
5037 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5038 // Ops[2] = Operand 1 ;; the result of the extended instruction
5039 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005040
David Neto3fbb4072017-10-16 11:28:14 -04005041 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005042 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005043
5044 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5045 constant = ConstantVector::getSplat(
5046 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5047 }
David Neto257c3892018-04-11 13:19:45 -04005048 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005049
5050 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005051 InsertPoint, new SPIRVInstruction(
5052 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005053 };
5054
5055 switch (IndirectExtInst) {
5056 case glsl::ExtInstFindUMsb: // Implementing clz
5057 generate_extra_inst(
5058 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5059 break;
5060 case glsl::ExtInstAcos: // Implementing acospi
5061 case glsl::ExtInstAsin: // Implementing asinpi
5062 case glsl::ExtInstAtan2: // Implementing atan2pi
5063 generate_extra_inst(
5064 spv::OpFMul,
5065 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5066 break;
5067
5068 default:
5069 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005070 }
David Neto22f144c2017-06-12 14:26:21 -04005071 }
David Neto3fbb4072017-10-16 11:28:14 -04005072
David Neto862b7d82018-06-14 18:48:37 -04005073 } else if (callee_name.equals("_Z8popcounti") ||
5074 callee_name.equals("_Z8popcountj") ||
5075 callee_name.equals("_Z8popcountDv2_i") ||
5076 callee_name.equals("_Z8popcountDv3_i") ||
5077 callee_name.equals("_Z8popcountDv4_i") ||
5078 callee_name.equals("_Z8popcountDv2_j") ||
5079 callee_name.equals("_Z8popcountDv3_j") ||
5080 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005081 //
5082 // Generate OpBitCount
5083 //
5084 // Ops[0] = Result Type ID
5085 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005086 SPIRVOperandList Ops;
5087 Ops << MkId(lookupType(Call->getType()))
5088 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005089
5090 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005091 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005092 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005093
David Neto862b7d82018-06-14 18:48:37 -04005094 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005095
5096 // Generate an OpCompositeConstruct
5097 SPIRVOperandList Ops;
5098
5099 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005100 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005101
5102 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005103 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005104 }
5105
5106 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005107 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5108 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005109
David Neto862b7d82018-06-14 18:48:37 -04005110 } else if (callee_name.startswith("clspv.resource.var.")) {
5111
5112 // We have already mapped the call's result value to an ID.
5113 // Don't generate any code now.
5114
David Neto22f144c2017-06-12 14:26:21 -04005115 } else {
5116 //
5117 // Generate OpFunctionCall.
5118 //
5119
5120 // Ops[0] = Result Type ID
5121 // Ops[1] = Callee Function ID
5122 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5123 SPIRVOperandList Ops;
5124
David Neto862b7d82018-06-14 18:48:37 -04005125 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005126
5127 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005128 if (CalleeID == 0) {
5129 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005130 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005131 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5132 // causes an infinite loop. Instead, go ahead and generate
5133 // the bad function call. A validator will catch the 0-Id.
5134 // llvm_unreachable("Can't translate function call");
5135 }
David Neto22f144c2017-06-12 14:26:21 -04005136
David Neto257c3892018-04-11 13:19:45 -04005137 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005138
David Neto22f144c2017-06-12 14:26:21 -04005139 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5140 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005141 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005142 }
5143
David Neto87846742018-04-11 17:36:22 -04005144 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5145 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005146 SPIRVInstList.insert(InsertPoint, CallInst);
5147 }
5148 }
5149 }
5150}
5151
David Neto1a1a0582017-07-07 12:01:44 -04005152void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
David Netoc6f3ab22018-04-06 18:02:31 -04005153 if (getTypesNeedingArrayStride().empty() && LocalArgs.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005154 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005155 }
David Neto1a1a0582017-07-07 12:01:44 -04005156
5157 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005158
5159 // Find an iterator pointing just past the last decoration.
5160 bool seen_decorations = false;
5161 auto DecoInsertPoint =
5162 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5163 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5164 const bool is_decoration =
5165 Inst->getOpcode() == spv::OpDecorate ||
5166 Inst->getOpcode() == spv::OpMemberDecorate;
5167 if (is_decoration) {
5168 seen_decorations = true;
5169 return false;
5170 } else {
5171 return seen_decorations;
5172 }
5173 });
5174
David Netoc6f3ab22018-04-06 18:02:31 -04005175 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5176 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005177 for (auto *type : getTypesNeedingArrayStride()) {
5178 Type *elemTy = nullptr;
5179 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5180 elemTy = ptrTy->getElementType();
5181 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5182 elemTy = arrayTy->getArrayElementType();
5183 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5184 elemTy = seqTy->getSequentialElementType();
5185 } else {
5186 errs() << "Unhandled strided type " << *type << "\n";
5187 llvm_unreachable("Unhandled strided type");
5188 }
David Neto1a1a0582017-07-07 12:01:44 -04005189
5190 // Ops[0] = Target ID
5191 // Ops[1] = Decoration (ArrayStride)
5192 // Ops[2] = Stride number (Literal Number)
5193 SPIRVOperandList Ops;
5194
David Neto85082642018-03-24 06:55:20 -07005195 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005196 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005197
5198 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5199 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005200
David Neto87846742018-04-11 17:36:22 -04005201 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005202 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5203 }
David Netoc6f3ab22018-04-06 18:02:31 -04005204
5205 // Emit SpecId decorations targeting the array size value.
5206 for (const Argument *arg : LocalArgs) {
5207 const LocalArgInfo &arg_info = LocalArgMap[arg];
5208 SPIRVOperandList Ops;
5209 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5210 << MkNum(arg_info.spec_id);
5211 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005212 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005213 }
David Neto1a1a0582017-07-07 12:01:44 -04005214}
5215
David Neto22f144c2017-06-12 14:26:21 -04005216glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5217 return StringSwitch<glsl::ExtInst>(Name)
5218 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5219 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5220 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5221 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5222 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5223 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5224 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5225 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5226 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5227 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5228 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5229 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5230 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5231 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5232 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5233 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005234 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5235 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5236 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5237 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5238 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5239 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5240 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5241 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5242 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5243 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5244 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5245 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5246 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5247 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5248 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5249 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5250 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5251 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5252 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5253 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5254 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5255 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5256 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5257 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5258 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5259 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5260 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5261 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5262 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5263 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5264 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5265 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5266 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5267 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5268 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5269 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5270 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5271 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5272 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5273 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5274 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5275 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5276 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5277 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5278 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5279 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5280 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5281 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5282 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5283 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5284 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5285 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5286 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5287 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5288 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5289 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5290 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5291 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5292 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5293 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5294 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5295 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5296 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5297 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5298 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5299 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5300 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5301 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5302 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5303 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5304 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5305 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5306 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5307 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5308 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5309 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5310 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5311 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5312 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5313 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005314 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005315 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5316 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5317 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5318 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5319 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005320 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5321 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5322 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5323 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005324 .Default(kGlslExtInstBad);
5325}
5326
5327glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5328 // Check indirect cases.
5329 return StringSwitch<glsl::ExtInst>(Name)
5330 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5331 // Use exact match on float arg because these need a multiply
5332 // of a constant of the right floating point type.
5333 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5334 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5335 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5336 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5337 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5338 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5339 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5340 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5341 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5342 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5343 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5344 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5345 .Default(kGlslExtInstBad);
5346}
5347
5348glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5349 auto direct = getExtInstEnum(Name);
5350 if (direct != kGlslExtInstBad)
5351 return direct;
5352 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005353}
5354
5355void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5356 out << "%" << Inst->getResultID();
5357}
5358
5359void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5360 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5361 out << "\t" << spv::getOpName(Opcode);
5362}
5363
5364void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5365 SPIRVOperandType OpTy = Op->getType();
5366 switch (OpTy) {
5367 default: {
5368 llvm_unreachable("Unsupported SPIRV Operand Type???");
5369 break;
5370 }
5371 case SPIRVOperandType::NUMBERID: {
5372 out << "%" << Op->getNumID();
5373 break;
5374 }
5375 case SPIRVOperandType::LITERAL_STRING: {
5376 out << "\"" << Op->getLiteralStr() << "\"";
5377 break;
5378 }
5379 case SPIRVOperandType::LITERAL_INTEGER: {
5380 // TODO: Handle LiteralNum carefully.
5381 for (auto Word : Op->getLiteralNum()) {
5382 out << Word;
5383 }
5384 break;
5385 }
5386 case SPIRVOperandType::LITERAL_FLOAT: {
5387 // TODO: Handle LiteralNum carefully.
5388 for (auto Word : Op->getLiteralNum()) {
5389 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5390 SmallString<8> Str;
5391 APF.toString(Str, 6, 2);
5392 out << Str;
5393 }
5394 break;
5395 }
5396 }
5397}
5398
5399void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5400 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5401 out << spv::getCapabilityName(Cap);
5402}
5403
5404void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5405 auto LiteralNum = Op->getLiteralNum();
5406 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5407 out << glsl::getExtInstName(Ext);
5408}
5409
5410void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5411 spv::AddressingModel AddrModel =
5412 static_cast<spv::AddressingModel>(Op->getNumID());
5413 out << spv::getAddressingModelName(AddrModel);
5414}
5415
5416void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5417 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5418 out << spv::getMemoryModelName(MemModel);
5419}
5420
5421void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5422 spv::ExecutionModel ExecModel =
5423 static_cast<spv::ExecutionModel>(Op->getNumID());
5424 out << spv::getExecutionModelName(ExecModel);
5425}
5426
5427void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5428 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5429 out << spv::getExecutionModeName(ExecMode);
5430}
5431
5432void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5433 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5434 out << spv::getSourceLanguageName(SourceLang);
5435}
5436
5437void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5438 spv::FunctionControlMask FuncCtrl =
5439 static_cast<spv::FunctionControlMask>(Op->getNumID());
5440 out << spv::getFunctionControlName(FuncCtrl);
5441}
5442
5443void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5444 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5445 out << getStorageClassName(StClass);
5446}
5447
5448void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5449 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5450 out << getDecorationName(Deco);
5451}
5452
5453void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5454 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5455 out << getBuiltInName(BIn);
5456}
5457
5458void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5459 spv::SelectionControlMask BIn =
5460 static_cast<spv::SelectionControlMask>(Op->getNumID());
5461 out << getSelectionControlName(BIn);
5462}
5463
5464void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5465 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5466 out << getLoopControlName(BIn);
5467}
5468
5469void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5470 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5471 out << getDimName(DIM);
5472}
5473
5474void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5475 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5476 out << getImageFormatName(Format);
5477}
5478
5479void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5480 out << spv::getMemoryAccessName(
5481 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5482}
5483
5484void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5485 auto LiteralNum = Op->getLiteralNum();
5486 spv::ImageOperandsMask Type =
5487 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5488 out << getImageOperandsName(Type);
5489}
5490
5491void SPIRVProducerPass::WriteSPIRVAssembly() {
5492 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5493
5494 for (auto Inst : SPIRVInstList) {
5495 SPIRVOperandList Ops = Inst->getOperands();
5496 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5497
5498 switch (Opcode) {
5499 default: {
5500 llvm_unreachable("Unsupported SPIRV instruction");
5501 break;
5502 }
5503 case spv::OpCapability: {
5504 // Ops[0] = Capability
5505 PrintOpcode(Inst);
5506 out << " ";
5507 PrintCapability(Ops[0]);
5508 out << "\n";
5509 break;
5510 }
5511 case spv::OpMemoryModel: {
5512 // Ops[0] = Addressing Model
5513 // Ops[1] = Memory Model
5514 PrintOpcode(Inst);
5515 out << " ";
5516 PrintAddrModel(Ops[0]);
5517 out << " ";
5518 PrintMemModel(Ops[1]);
5519 out << "\n";
5520 break;
5521 }
5522 case spv::OpEntryPoint: {
5523 // Ops[0] = Execution Model
5524 // Ops[1] = EntryPoint ID
5525 // Ops[2] = Name (Literal String)
5526 // Ops[3] ... Ops[n] = Interface ID
5527 PrintOpcode(Inst);
5528 out << " ";
5529 PrintExecModel(Ops[0]);
5530 for (uint32_t i = 1; i < Ops.size(); i++) {
5531 out << " ";
5532 PrintOperand(Ops[i]);
5533 }
5534 out << "\n";
5535 break;
5536 }
5537 case spv::OpExecutionMode: {
5538 // Ops[0] = Entry Point ID
5539 // Ops[1] = Execution Mode
5540 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5541 PrintOpcode(Inst);
5542 out << " ";
5543 PrintOperand(Ops[0]);
5544 out << " ";
5545 PrintExecMode(Ops[1]);
5546 for (uint32_t i = 2; i < Ops.size(); i++) {
5547 out << " ";
5548 PrintOperand(Ops[i]);
5549 }
5550 out << "\n";
5551 break;
5552 }
5553 case spv::OpSource: {
5554 // Ops[0] = SourceLanguage ID
5555 // Ops[1] = Version (LiteralNum)
5556 PrintOpcode(Inst);
5557 out << " ";
5558 PrintSourceLanguage(Ops[0]);
5559 out << " ";
5560 PrintOperand(Ops[1]);
5561 out << "\n";
5562 break;
5563 }
5564 case spv::OpDecorate: {
5565 // Ops[0] = Target ID
5566 // Ops[1] = Decoration (Block or BufferBlock)
5567 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5568 PrintOpcode(Inst);
5569 out << " ";
5570 PrintOperand(Ops[0]);
5571 out << " ";
5572 PrintDecoration(Ops[1]);
5573 // Handle BuiltIn OpDecorate specially.
5574 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5575 out << " ";
5576 PrintBuiltIn(Ops[2]);
5577 } else {
5578 for (uint32_t i = 2; i < Ops.size(); i++) {
5579 out << " ";
5580 PrintOperand(Ops[i]);
5581 }
5582 }
5583 out << "\n";
5584 break;
5585 }
5586 case spv::OpMemberDecorate: {
5587 // Ops[0] = Structure Type ID
5588 // Ops[1] = Member Index(Literal Number)
5589 // Ops[2] = Decoration
5590 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5591 PrintOpcode(Inst);
5592 out << " ";
5593 PrintOperand(Ops[0]);
5594 out << " ";
5595 PrintOperand(Ops[1]);
5596 out << " ";
5597 PrintDecoration(Ops[2]);
5598 for (uint32_t i = 3; i < Ops.size(); i++) {
5599 out << " ";
5600 PrintOperand(Ops[i]);
5601 }
5602 out << "\n";
5603 break;
5604 }
5605 case spv::OpTypePointer: {
5606 // Ops[0] = Storage Class
5607 // Ops[1] = Element Type ID
5608 PrintResID(Inst);
5609 out << " = ";
5610 PrintOpcode(Inst);
5611 out << " ";
5612 PrintStorageClass(Ops[0]);
5613 out << " ";
5614 PrintOperand(Ops[1]);
5615 out << "\n";
5616 break;
5617 }
5618 case spv::OpTypeImage: {
5619 // Ops[0] = Sampled Type ID
5620 // Ops[1] = Dim ID
5621 // Ops[2] = Depth (Literal Number)
5622 // Ops[3] = Arrayed (Literal Number)
5623 // Ops[4] = MS (Literal Number)
5624 // Ops[5] = Sampled (Literal Number)
5625 // Ops[6] = Image Format ID
5626 PrintResID(Inst);
5627 out << " = ";
5628 PrintOpcode(Inst);
5629 out << " ";
5630 PrintOperand(Ops[0]);
5631 out << " ";
5632 PrintDimensionality(Ops[1]);
5633 out << " ";
5634 PrintOperand(Ops[2]);
5635 out << " ";
5636 PrintOperand(Ops[3]);
5637 out << " ";
5638 PrintOperand(Ops[4]);
5639 out << " ";
5640 PrintOperand(Ops[5]);
5641 out << " ";
5642 PrintImageFormat(Ops[6]);
5643 out << "\n";
5644 break;
5645 }
5646 case spv::OpFunction: {
5647 // Ops[0] : Result Type ID
5648 // Ops[1] : Function Control
5649 // Ops[2] : Function Type ID
5650 PrintResID(Inst);
5651 out << " = ";
5652 PrintOpcode(Inst);
5653 out << " ";
5654 PrintOperand(Ops[0]);
5655 out << " ";
5656 PrintFuncCtrl(Ops[1]);
5657 out << " ";
5658 PrintOperand(Ops[2]);
5659 out << "\n";
5660 break;
5661 }
5662 case spv::OpSelectionMerge: {
5663 // Ops[0] = Merge Block ID
5664 // Ops[1] = Selection Control
5665 PrintOpcode(Inst);
5666 out << " ";
5667 PrintOperand(Ops[0]);
5668 out << " ";
5669 PrintSelectionControl(Ops[1]);
5670 out << "\n";
5671 break;
5672 }
5673 case spv::OpLoopMerge: {
5674 // Ops[0] = Merge Block ID
5675 // Ops[1] = Continue Target ID
5676 // Ops[2] = Selection Control
5677 PrintOpcode(Inst);
5678 out << " ";
5679 PrintOperand(Ops[0]);
5680 out << " ";
5681 PrintOperand(Ops[1]);
5682 out << " ";
5683 PrintLoopControl(Ops[2]);
5684 out << "\n";
5685 break;
5686 }
5687 case spv::OpImageSampleExplicitLod: {
5688 // Ops[0] = Result Type ID
5689 // Ops[1] = Sampled Image ID
5690 // Ops[2] = Coordinate ID
5691 // Ops[3] = Image Operands Type ID
5692 // Ops[4] ... Ops[n] = Operands ID
5693 PrintResID(Inst);
5694 out << " = ";
5695 PrintOpcode(Inst);
5696 for (uint32_t i = 0; i < 3; i++) {
5697 out << " ";
5698 PrintOperand(Ops[i]);
5699 }
5700 out << " ";
5701 PrintImageOperandsType(Ops[3]);
5702 for (uint32_t i = 4; i < Ops.size(); i++) {
5703 out << " ";
5704 PrintOperand(Ops[i]);
5705 }
5706 out << "\n";
5707 break;
5708 }
5709 case spv::OpVariable: {
5710 // Ops[0] : Result Type ID
5711 // Ops[1] : Storage Class
5712 // Ops[2] ... Ops[n] = Initializer IDs
5713 PrintResID(Inst);
5714 out << " = ";
5715 PrintOpcode(Inst);
5716 out << " ";
5717 PrintOperand(Ops[0]);
5718 out << " ";
5719 PrintStorageClass(Ops[1]);
5720 for (uint32_t i = 2; i < Ops.size(); i++) {
5721 out << " ";
5722 PrintOperand(Ops[i]);
5723 }
5724 out << "\n";
5725 break;
5726 }
5727 case spv::OpExtInst: {
5728 // Ops[0] = Result Type ID
5729 // Ops[1] = Set ID (OpExtInstImport ID)
5730 // Ops[2] = Instruction Number (Literal Number)
5731 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5732 PrintResID(Inst);
5733 out << " = ";
5734 PrintOpcode(Inst);
5735 out << " ";
5736 PrintOperand(Ops[0]);
5737 out << " ";
5738 PrintOperand(Ops[1]);
5739 out << " ";
5740 PrintExtInst(Ops[2]);
5741 for (uint32_t i = 3; i < Ops.size(); i++) {
5742 out << " ";
5743 PrintOperand(Ops[i]);
5744 }
5745 out << "\n";
5746 break;
5747 }
5748 case spv::OpCopyMemory: {
5749 // Ops[0] = Addressing Model
5750 // Ops[1] = Memory Model
5751 PrintOpcode(Inst);
5752 out << " ";
5753 PrintOperand(Ops[0]);
5754 out << " ";
5755 PrintOperand(Ops[1]);
5756 out << " ";
5757 PrintMemoryAccess(Ops[2]);
5758 out << " ";
5759 PrintOperand(Ops[3]);
5760 out << "\n";
5761 break;
5762 }
5763 case spv::OpExtension:
5764 case spv::OpControlBarrier:
5765 case spv::OpMemoryBarrier:
5766 case spv::OpBranch:
5767 case spv::OpBranchConditional:
5768 case spv::OpStore:
5769 case spv::OpImageWrite:
5770 case spv::OpReturnValue:
5771 case spv::OpReturn:
5772 case spv::OpFunctionEnd: {
5773 PrintOpcode(Inst);
5774 for (uint32_t i = 0; i < Ops.size(); i++) {
5775 out << " ";
5776 PrintOperand(Ops[i]);
5777 }
5778 out << "\n";
5779 break;
5780 }
5781 case spv::OpExtInstImport:
5782 case spv::OpTypeRuntimeArray:
5783 case spv::OpTypeStruct:
5784 case spv::OpTypeSampler:
5785 case spv::OpTypeSampledImage:
5786 case spv::OpTypeInt:
5787 case spv::OpTypeFloat:
5788 case spv::OpTypeArray:
5789 case spv::OpTypeVector:
5790 case spv::OpTypeBool:
5791 case spv::OpTypeVoid:
5792 case spv::OpTypeFunction:
5793 case spv::OpFunctionParameter:
5794 case spv::OpLabel:
5795 case spv::OpPhi:
5796 case spv::OpLoad:
5797 case spv::OpSelect:
5798 case spv::OpAccessChain:
5799 case spv::OpPtrAccessChain:
5800 case spv::OpInBoundsAccessChain:
5801 case spv::OpUConvert:
5802 case spv::OpSConvert:
5803 case spv::OpConvertFToU:
5804 case spv::OpConvertFToS:
5805 case spv::OpConvertUToF:
5806 case spv::OpConvertSToF:
5807 case spv::OpFConvert:
5808 case spv::OpConvertPtrToU:
5809 case spv::OpConvertUToPtr:
5810 case spv::OpBitcast:
5811 case spv::OpIAdd:
5812 case spv::OpFAdd:
5813 case spv::OpISub:
5814 case spv::OpFSub:
5815 case spv::OpIMul:
5816 case spv::OpFMul:
5817 case spv::OpUDiv:
5818 case spv::OpSDiv:
5819 case spv::OpFDiv:
5820 case spv::OpUMod:
5821 case spv::OpSRem:
5822 case spv::OpFRem:
5823 case spv::OpBitwiseOr:
5824 case spv::OpBitwiseXor:
5825 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005826 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005827 case spv::OpShiftLeftLogical:
5828 case spv::OpShiftRightLogical:
5829 case spv::OpShiftRightArithmetic:
5830 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005831 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005832 case spv::OpCompositeExtract:
5833 case spv::OpVectorExtractDynamic:
5834 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005835 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005836 case spv::OpVectorInsertDynamic:
5837 case spv::OpVectorShuffle:
5838 case spv::OpIEqual:
5839 case spv::OpINotEqual:
5840 case spv::OpUGreaterThan:
5841 case spv::OpUGreaterThanEqual:
5842 case spv::OpULessThan:
5843 case spv::OpULessThanEqual:
5844 case spv::OpSGreaterThan:
5845 case spv::OpSGreaterThanEqual:
5846 case spv::OpSLessThan:
5847 case spv::OpSLessThanEqual:
5848 case spv::OpFOrdEqual:
5849 case spv::OpFOrdGreaterThan:
5850 case spv::OpFOrdGreaterThanEqual:
5851 case spv::OpFOrdLessThan:
5852 case spv::OpFOrdLessThanEqual:
5853 case spv::OpFOrdNotEqual:
5854 case spv::OpFUnordEqual:
5855 case spv::OpFUnordGreaterThan:
5856 case spv::OpFUnordGreaterThanEqual:
5857 case spv::OpFUnordLessThan:
5858 case spv::OpFUnordLessThanEqual:
5859 case spv::OpFUnordNotEqual:
5860 case spv::OpSampledImage:
5861 case spv::OpFunctionCall:
5862 case spv::OpConstantTrue:
5863 case spv::OpConstantFalse:
5864 case spv::OpConstant:
5865 case spv::OpSpecConstant:
5866 case spv::OpConstantComposite:
5867 case spv::OpSpecConstantComposite:
5868 case spv::OpConstantNull:
5869 case spv::OpLogicalOr:
5870 case spv::OpLogicalAnd:
5871 case spv::OpLogicalNot:
5872 case spv::OpLogicalNotEqual:
5873 case spv::OpUndef:
5874 case spv::OpIsInf:
5875 case spv::OpIsNan:
5876 case spv::OpAny:
5877 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005878 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005879 case spv::OpAtomicIAdd:
5880 case spv::OpAtomicISub:
5881 case spv::OpAtomicExchange:
5882 case spv::OpAtomicIIncrement:
5883 case spv::OpAtomicIDecrement:
5884 case spv::OpAtomicCompareExchange:
5885 case spv::OpAtomicUMin:
5886 case spv::OpAtomicSMin:
5887 case spv::OpAtomicUMax:
5888 case spv::OpAtomicSMax:
5889 case spv::OpAtomicAnd:
5890 case spv::OpAtomicOr:
5891 case spv::OpAtomicXor:
5892 case spv::OpDot: {
5893 PrintResID(Inst);
5894 out << " = ";
5895 PrintOpcode(Inst);
5896 for (uint32_t i = 0; i < Ops.size(); i++) {
5897 out << " ";
5898 PrintOperand(Ops[i]);
5899 }
5900 out << "\n";
5901 break;
5902 }
5903 }
5904 }
5905}
5906
5907void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005908 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005909}
5910
5911void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5912 WriteOneWord(Inst->getResultID());
5913}
5914
5915void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5916 // High 16 bit : Word Count
5917 // Low 16 bit : Opcode
5918 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005919 const uint32_t count = Inst->getWordCount();
5920 if (count > 65535) {
5921 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5922 llvm_unreachable("Word count too high");
5923 }
David Neto22f144c2017-06-12 14:26:21 -04005924 Word |= Inst->getWordCount() << 16;
5925 WriteOneWord(Word);
5926}
5927
5928void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5929 SPIRVOperandType OpTy = Op->getType();
5930 switch (OpTy) {
5931 default: {
5932 llvm_unreachable("Unsupported SPIRV Operand Type???");
5933 break;
5934 }
5935 case SPIRVOperandType::NUMBERID: {
5936 WriteOneWord(Op->getNumID());
5937 break;
5938 }
5939 case SPIRVOperandType::LITERAL_STRING: {
5940 std::string Str = Op->getLiteralStr();
5941 const char *Data = Str.c_str();
5942 size_t WordSize = Str.size() / 4;
5943 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5944 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5945 }
5946
5947 uint32_t Remainder = Str.size() % 4;
5948 uint32_t LastWord = 0;
5949 if (Remainder) {
5950 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5951 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5952 }
5953 }
5954
5955 WriteOneWord(LastWord);
5956 break;
5957 }
5958 case SPIRVOperandType::LITERAL_INTEGER:
5959 case SPIRVOperandType::LITERAL_FLOAT: {
5960 auto LiteralNum = Op->getLiteralNum();
5961 // TODO: Handle LiteranNum carefully.
5962 for (auto Word : LiteralNum) {
5963 WriteOneWord(Word);
5964 }
5965 break;
5966 }
5967 }
5968}
5969
5970void SPIRVProducerPass::WriteSPIRVBinary() {
5971 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5972
5973 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04005974 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04005975 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5976
5977 switch (Opcode) {
5978 default: {
David Neto5c22a252018-03-15 16:07:41 -04005979 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04005980 llvm_unreachable("Unsupported SPIRV instruction");
5981 break;
5982 }
5983 case spv::OpCapability:
5984 case spv::OpExtension:
5985 case spv::OpMemoryModel:
5986 case spv::OpEntryPoint:
5987 case spv::OpExecutionMode:
5988 case spv::OpSource:
5989 case spv::OpDecorate:
5990 case spv::OpMemberDecorate:
5991 case spv::OpBranch:
5992 case spv::OpBranchConditional:
5993 case spv::OpSelectionMerge:
5994 case spv::OpLoopMerge:
5995 case spv::OpStore:
5996 case spv::OpImageWrite:
5997 case spv::OpReturnValue:
5998 case spv::OpControlBarrier:
5999 case spv::OpMemoryBarrier:
6000 case spv::OpReturn:
6001 case spv::OpFunctionEnd:
6002 case spv::OpCopyMemory: {
6003 WriteWordCountAndOpcode(Inst);
6004 for (uint32_t i = 0; i < Ops.size(); i++) {
6005 WriteOperand(Ops[i]);
6006 }
6007 break;
6008 }
6009 case spv::OpTypeBool:
6010 case spv::OpTypeVoid:
6011 case spv::OpTypeSampler:
6012 case spv::OpLabel:
6013 case spv::OpExtInstImport:
6014 case spv::OpTypePointer:
6015 case spv::OpTypeRuntimeArray:
6016 case spv::OpTypeStruct:
6017 case spv::OpTypeImage:
6018 case spv::OpTypeSampledImage:
6019 case spv::OpTypeInt:
6020 case spv::OpTypeFloat:
6021 case spv::OpTypeArray:
6022 case spv::OpTypeVector:
6023 case spv::OpTypeFunction: {
6024 WriteWordCountAndOpcode(Inst);
6025 WriteResultID(Inst);
6026 for (uint32_t i = 0; i < Ops.size(); i++) {
6027 WriteOperand(Ops[i]);
6028 }
6029 break;
6030 }
6031 case spv::OpFunction:
6032 case spv::OpFunctionParameter:
6033 case spv::OpAccessChain:
6034 case spv::OpPtrAccessChain:
6035 case spv::OpInBoundsAccessChain:
6036 case spv::OpUConvert:
6037 case spv::OpSConvert:
6038 case spv::OpConvertFToU:
6039 case spv::OpConvertFToS:
6040 case spv::OpConvertUToF:
6041 case spv::OpConvertSToF:
6042 case spv::OpFConvert:
6043 case spv::OpConvertPtrToU:
6044 case spv::OpConvertUToPtr:
6045 case spv::OpBitcast:
6046 case spv::OpIAdd:
6047 case spv::OpFAdd:
6048 case spv::OpISub:
6049 case spv::OpFSub:
6050 case spv::OpIMul:
6051 case spv::OpFMul:
6052 case spv::OpUDiv:
6053 case spv::OpSDiv:
6054 case spv::OpFDiv:
6055 case spv::OpUMod:
6056 case spv::OpSRem:
6057 case spv::OpFRem:
6058 case spv::OpBitwiseOr:
6059 case spv::OpBitwiseXor:
6060 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006061 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006062 case spv::OpShiftLeftLogical:
6063 case spv::OpShiftRightLogical:
6064 case spv::OpShiftRightArithmetic:
6065 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006066 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006067 case spv::OpCompositeExtract:
6068 case spv::OpVectorExtractDynamic:
6069 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006070 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006071 case spv::OpVectorInsertDynamic:
6072 case spv::OpVectorShuffle:
6073 case spv::OpIEqual:
6074 case spv::OpINotEqual:
6075 case spv::OpUGreaterThan:
6076 case spv::OpUGreaterThanEqual:
6077 case spv::OpULessThan:
6078 case spv::OpULessThanEqual:
6079 case spv::OpSGreaterThan:
6080 case spv::OpSGreaterThanEqual:
6081 case spv::OpSLessThan:
6082 case spv::OpSLessThanEqual:
6083 case spv::OpFOrdEqual:
6084 case spv::OpFOrdGreaterThan:
6085 case spv::OpFOrdGreaterThanEqual:
6086 case spv::OpFOrdLessThan:
6087 case spv::OpFOrdLessThanEqual:
6088 case spv::OpFOrdNotEqual:
6089 case spv::OpFUnordEqual:
6090 case spv::OpFUnordGreaterThan:
6091 case spv::OpFUnordGreaterThanEqual:
6092 case spv::OpFUnordLessThan:
6093 case spv::OpFUnordLessThanEqual:
6094 case spv::OpFUnordNotEqual:
6095 case spv::OpExtInst:
6096 case spv::OpIsInf:
6097 case spv::OpIsNan:
6098 case spv::OpAny:
6099 case spv::OpAll:
6100 case spv::OpUndef:
6101 case spv::OpConstantNull:
6102 case spv::OpLogicalOr:
6103 case spv::OpLogicalAnd:
6104 case spv::OpLogicalNot:
6105 case spv::OpLogicalNotEqual:
6106 case spv::OpConstantComposite:
6107 case spv::OpSpecConstantComposite:
6108 case spv::OpConstantTrue:
6109 case spv::OpConstantFalse:
6110 case spv::OpConstant:
6111 case spv::OpSpecConstant:
6112 case spv::OpVariable:
6113 case spv::OpFunctionCall:
6114 case spv::OpSampledImage:
6115 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006116 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006117 case spv::OpSelect:
6118 case spv::OpPhi:
6119 case spv::OpLoad:
6120 case spv::OpAtomicIAdd:
6121 case spv::OpAtomicISub:
6122 case spv::OpAtomicExchange:
6123 case spv::OpAtomicIIncrement:
6124 case spv::OpAtomicIDecrement:
6125 case spv::OpAtomicCompareExchange:
6126 case spv::OpAtomicUMin:
6127 case spv::OpAtomicSMin:
6128 case spv::OpAtomicUMax:
6129 case spv::OpAtomicSMax:
6130 case spv::OpAtomicAnd:
6131 case spv::OpAtomicOr:
6132 case spv::OpAtomicXor:
6133 case spv::OpDot: {
6134 WriteWordCountAndOpcode(Inst);
6135 WriteOperand(Ops[0]);
6136 WriteResultID(Inst);
6137 for (uint32_t i = 1; i < Ops.size(); i++) {
6138 WriteOperand(Ops[i]);
6139 }
6140 break;
6141 }
6142 }
6143 }
6144}