blob: 6244484a432e31795bebfd9fff6642f4f5bd500c [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
David Neto118188e2018-08-24 11:27:54 -040021#include <iomanip>
22#include <list>
David Neto862b7d82018-06-14 18:48:37 -040023#include <memory>
David Neto118188e2018-08-24 11:27:54 -040024#include <set>
25#include <sstream>
26#include <string>
27#include <tuple>
28#include <unordered_set>
29#include <utility>
David Neto862b7d82018-06-14 18:48:37 -040030
David Neto22f144c2017-06-12 14:26:21 -040031
David Neto118188e2018-08-24 11:27:54 -040032#include "llvm/ADT/StringSwitch.h"
33#include "llvm/ADT/UniqueVector.h"
34#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
40#include "llvm/Pass.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040044
David Neto85082642018-03-24 06:55:20 -070045#include "spirv/1.0/spirv.hpp"
David Neto118188e2018-08-24 11:27:54 -040046
David Neto85082642018-03-24 06:55:20 -070047#include "clspv/AddressSpace.h"
David Neto118188e2018-08-24 11:27:54 -040048#include "clspv/Option.h"
49#include "clspv/Passes.h"
David Neto85082642018-03-24 06:55:20 -070050#include "clspv/spirv_c_strings.hpp"
51#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040052
David Neto4feb7a42017-10-06 17:29:42 -040053#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070054#include "ConstantEmitter.h"
Alan Baker202c8c72018-08-13 13:47:44 -040055#include "Constants.h"
David Neto78383442018-06-15 20:31:56 -040056#include "DescriptorCounter.h"
David Neto48f56a42017-10-06 16:44:25 -040057
David Neto22f144c2017-06-12 14:26:21 -040058#if defined(_MSC_VER)
59#pragma warning(pop)
60#endif
61
62using namespace llvm;
63using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040064using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040065
66namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040067
David Neto862b7d82018-06-14 18:48:37 -040068cl::opt<bool> ShowResourceVars("show-rv", cl::init(false), cl::Hidden,
69 cl::desc("Show resource variable creation"));
70
71// These hacks exist to help transition code generation algorithms
72// without making huge noise in detailed test output.
73const bool Hack_generate_runtime_array_stride_early = true;
74
David Neto3fbb4072017-10-16 11:28:14 -040075// The value of 1/pi. This value is from MSDN
76// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
77const double kOneOverPi = 0.318309886183790671538;
78const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
79
David Netoab03f432017-11-03 17:00:44 -040080const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
81
David Neto22f144c2017-06-12 14:26:21 -040082enum SPIRVOperandType {
83 NUMBERID,
84 LITERAL_INTEGER,
85 LITERAL_STRING,
86 LITERAL_FLOAT
87};
88
89struct SPIRVOperand {
90 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
91 : Type(Ty), LiteralNum(1, Num) {}
92 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
93 : Type(Ty), LiteralStr(Str) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
97 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
98
99 SPIRVOperandType getType() { return Type; };
100 uint32_t getNumID() { return LiteralNum[0]; };
101 std::string getLiteralStr() { return LiteralStr; };
102 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
103
David Neto87846742018-04-11 17:36:22 -0400104 uint32_t GetNumWords() const {
105 switch (Type) {
106 case NUMBERID:
107 return 1;
108 case LITERAL_INTEGER:
109 case LITERAL_FLOAT:
David Netoee2660d2018-06-28 16:31:29 -0400110 return uint32_t(LiteralNum.size());
David Neto87846742018-04-11 17:36:22 -0400111 case LITERAL_STRING:
112 // Account for the terminating null character.
David Netoee2660d2018-06-28 16:31:29 -0400113 return uint32_t((LiteralStr.size() + 4) / 4);
David Neto87846742018-04-11 17:36:22 -0400114 }
115 llvm_unreachable("Unhandled case in SPIRVOperand::GetNumWords()");
116 }
117
David Neto22f144c2017-06-12 14:26:21 -0400118private:
119 SPIRVOperandType Type;
120 std::string LiteralStr;
121 SmallVector<uint32_t, 4> LiteralNum;
122};
123
David Netoc6f3ab22018-04-06 18:02:31 -0400124class SPIRVOperandList {
125public:
126 SPIRVOperandList() {}
127 SPIRVOperandList(const SPIRVOperandList& other) = delete;
128 SPIRVOperandList(SPIRVOperandList&& other) {
129 contents_ = std::move(other.contents_);
130 other.contents_.clear();
131 }
132 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
133 : contents_(init.begin(), init.end()) {}
134 operator ArrayRef<SPIRVOperand *>() { return contents_; }
135 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
136 void clear() { contents_.clear();}
137 size_t size() const { return contents_.size(); }
138 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
139
David Neto87846742018-04-11 17:36:22 -0400140 const SmallVector<SPIRVOperand *, 8> &getOperands() const {
141 return contents_;
142 }
143
David Netoc6f3ab22018-04-06 18:02:31 -0400144private:
145 SmallVector<SPIRVOperand *,8> contents_;
146};
147
148SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
149 list.push_back(elem);
150 return list;
151}
152
153SPIRVOperand* MkNum(uint32_t num) {
154 return new SPIRVOperand(LITERAL_INTEGER, num);
155}
David Neto257c3892018-04-11 13:19:45 -0400156SPIRVOperand* MkInteger(ArrayRef<uint32_t> num_vec) {
157 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
158}
159SPIRVOperand* MkFloat(ArrayRef<uint32_t> num_vec) {
160 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
161}
David Netoc6f3ab22018-04-06 18:02:31 -0400162SPIRVOperand* MkId(uint32_t id) {
163 return new SPIRVOperand(NUMBERID, id);
164}
David Neto257c3892018-04-11 13:19:45 -0400165SPIRVOperand* MkString(StringRef str) {
166 return new SPIRVOperand(LITERAL_STRING, str);
167}
David Netoc6f3ab22018-04-06 18:02:31 -0400168
David Neto22f144c2017-06-12 14:26:21 -0400169struct SPIRVInstruction {
David Neto87846742018-04-11 17:36:22 -0400170 // Create an instruction with an opcode and no result ID, and with the given
171 // operands. This computes its own word count.
172 explicit SPIRVInstruction(spv::Op Opc, ArrayRef<SPIRVOperand *> Ops)
173 : WordCount(1), Opcode(static_cast<uint16_t>(Opc)), ResultID(0),
174 Operands(Ops.begin(), Ops.end()) {
175 for (auto *operand : Ops) {
David Netoee2660d2018-06-28 16:31:29 -0400176 WordCount += uint16_t(operand->GetNumWords());
David Neto87846742018-04-11 17:36:22 -0400177 }
178 }
179 // Create an instruction with an opcode and a no-zero result ID, and
180 // with the given operands. This computes its own word count.
181 explicit SPIRVInstruction(spv::Op Opc, uint32_t ResID,
David Neto22f144c2017-06-12 14:26:21 -0400182 ArrayRef<SPIRVOperand *> Ops)
David Neto87846742018-04-11 17:36:22 -0400183 : WordCount(2), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
184 Operands(Ops.begin(), Ops.end()) {
185 if (ResID == 0) {
186 llvm_unreachable("Result ID of 0 was provided");
187 }
188 for (auto *operand : Ops) {
189 WordCount += operand->GetNumWords();
190 }
191 }
David Neto22f144c2017-06-12 14:26:21 -0400192
David Netoee2660d2018-06-28 16:31:29 -0400193 uint32_t getWordCount() const { return WordCount; }
David Neto22f144c2017-06-12 14:26:21 -0400194 uint16_t getOpcode() const { return Opcode; }
195 uint32_t getResultID() const { return ResultID; }
196 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
197
198private:
David Netoee2660d2018-06-28 16:31:29 -0400199 uint32_t WordCount; // Check the 16-bit bound at code generation time.
David Neto22f144c2017-06-12 14:26:21 -0400200 uint16_t Opcode;
201 uint32_t ResultID;
202 SmallVector<SPIRVOperand *, 4> Operands;
203};
204
205struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400206 typedef DenseMap<Type *, uint32_t> TypeMapType;
207 typedef UniqueVector<Type *> TypeList;
208 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400209 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400210 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
211 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
David Neto87846742018-04-11 17:36:22 -0400212 // A vector of tuples, each of which is:
213 // - the LLVM instruction that we will later generate SPIR-V code for
214 // - where the SPIR-V instruction should be inserted
215 // - the result ID of the SPIR-V instruction
David Neto22f144c2017-06-12 14:26:21 -0400216 typedef std::vector<
217 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
218 DeferredInstVecType;
219 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
220 GlobalConstFuncMapType;
221
David Neto44795152017-07-13 15:45:28 -0400222 explicit SPIRVProducerPass(
223 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
224 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
225 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400226 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400227 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400228 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400229 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400230 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
David Neto85082642018-03-24 06:55:20 -0700231 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0),
Alan Baker202c8c72018-08-13 13:47:44 -0400232 max_local_spec_id_(0), constant_i32_zero_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400233
234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<DominatorTreeWrapperPass>();
236 AU.addRequired<LoopInfoWrapperPass>();
237 }
238
239 virtual bool runOnModule(Module &module) override;
240
241 // output the SPIR-V header block
242 void outputHeader();
243
244 // patch the SPIR-V header block
245 void patchHeader();
246
247 uint32_t lookupType(Type *Ty) {
248 if (Ty->isPointerTy() &&
249 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
250 auto PointeeTy = Ty->getPointerElementType();
251 if (PointeeTy->isStructTy() &&
252 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
253 Ty = PointeeTy;
254 }
255 }
256
David Neto862b7d82018-06-14 18:48:37 -0400257 auto where = TypeMap.find(Ty);
258 if (where == TypeMap.end()) {
259 if (Ty) {
260 errs() << "Unhandled type " << *Ty << "\n";
261 } else {
262 errs() << "Unhandled type (null)\n";
263 }
David Netoe439d702018-03-23 13:14:08 -0700264 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400265 }
266
David Neto862b7d82018-06-14 18:48:37 -0400267 return where->second;
David Neto22f144c2017-06-12 14:26:21 -0400268 }
269 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
270 TypeList &getTypeList() { return Types; };
271 ValueList &getConstantList() { return Constants; };
272 ValueMapType &getValueMap() { return ValueMap; }
273 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
274 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
David Neto22f144c2017-06-12 14:26:21 -0400275 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
276 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
277 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
278 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
279 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
280 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
281 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400282 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400283 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
284 return GlobalConstFuncTypeMap;
285 }
286 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
287 return GlobalConstArgumentSet;
288 }
David Neto85082642018-03-24 06:55:20 -0700289 TypeList &getTypesNeedingArrayStride() {
290 return TypesNeedingArrayStride;
David Neto1a1a0582017-07-07 12:01:44 -0400291 }
David Neto22f144c2017-06-12 14:26:21 -0400292
David Netoc6f3ab22018-04-06 18:02:31 -0400293 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
David Neto862b7d82018-06-14 18:48:37 -0400294 // Populate GlobalConstFuncTypeMap. Also, if module-scope __constant will *not*
295 // be converted to a storage buffer, replace each such global variable with
296 // one in the storage class expecgted by SPIR-V.
297 void FindGlobalConstVars(Module &M, const DataLayout &DL);
298 // Populate ResourceVarInfoList, FunctionToResourceVarsMap, and
299 // ModuleOrderedResourceVars.
300 void FindResourceVars(Module &M, const DataLayout &DL);
Alan Baker202c8c72018-08-13 13:47:44 -0400301 void FindWorkgroupVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400302 bool FindExtInst(Module &M);
303 void FindTypePerGlobalVar(GlobalVariable &GV);
304 void FindTypePerFunc(Function &F);
David Neto862b7d82018-06-14 18:48:37 -0400305 void FindTypesForSamplerMap(Module &M);
306 void FindTypesForResourceVars(Module &M);
David Neto19a1bad2017-08-25 15:01:41 -0400307 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
308 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400309 void FindType(Type *Ty);
310 void FindConstantPerGlobalVar(GlobalVariable &GV);
311 void FindConstantPerFunc(Function &F);
312 void FindConstant(Value *V);
313 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400314 // Generates instructions for SPIR-V types corresponding to the LLVM types
315 // saved in the |Types| member. A type follows its subtypes. IDs are
316 // allocated sequentially starting with the current value of nextID, and
317 // with a type following its subtypes. Also updates nextID to just beyond
318 // the last generated ID.
Alan Bakerfcda9482018-10-02 17:09:59 -0400319 void GenerateSPIRVTypes(LLVMContext& context, Module &module);
David Neto22f144c2017-06-12 14:26:21 -0400320 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400321 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400322 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400323 void GenerateWorkgroupVars();
David Neto862b7d82018-06-14 18:48:37 -0400324 // Generate descriptor map entries for resource variables associated with
325 // arguments to F.
326 void GenerateDescriptorMapInfo(const DataLayout& DL, Function& F);
David Neto22f144c2017-06-12 14:26:21 -0400327 void GenerateSamplers(Module &M);
David Neto862b7d82018-06-14 18:48:37 -0400328 // Generate OpVariables for %clspv.resource.var.* calls.
329 void GenerateResourceVars(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400330 void GenerateFuncPrologue(Function &F);
331 void GenerateFuncBody(Function &F);
David Netob6e2e062018-04-25 10:32:06 -0400332 void GenerateEntryPointInitialStores();
David Neto22f144c2017-06-12 14:26:21 -0400333 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
334 spv::Op GetSPIRVCastOpcode(Instruction &I);
335 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
336 void GenerateInstruction(Instruction &I);
337 void GenerateFuncEpilogue();
338 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400339 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400340 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400341 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
342 // have been created.
343 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400344 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
David Neto862b7d82018-06-14 18:48:37 -0400345 spv::StorageClass GetStorageClassForArgKind(clspv::ArgKind arg_kind) const;
David Neto22f144c2017-06-12 14:26:21 -0400346 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400347 // Returns the GLSL extended instruction enum that the given function
348 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400349 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400350 // Returns the GLSL extended instruction enum indirectly used by the given
351 // function. That is, to implement the given function, we use an extended
352 // instruction plus one more instruction. If none, then returns the 0 value,
353 // i.e. GLSLstd4580Bad.
354 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
355 // Returns the single GLSL extended instruction used directly or
356 // indirectly by the given function call.
357 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400358 void PrintResID(SPIRVInstruction *Inst);
359 void PrintOpcode(SPIRVInstruction *Inst);
360 void PrintOperand(SPIRVOperand *Op);
361 void PrintCapability(SPIRVOperand *Op);
362 void PrintExtInst(SPIRVOperand *Op);
363 void PrintAddrModel(SPIRVOperand *Op);
364 void PrintMemModel(SPIRVOperand *Op);
365 void PrintExecModel(SPIRVOperand *Op);
366 void PrintExecMode(SPIRVOperand *Op);
367 void PrintSourceLanguage(SPIRVOperand *Op);
368 void PrintFuncCtrl(SPIRVOperand *Op);
369 void PrintStorageClass(SPIRVOperand *Op);
370 void PrintDecoration(SPIRVOperand *Op);
371 void PrintBuiltIn(SPIRVOperand *Op);
372 void PrintSelectionControl(SPIRVOperand *Op);
373 void PrintLoopControl(SPIRVOperand *Op);
374 void PrintDimensionality(SPIRVOperand *Op);
375 void PrintImageFormat(SPIRVOperand *Op);
376 void PrintMemoryAccess(SPIRVOperand *Op);
377 void PrintImageOperandsType(SPIRVOperand *Op);
378 void WriteSPIRVAssembly();
379 void WriteOneWord(uint32_t Word);
380 void WriteResultID(SPIRVInstruction *Inst);
381 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
382 void WriteOperand(SPIRVOperand *Op);
383 void WriteSPIRVBinary();
384
Alan Baker9bf93fb2018-08-28 16:59:26 -0400385 // Returns true if |type| is compatible with OpConstantNull.
386 bool IsTypeNullable(const Type* type) const;
387
Alan Bakerfcda9482018-10-02 17:09:59 -0400388 // Populate UBO remapped type maps.
389 void PopulateUBOTypeMaps(Module &module);
390
391 // Wrapped methods of DataLayout accessors. If |type| was remapped for UBOs,
392 // uses the internal map, otherwise it falls back on the data layout.
393 uint64_t GetTypeSizeInBits(Type *type, const DataLayout &DL);
394 uint64_t GetTypeStoreSize(Type *type, const DataLayout &DL);
395 uint64_t GetTypeAllocSize(Type *type, const DataLayout &DL);
396
David Neto22f144c2017-06-12 14:26:21 -0400397private:
398 static char ID;
David Neto44795152017-07-13 15:45:28 -0400399 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400400 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400401
402 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
403 // convert to other formats on demand?
404
405 // When emitting a C initialization list, the WriteSPIRVBinary method
406 // will actually write its words to this vector via binaryTempOut.
407 SmallVector<char, 100> binaryTempUnderlyingVector;
408 raw_svector_ostream binaryTempOut;
409
410 // Binary output writes to this stream, which might be |out| or
411 // |binaryTempOut|. It's the latter when we really want to write a C
412 // initializer list.
413 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400414 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400415 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400416 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400417 uint64_t patchBoundOffset;
418 uint32_t nextID;
419
David Neto19a1bad2017-08-25 15:01:41 -0400420 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400421 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400422 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400423 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400424 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400425 TypeList Types;
426 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400427 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400428 ValueMapType ValueMap;
429 ValueMapType AllocatedValueMap;
430 SPIRVInstructionList SPIRVInsts;
David Neto862b7d82018-06-14 18:48:37 -0400431
David Neto22f144c2017-06-12 14:26:21 -0400432 EntryPointVecType EntryPointVec;
433 DeferredInstVecType DeferredInstVec;
434 ValueList EntryPointInterfacesVec;
435 uint32_t OpExtInstImportID;
436 std::vector<uint32_t> BuiltinDimensionVec;
437 bool HasVariablePointers;
438 Type *SamplerTy;
David Neto862b7d82018-06-14 18:48:37 -0400439 DenseMap<unsigned,uint32_t> SamplerMapIndexToIDMap;
David Netoc77d9e22018-03-24 06:30:28 -0700440
441 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700442 // will map F's type to (G, index of the parameter), where in a first phase
443 // G is F's type. During FindTypePerFunc, G will be changed to F's type
444 // but replacing the pointer-to-constant parameter with
445 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700446 // TODO(dneto): This doesn't seem general enough? A function might have
447 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400448 GlobalConstFuncMapType GlobalConstFuncTypeMap;
449 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400450 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700451 // or array types, and which point into transparent memory (StorageBuffer
452 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400453 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700454 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400455
456 // This is truly ugly, but works around what look like driver bugs.
457 // For get_local_size, an earlier part of the flow has created a module-scope
458 // variable in Private address space to hold the value for the workgroup
459 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
460 // When this is present, save the IDs of the initializer value and variable
461 // in these two variables. We only ever do a vector load from it, and
462 // when we see one of those, substitute just the value of the intializer.
463 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700464 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400465 uint32_t WorkgroupSizeValueID;
466 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400467
David Neto862b7d82018-06-14 18:48:37 -0400468 // Bookkeeping for mapping kernel arguments to resource variables.
469 struct ResourceVarInfo {
470 ResourceVarInfo(int index_arg, unsigned set_arg, unsigned binding_arg,
471 Function *fn, clspv::ArgKind arg_kind_arg)
472 : index(index_arg), descriptor_set(set_arg), binding(binding_arg),
473 var_fn(fn), arg_kind(arg_kind_arg),
474 addr_space(fn->getReturnType()->getPointerAddressSpace()) {}
475 const int index; // Index into ResourceVarInfoList
476 const unsigned descriptor_set;
477 const unsigned binding;
478 Function *const var_fn; // The @clspv.resource.var.* function.
479 const clspv::ArgKind arg_kind;
480 const unsigned addr_space; // The LLVM address space
481 // The SPIR-V ID of the OpVariable. Not populated at construction time.
482 uint32_t var_id = 0;
483 };
484 // A list of resource var info. Each one correponds to a module-scope
485 // resource variable we will have to create. Resource var indices are
486 // indices into this vector.
487 SmallVector<std::unique_ptr<ResourceVarInfo>, 8> ResourceVarInfoList;
488 // This is a vector of pointers of all the resource vars, but ordered by
489 // kernel function, and then by argument.
490 UniqueVector<ResourceVarInfo*> ModuleOrderedResourceVars;
491 // Map a function to the ordered list of resource variables it uses, one for
492 // each argument. If an argument does not use a resource variable, it
493 // will have a null pointer entry.
494 using FunctionToResourceVarsMapType =
495 DenseMap<Function *, SmallVector<ResourceVarInfo *, 8>>;
496 FunctionToResourceVarsMapType FunctionToResourceVarsMap;
497
498 // What LLVM types map to SPIR-V types needing layout? These are the
499 // arrays and structures supporting storage buffers and uniform buffers.
500 TypeList TypesNeedingLayout;
501 // What LLVM struct types map to a SPIR-V struct type with Block decoration?
502 UniqueVector<StructType *> StructTypesNeedingBlock;
503 // For a call that represents a load from an opaque type (samplers, images),
504 // map it to the variable id it should load from.
505 DenseMap<CallInst *, uint32_t> ResourceVarDeferredLoadCalls;
David Neto85082642018-03-24 06:55:20 -0700506
Alan Baker202c8c72018-08-13 13:47:44 -0400507 // One larger than the maximum used SpecId for pointer-to-local arguments.
508 int max_local_spec_id_;
David Netoc6f3ab22018-04-06 18:02:31 -0400509 // An ordered list of the kernel arguments of type pointer-to-local.
Alan Baker202c8c72018-08-13 13:47:44 -0400510 using LocalArgList = SmallVector<Argument*, 8>;
David Netoc6f3ab22018-04-06 18:02:31 -0400511 LocalArgList LocalArgs;
512 // Information about a pointer-to-local argument.
513 struct LocalArgInfo {
514 // The SPIR-V ID of the array variable.
515 uint32_t variable_id;
516 // The element type of the
517 Type* elem_type;
518 // The ID of the array type.
519 uint32_t array_size_id;
520 // The ID of the array type.
521 uint32_t array_type_id;
522 // The ID of the pointer to the array type.
523 uint32_t ptr_array_type_id;
David Netoc6f3ab22018-04-06 18:02:31 -0400524 // The specialization constant ID of the array size.
525 int spec_id;
526 };
Alan Baker202c8c72018-08-13 13:47:44 -0400527 // A mapping from Argument to its assigned SpecId.
528 DenseMap<const Argument*, int> LocalArgSpecIds;
529 // A mapping from SpecId to its LocalArgInfo.
530 DenseMap<int, LocalArgInfo> LocalSpecIdInfoMap;
Alan Bakerfcda9482018-10-02 17:09:59 -0400531 // A mapping from a remapped type to its real offsets.
532 DenseMap<Type*, std::vector<uint32_t>> RemappedUBOTypeOffsets;
533 // A mapping from a remapped type to its real sizes.
534 DenseMap<Type*, std::tuple<uint64_t, uint64_t, uint64_t>> RemappedUBOTypeSizes;
David Neto257c3892018-04-11 13:19:45 -0400535
536 // The ID of 32-bit integer zero constant. This is only valid after
537 // GenerateSPIRVConstants has run.
538 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400539};
540
541char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400542
David Neto22f144c2017-06-12 14:26:21 -0400543}
544
545namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400546ModulePass *
547createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
548 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
549 bool outputAsm, bool outputCInitList) {
550 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
551 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400552}
David Netoc2c368d2017-06-30 16:50:17 -0400553} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400554
555bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400556 binaryOut = outputCInitList ? &binaryTempOut : &out;
557
David Neto257c3892018-04-11 13:19:45 -0400558 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
559
Alan Bakerfcda9482018-10-02 17:09:59 -0400560 PopulateUBOTypeMaps(module);
561
David Neto22f144c2017-06-12 14:26:21 -0400562 // SPIR-V always begins with its header information
563 outputHeader();
564
David Netoc6f3ab22018-04-06 18:02:31 -0400565 const DataLayout &DL = module.getDataLayout();
566
David Neto22f144c2017-06-12 14:26:21 -0400567 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400568 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400569
David Neto22f144c2017-06-12 14:26:21 -0400570 // Collect information on global variables too.
571 for (GlobalVariable &GV : module.globals()) {
572 // If the GV is one of our special __spirv_* variables, remove the
573 // initializer as it was only placed there to force LLVM to not throw the
574 // value away.
575 if (GV.getName().startswith("__spirv_")) {
576 GV.setInitializer(nullptr);
577 }
578
579 // Collect types' information from global variable.
580 FindTypePerGlobalVar(GV);
581
582 // Collect constant information from global variable.
583 FindConstantPerGlobalVar(GV);
584
585 // If the variable is an input, entry points need to know about it.
586 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400587 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400588 }
589 }
590
591 // If there are extended instructions, generate OpExtInstImport.
592 if (FindExtInst(module)) {
593 GenerateExtInstImport();
594 }
595
596 // Generate SPIRV instructions for types.
Alan Bakerfcda9482018-10-02 17:09:59 -0400597 GenerateSPIRVTypes(module.getContext(), module);
David Neto22f144c2017-06-12 14:26:21 -0400598
599 // Generate SPIRV constants.
600 GenerateSPIRVConstants();
601
602 // If we have a sampler map, we might have literal samplers to generate.
603 if (0 < getSamplerMap().size()) {
604 GenerateSamplers(module);
605 }
606
607 // Generate SPIRV variables.
608 for (GlobalVariable &GV : module.globals()) {
609 GenerateGlobalVar(GV);
610 }
David Neto862b7d82018-06-14 18:48:37 -0400611 GenerateResourceVars(module);
David Netoc6f3ab22018-04-06 18:02:31 -0400612 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400613
614 // Generate SPIRV instructions for each function.
615 for (Function &F : module) {
616 if (F.isDeclaration()) {
617 continue;
618 }
619
David Neto862b7d82018-06-14 18:48:37 -0400620 GenerateDescriptorMapInfo(DL, F);
621
David Neto22f144c2017-06-12 14:26:21 -0400622 // Generate Function Prologue.
623 GenerateFuncPrologue(F);
624
625 // Generate SPIRV instructions for function body.
626 GenerateFuncBody(F);
627
628 // Generate Function Epilogue.
629 GenerateFuncEpilogue();
630 }
631
632 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400633 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400634
635 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400636 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400637
638 if (outputAsm) {
639 WriteSPIRVAssembly();
640 } else {
641 WriteSPIRVBinary();
642 }
643
644 // We need to patch the SPIR-V header to set bound correctly.
645 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400646
647 if (outputCInitList) {
648 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400649 std::ostringstream os;
650
David Neto57fb0b92017-08-04 15:35:09 -0400651 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400652 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400653 os << ",\n";
654 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400655 first = false;
656 };
657
658 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400659 const std::string str(binaryTempOut.str());
660 for (unsigned i = 0; i < str.size(); i += 4) {
661 const uint32_t a = static_cast<unsigned char>(str[i]);
662 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
663 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
664 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
665 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400666 }
667 os << "}\n";
668 out << os.str();
669 }
670
David Neto22f144c2017-06-12 14:26:21 -0400671 return false;
672}
673
674void SPIRVProducerPass::outputHeader() {
675 if (outputAsm) {
676 // for ASM output the header goes into 5 comments at the beginning of the
677 // file
678 out << "; SPIR-V\n";
679
680 // the major version number is in the 2nd highest byte
681 const uint32_t major = (spv::Version >> 16) & 0xFF;
682
683 // the minor version number is in the 2nd lowest byte
684 const uint32_t minor = (spv::Version >> 8) & 0xFF;
685 out << "; Version: " << major << "." << minor << "\n";
686
687 // use Codeplay's vendor ID
688 out << "; Generator: Codeplay; 0\n";
689
690 out << "; Bound: ";
691
692 // we record where we need to come back to and patch in the bound value
693 patchBoundOffset = out.tell();
694
695 // output one space per digit for the max size of a 32 bit unsigned integer
696 // (which is the maximum ID we could possibly be using)
697 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
698 out << " ";
699 }
700
701 out << "\n";
702
703 out << "; Schema: 0\n";
704 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400705 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400706 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400707 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400708 sizeof(spv::Version));
709
710 // use Codeplay's vendor ID
711 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400712 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400713
714 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400715 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400716
717 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400718 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400719
720 // output the schema (reserved for use and must be 0)
721 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400722 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400723 }
724}
725
726void SPIRVProducerPass::patchHeader() {
727 if (outputAsm) {
728 // get the string representation of the max bound used (nextID will be the
729 // max ID used)
730 auto asString = std::to_string(nextID);
731 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
732 } else {
733 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400734 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
735 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400736 }
737}
738
David Netoc6f3ab22018-04-06 18:02:31 -0400739void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400740 // This function generates LLVM IR for function such as global variable for
741 // argument, constant and pointer type for argument access. These information
742 // is artificial one because we need Vulkan SPIR-V output. This function is
743 // executed ahead of FindType and FindConstant.
David Neto22f144c2017-06-12 14:26:21 -0400744 LLVMContext &Context = M.getContext();
745
David Neto862b7d82018-06-14 18:48:37 -0400746 FindGlobalConstVars(M, DL);
David Neto5c22a252018-03-15 16:07:41 -0400747
David Neto862b7d82018-06-14 18:48:37 -0400748 FindResourceVars(M, DL);
David Neto22f144c2017-06-12 14:26:21 -0400749
750 bool HasWorkGroupBuiltin = false;
751 for (GlobalVariable &GV : M.globals()) {
752 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
753 if (spv::BuiltInWorkgroupSize == BuiltinType) {
754 HasWorkGroupBuiltin = true;
755 }
756 }
757
David Neto862b7d82018-06-14 18:48:37 -0400758 FindTypesForSamplerMap(M);
759 FindTypesForResourceVars(M);
Alan Baker202c8c72018-08-13 13:47:44 -0400760 FindWorkgroupVars(M);
David Neto22f144c2017-06-12 14:26:21 -0400761
David Neto862b7d82018-06-14 18:48:37 -0400762 // TODO(dneto): Delete the next 3 vars.
763
764 //#error "remove arg handling from this code"
David Neto26aaf622017-10-23 18:11:53 -0400765 // Map kernel functions to their ordinal number in the compilation unit.
766 UniqueVector<Function*> KernelOrdinal;
767
768 // Map the global variables created for kernel args to their creation
769 // order.
770 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
771
David Neto862b7d82018-06-14 18:48:37 -0400772 // For each kernel argument type, record the kernel arg global resource
773 // variables generated for that type, the function in which that variable
774 // was most recently used, and the binding number it took. For
775 // reproducibility, we track things by ordinal number (rather than pointer),
776 // and we use a std::set rather than DenseSet since std::set maintains an
777 // ordering. Each tuple is the ordinals of the kernel function, the binding
778 // number, and the ordinal of the kernal-arg-var.
David Neto26aaf622017-10-23 18:11:53 -0400779 //
780 // This table lets us reuse module-scope StorageBuffer variables between
781 // different kernels.
782 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
783 GVarsForType;
784
David Neto862b7d82018-06-14 18:48:37 -0400785 // These function calls need a <2 x i32> as an intermediate result but not
786 // the final result.
787 std::unordered_set<std::string> NeedsIVec2{
788 "_Z15get_image_width14ocl_image2d_ro",
789 "_Z15get_image_width14ocl_image2d_wo",
790 "_Z16get_image_height14ocl_image2d_ro",
791 "_Z16get_image_height14ocl_image2d_wo",
792 };
793
David Neto22f144c2017-06-12 14:26:21 -0400794 for (Function &F : M) {
795 // Handle kernel function first.
796 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
797 continue;
798 }
David Neto26aaf622017-10-23 18:11:53 -0400799 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400800
801 for (BasicBlock &BB : F) {
802 for (Instruction &I : BB) {
803 if (I.getOpcode() == Instruction::ZExt ||
804 I.getOpcode() == Instruction::SExt ||
805 I.getOpcode() == Instruction::UIToFP) {
806 // If there is zext with i1 type, it will be changed to OpSelect. The
807 // OpSelect needs constant 0 and 1 so the constants are added here.
808
809 auto OpTy = I.getOperand(0)->getType();
810
Kévin Petit24272b62018-10-18 19:16:12 +0000811 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400812 if (I.getOpcode() == Instruction::ZExt) {
813 APInt One(32, 1);
814 FindConstant(Constant::getNullValue(I.getType()));
815 FindConstant(Constant::getIntegerValue(I.getType(), One));
816 } else if (I.getOpcode() == Instruction::SExt) {
817 APInt MinusOne(32, UINT64_MAX, true);
818 FindConstant(Constant::getNullValue(I.getType()));
819 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
820 } else {
821 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
822 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
823 }
824 }
825 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
David Neto862b7d82018-06-14 18:48:37 -0400826 StringRef callee_name = Call->getCalledFunction()->getName();
David Neto22f144c2017-06-12 14:26:21 -0400827
828 // Handle image type specially.
David Neto862b7d82018-06-14 18:48:37 -0400829 if (callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400830 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
David Neto862b7d82018-06-14 18:48:37 -0400831 callee_name.equals(
David Neto22f144c2017-06-12 14:26:21 -0400832 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
833 TypeMapType &OpImageTypeMap = getImageTypeMap();
834 Type *ImageTy =
835 Call->getArgOperand(0)->getType()->getPointerElementType();
836 OpImageTypeMap[ImageTy] = 0;
837
838 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
839 }
David Neto5c22a252018-03-15 16:07:41 -0400840
David Neto862b7d82018-06-14 18:48:37 -0400841 if (NeedsIVec2.find(callee_name) != NeedsIVec2.end()) {
David Neto5c22a252018-03-15 16:07:41 -0400842 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
843 }
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845 }
846 }
847
David Neto22f144c2017-06-12 14:26:21 -0400848 if (const MDNode *MD =
849 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
850 // We generate constants if the WorkgroupSize builtin is being used.
851 if (HasWorkGroupBuiltin) {
852 // Collect constant information for work group size.
853 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
854 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
855 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
856 }
857 }
858
David Neto22f144c2017-06-12 14:26:21 -0400859 // Collect types' information from function.
860 FindTypePerFunc(F);
861
862 // Collect constant information from function.
863 FindConstantPerFunc(F);
864 }
865
866 for (Function &F : M) {
867 // Handle non-kernel functions.
868 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
869 continue;
870 }
871
872 for (BasicBlock &BB : F) {
873 for (Instruction &I : BB) {
874 if (I.getOpcode() == Instruction::ZExt ||
875 I.getOpcode() == Instruction::SExt ||
876 I.getOpcode() == Instruction::UIToFP) {
877 // If there is zext with i1 type, it will be changed to OpSelect. The
878 // OpSelect needs constant 0 and 1 so the constants are added here.
879
880 auto OpTy = I.getOperand(0)->getType();
881
Kévin Petit24272b62018-10-18 19:16:12 +0000882 if (OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -0400883 if (I.getOpcode() == Instruction::ZExt) {
884 APInt One(32, 1);
885 FindConstant(Constant::getNullValue(I.getType()));
886 FindConstant(Constant::getIntegerValue(I.getType(), One));
887 } else if (I.getOpcode() == Instruction::SExt) {
888 APInt MinusOne(32, UINT64_MAX, true);
889 FindConstant(Constant::getNullValue(I.getType()));
890 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
891 } else {
892 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
893 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
894 }
895 }
896 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
897 Function *Callee = Call->getCalledFunction();
898
899 // Handle image type specially.
900 if (Callee->getName().equals(
901 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
902 Callee->getName().equals(
903 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
904 TypeMapType &OpImageTypeMap = getImageTypeMap();
905 Type *ImageTy =
906 Call->getArgOperand(0)->getType()->getPointerElementType();
907 OpImageTypeMap[ImageTy] = 0;
908
909 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
910 }
911 }
912 }
913 }
914
915 if (M.getTypeByName("opencl.image2d_ro_t") ||
916 M.getTypeByName("opencl.image2d_wo_t") ||
917 M.getTypeByName("opencl.image3d_ro_t") ||
918 M.getTypeByName("opencl.image3d_wo_t")) {
919 // Assume Image type's sampled type is float type.
920 FindType(Type::getFloatTy(Context));
921 }
922
923 // Collect types' information from function.
924 FindTypePerFunc(F);
925
926 // Collect constant information from function.
927 FindConstantPerFunc(F);
928 }
929}
930
David Neto862b7d82018-06-14 18:48:37 -0400931void SPIRVProducerPass::FindGlobalConstVars(Module &M, const DataLayout &DL) {
932 SmallVector<GlobalVariable *, 8> GVList;
933 SmallVector<GlobalVariable *, 8> DeadGVList;
934 for (GlobalVariable &GV : M.globals()) {
935 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
936 if (GV.use_empty()) {
937 DeadGVList.push_back(&GV);
938 } else {
939 GVList.push_back(&GV);
940 }
941 }
942 }
943
944 // Remove dead global __constant variables.
945 for (auto GV : DeadGVList) {
946 GV->eraseFromParent();
947 }
948 DeadGVList.clear();
949
950 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
951 // For now, we only support a single storage buffer.
952 if (GVList.size() > 0) {
953 assert(GVList.size() == 1);
954 const auto *GV = GVList[0];
955 const auto constants_byte_size =
Alan Bakerfcda9482018-10-02 17:09:59 -0400956 (GetTypeSizeInBits(GV->getInitializer()->getType(), DL)) / 8;
David Neto862b7d82018-06-14 18:48:37 -0400957 const size_t kConstantMaxSize = 65536;
958 if (constants_byte_size > kConstantMaxSize) {
959 outs() << "Max __constant capacity of " << kConstantMaxSize
960 << " bytes exceeded: " << constants_byte_size << " bytes used\n";
961 llvm_unreachable("Max __constant capacity exceeded");
962 }
963 }
964 } else {
965 // Change global constant variable's address space to ModuleScopePrivate.
966 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
967 for (auto GV : GVList) {
968 // Create new gv with ModuleScopePrivate address space.
969 Type *NewGVTy = GV->getType()->getPointerElementType();
970 GlobalVariable *NewGV = new GlobalVariable(
971 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
972 nullptr, GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
973 NewGV->takeName(GV);
974
975 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
976 SmallVector<User *, 8> CandidateUsers;
977
978 auto record_called_function_type_as_user =
979 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
980 // Find argument index.
981 unsigned index = 0;
982 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
983 if (gv == call->getOperand(i)) {
984 // TODO(dneto): Should we break here?
985 index = i;
986 }
987 }
988
989 // Record function type with global constant.
990 GlobalConstFuncTyMap[call->getFunctionType()] =
991 std::make_pair(call->getFunctionType(), index);
992 };
993
994 for (User *GVU : GVUsers) {
995 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
996 record_called_function_type_as_user(GV, Call);
997 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
998 // Check GEP users.
999 for (User *GEPU : GEP->users()) {
1000 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
1001 record_called_function_type_as_user(GEP, GEPCall);
1002 }
1003 }
1004 }
1005
1006 CandidateUsers.push_back(GVU);
1007 }
1008
1009 for (User *U : CandidateUsers) {
1010 // Update users of gv with new gv.
1011 U->replaceUsesOfWith(GV, NewGV);
1012 }
1013
1014 // Delete original gv.
1015 GV->eraseFromParent();
1016 }
1017 }
1018}
1019
1020void SPIRVProducerPass::FindResourceVars(Module &M, const DataLayout &DL) {
1021 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1022 ValueMapType &VMap = getValueMap();
1023
1024 ResourceVarInfoList.clear();
1025 FunctionToResourceVarsMap.clear();
1026 ModuleOrderedResourceVars.reset();
1027 // Normally, there is one resource variable per clspv.resource.var.*
1028 // function, since that is unique'd by arg type and index. By design,
1029 // we can share these resource variables across kernels because all
1030 // kernels use the same descriptor set.
1031 //
1032 // But if the user requested distinct descriptor sets per kernel, then
1033 // the descriptor allocator has made different (set,binding) pairs for
1034 // the same (type,arg_index) pair. Since we can decorate a resource
1035 // variable with only exactly one DescriptorSet and Binding, we are
1036 // forced in this case to make distinct resource variables whenever
1037 // the same clspv.reource.var.X function is seen with disintct
1038 // (set,binding) values.
1039 const bool always_distinct_sets =
1040 clspv::Option::DistinctKernelDescriptorSets();
1041 for (Function &F : M) {
1042 // Rely on the fact the resource var functions have a stable ordering
1043 // in the module.
Alan Baker202c8c72018-08-13 13:47:44 -04001044 if (F.getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001045 // Find all calls to this function with distinct set and binding pairs.
1046 // Save them in ResourceVarInfoList.
1047
1048 // Determine uniqueness of the (set,binding) pairs only withing this
1049 // one resource-var builtin function.
1050 using SetAndBinding = std::pair<unsigned, unsigned>;
1051 // Maps set and binding to the resource var info.
1052 DenseMap<SetAndBinding, ResourceVarInfo *> set_and_binding_map;
1053 bool first_use = true;
1054 for (auto &U : F.uses()) {
1055 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
1056 const auto set = unsigned(
1057 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
1058 const auto binding = unsigned(
1059 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
1060 const auto arg_kind = clspv::ArgKind(
1061 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue());
1062 const auto arg_index = unsigned(
1063 dyn_cast<ConstantInt>(call->getArgOperand(3))->getZExtValue());
1064
1065 // Find or make the resource var info for this combination.
1066 ResourceVarInfo *rv = nullptr;
1067 if (always_distinct_sets) {
1068 // Make a new resource var any time we see a different
1069 // (set,binding) pair.
1070 SetAndBinding key{set, binding};
1071 auto where = set_and_binding_map.find(key);
1072 if (where == set_and_binding_map.end()) {
1073 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1074 binding, &F, arg_kind);
1075 ResourceVarInfoList.emplace_back(rv);
1076 set_and_binding_map[key] = rv;
1077 } else {
1078 rv = where->second;
1079 }
1080 } else {
1081 // The default is to make exactly one resource for each
1082 // clspv.resource.var.* function.
1083 if (first_use) {
1084 first_use = false;
1085 rv = new ResourceVarInfo(int(ResourceVarInfoList.size()), set,
1086 binding, &F, arg_kind);
1087 ResourceVarInfoList.emplace_back(rv);
1088 } else {
1089 rv = ResourceVarInfoList.back().get();
1090 }
1091 }
1092
1093 // Now populate FunctionToResourceVarsMap.
1094 auto &mapping =
1095 FunctionToResourceVarsMap[call->getParent()->getParent()];
1096 while (mapping.size() <= arg_index) {
1097 mapping.push_back(nullptr);
1098 }
1099 mapping[arg_index] = rv;
1100 }
1101 }
1102 }
1103 }
1104
1105 // Populate ModuleOrderedResourceVars.
1106 for (Function &F : M) {
1107 auto where = FunctionToResourceVarsMap.find(&F);
1108 if (where != FunctionToResourceVarsMap.end()) {
1109 for (auto &rv : where->second) {
1110 if (rv != nullptr) {
1111 ModuleOrderedResourceVars.insert(rv);
1112 }
1113 }
1114 }
1115 }
1116 if (ShowResourceVars) {
1117 for (auto *info : ModuleOrderedResourceVars) {
1118 outs() << "MORV index " << info->index << " (" << info->descriptor_set
1119 << "," << info->binding << ") " << *(info->var_fn->getReturnType())
1120 << "\n";
1121 }
1122 }
1123}
1124
David Neto22f144c2017-06-12 14:26:21 -04001125bool SPIRVProducerPass::FindExtInst(Module &M) {
1126 LLVMContext &Context = M.getContext();
1127 bool HasExtInst = false;
1128
1129 for (Function &F : M) {
1130 for (BasicBlock &BB : F) {
1131 for (Instruction &I : BB) {
1132 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1133 Function *Callee = Call->getCalledFunction();
1134 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001135 auto callee_name = Callee->getName();
1136 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1137 const glsl::ExtInst IndirectEInst =
1138 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001139
David Neto3fbb4072017-10-16 11:28:14 -04001140 HasExtInst |=
1141 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1142
1143 if (IndirectEInst) {
1144 // Register extra constants if needed.
1145
1146 // Registers a type and constant for computing the result of the
1147 // given instruction. If the result of the instruction is a vector,
1148 // then make a splat vector constant with the same number of
1149 // elements.
1150 auto register_constant = [this, &I](Constant *constant) {
1151 FindType(constant->getType());
1152 FindConstant(constant);
1153 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1154 // Register the splat vector of the value with the same
1155 // width as the result of the instruction.
1156 auto *vec_constant = ConstantVector::getSplat(
1157 static_cast<unsigned>(vectorTy->getNumElements()),
1158 constant);
1159 FindConstant(vec_constant);
1160 FindType(vec_constant->getType());
1161 }
1162 };
1163 switch (IndirectEInst) {
1164 case glsl::ExtInstFindUMsb:
1165 // clz needs OpExtInst and OpISub with constant 31, or splat
1166 // vector of 31. Add it to the constant list here.
1167 register_constant(
1168 ConstantInt::get(Type::getInt32Ty(Context), 31));
1169 break;
1170 case glsl::ExtInstAcos:
1171 case glsl::ExtInstAsin:
Kévin Petiteb9f90a2018-09-29 12:29:34 +01001172 case glsl::ExtInstAtan:
David Neto3fbb4072017-10-16 11:28:14 -04001173 case glsl::ExtInstAtan2:
1174 // We need 1/pi for acospi, asinpi, atan2pi.
1175 register_constant(
1176 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1177 break;
1178 default:
1179 assert(false && "internally inconsistent");
1180 }
David Neto22f144c2017-06-12 14:26:21 -04001181 }
1182 }
1183 }
1184 }
1185 }
1186
1187 return HasExtInst;
1188}
1189
1190void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1191 // Investigate global variable's type.
1192 FindType(GV.getType());
1193}
1194
1195void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1196 // Investigate function's type.
1197 FunctionType *FTy = F.getFunctionType();
1198
1199 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1200 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001201 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001202 if (GlobalConstFuncTyMap.count(FTy)) {
1203 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1204 SmallVector<Type *, 4> NewFuncParamTys;
1205 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1206 Type *ParamTy = FTy->getParamType(i);
1207 if (i == GVCstArgIdx) {
1208 Type *EleTy = ParamTy->getPointerElementType();
1209 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1210 }
1211
1212 NewFuncParamTys.push_back(ParamTy);
1213 }
1214
1215 FunctionType *NewFTy =
1216 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1217 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1218 FTy = NewFTy;
1219 }
1220
1221 FindType(FTy);
1222 } else {
1223 // As kernel functions do not have parameters, create new function type and
1224 // add it to type map.
1225 SmallVector<Type *, 4> NewFuncParamTys;
1226 FunctionType *NewFTy =
1227 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1228 FindType(NewFTy);
1229 }
1230
1231 // Investigate instructions' type in function body.
1232 for (BasicBlock &BB : F) {
1233 for (Instruction &I : BB) {
1234 if (isa<ShuffleVectorInst>(I)) {
1235 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1236 // Ignore type for mask of shuffle vector instruction.
1237 if (i == 2) {
1238 continue;
1239 }
1240
1241 Value *Op = I.getOperand(i);
1242 if (!isa<MetadataAsValue>(Op)) {
1243 FindType(Op->getType());
1244 }
1245 }
1246
1247 FindType(I.getType());
1248 continue;
1249 }
1250
David Neto862b7d82018-06-14 18:48:37 -04001251 CallInst *Call = dyn_cast<CallInst>(&I);
1252
1253 if (Call && Call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -04001254 clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001255 // This is a fake call representing access to a resource variable.
1256 // We handle that elsewhere.
1257 continue;
1258 }
1259
Alan Baker202c8c72018-08-13 13:47:44 -04001260 if (Call && Call->getCalledFunction()->getName().startswith(
1261 clspv::WorkgroupAccessorFunction())) {
1262 // This is a fake call representing access to a workgroup variable.
1263 // We handle that elsewhere.
1264 continue;
1265 }
1266
David Neto22f144c2017-06-12 14:26:21 -04001267 // Work through the operands of the instruction.
1268 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1269 Value *const Op = I.getOperand(i);
1270 // If any of the operands is a constant, find the type!
1271 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1272 FindType(Op->getType());
1273 }
1274 }
1275
1276 for (Use &Op : I.operands()) {
1277 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1278 // Avoid to check call instruction's type.
1279 break;
1280 }
Alan Baker202c8c72018-08-13 13:47:44 -04001281 if (CallInst *OpCall = dyn_cast<CallInst>(Op)) {
1282 if (OpCall && OpCall->getCalledFunction()->getName().startswith(
1283 clspv::WorkgroupAccessorFunction())) {
1284 // This is a fake call representing access to a workgroup variable.
1285 // We handle that elsewhere.
1286 continue;
1287 }
1288 }
David Neto22f144c2017-06-12 14:26:21 -04001289 if (!isa<MetadataAsValue>(&Op)) {
1290 FindType(Op->getType());
1291 continue;
1292 }
1293 }
1294
David Neto22f144c2017-06-12 14:26:21 -04001295 // We don't want to track the type of this call as we are going to replace
1296 // it.
David Neto862b7d82018-06-14 18:48:37 -04001297 if (Call && ("clspv.sampler.var.literal" ==
David Neto22f144c2017-06-12 14:26:21 -04001298 Call->getCalledFunction()->getName())) {
1299 continue;
1300 }
1301
1302 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1303 // If gep's base operand has ModuleScopePrivate address space, make gep
1304 // return ModuleScopePrivate address space.
1305 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1306 // Add pointer type with private address space for global constant to
1307 // type list.
1308 Type *EleTy = I.getType()->getPointerElementType();
1309 Type *NewPTy =
1310 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1311
1312 FindType(NewPTy);
1313 continue;
1314 }
1315 }
1316
1317 FindType(I.getType());
1318 }
1319 }
1320}
1321
David Neto862b7d82018-06-14 18:48:37 -04001322void SPIRVProducerPass::FindTypesForSamplerMap(Module &M) {
1323 // If we are using a sampler map, find the type of the sampler.
1324 if (M.getFunction("clspv.sampler.var.literal") ||
1325 0 < getSamplerMap().size()) {
1326 auto SamplerStructTy = M.getTypeByName("opencl.sampler_t");
1327 if (!SamplerStructTy) {
1328 SamplerStructTy = StructType::create(M.getContext(), "opencl.sampler_t");
1329 }
1330
1331 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
1332
1333 FindType(SamplerTy);
1334 }
1335}
1336
1337void SPIRVProducerPass::FindTypesForResourceVars(Module &M) {
1338 // Record types so they are generated.
1339 TypesNeedingLayout.reset();
1340 StructTypesNeedingBlock.reset();
1341
1342 // To match older clspv codegen, generate the float type first if required
1343 // for images.
1344 for (const auto *info : ModuleOrderedResourceVars) {
1345 if (info->arg_kind == clspv::ArgKind::ReadOnlyImage ||
1346 info->arg_kind == clspv::ArgKind::WriteOnlyImage) {
1347 // We need "float" for the sampled component type.
1348 FindType(Type::getFloatTy(M.getContext()));
1349 // We only need to find it once.
1350 break;
1351 }
1352 }
1353
1354 for (const auto *info : ModuleOrderedResourceVars) {
1355 Type *type = info->var_fn->getReturnType();
1356
1357 switch (info->arg_kind) {
1358 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04001359 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04001360 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1361 StructTypesNeedingBlock.insert(sty);
1362 } else {
1363 errs() << *type << "\n";
1364 llvm_unreachable("Buffer arguments must map to structures!");
1365 }
1366 break;
1367 case clspv::ArgKind::Pod:
1368 if (auto *sty = dyn_cast<StructType>(type->getPointerElementType())) {
1369 StructTypesNeedingBlock.insert(sty);
1370 } else {
1371 errs() << *type << "\n";
1372 llvm_unreachable("POD arguments must map to structures!");
1373 }
1374 break;
1375 case clspv::ArgKind::ReadOnlyImage:
1376 case clspv::ArgKind::WriteOnlyImage:
1377 case clspv::ArgKind::Sampler:
1378 // Sampler and image types map to the pointee type but
1379 // in the uniform constant address space.
1380 type = PointerType::get(type->getPointerElementType(),
1381 clspv::AddressSpace::UniformConstant);
1382 break;
1383 default:
1384 break;
1385 }
1386
1387 // The converted type is the type of the OpVariable we will generate.
1388 // If the pointee type is an array of size zero, FindType will convert it
1389 // to a runtime array.
1390 FindType(type);
1391 }
1392
1393 // Traverse the arrays and structures underneath each Block, and
1394 // mark them as needing layout.
1395 std::vector<Type *> work_list(StructTypesNeedingBlock.begin(),
1396 StructTypesNeedingBlock.end());
1397 while (!work_list.empty()) {
1398 Type *type = work_list.back();
1399 work_list.pop_back();
1400 TypesNeedingLayout.insert(type);
1401 switch (type->getTypeID()) {
1402 case Type::ArrayTyID:
1403 work_list.push_back(type->getArrayElementType());
1404 if (!Hack_generate_runtime_array_stride_early) {
1405 // Remember this array type for deferred decoration.
1406 TypesNeedingArrayStride.insert(type);
1407 }
1408 break;
1409 case Type::StructTyID:
1410 for (auto *elem_ty : cast<StructType>(type)->elements()) {
1411 work_list.push_back(elem_ty);
1412 }
1413 default:
1414 // This type and its contained types don't get layout.
1415 break;
1416 }
1417 }
1418}
1419
Alan Baker202c8c72018-08-13 13:47:44 -04001420void SPIRVProducerPass::FindWorkgroupVars(Module &M) {
1421 // The SpecId assignment for pointer-to-local arguments is recorded in
1422 // module-level metadata. Translate that information into local argument
1423 // information.
1424 NamedMDNode *nmd = M.getNamedMetadata(clspv::LocalSpecIdMetadataName());
1425 if (!nmd) return;
1426 for (auto operand : nmd->operands()) {
1427 MDTuple *tuple = cast<MDTuple>(operand);
1428 ValueAsMetadata *fn_md = cast<ValueAsMetadata>(tuple->getOperand(0));
1429 Function *func = cast<Function>(fn_md->getValue());
1430 ConstantAsMetadata *arg_index_md = cast<ConstantAsMetadata>(tuple->getOperand(1));
1431 int arg_index = cast<ConstantInt>(arg_index_md->getValue())->getSExtValue();
1432 Argument* arg = &*(func->arg_begin() + arg_index);
1433
1434 ConstantAsMetadata *spec_id_md =
1435 cast<ConstantAsMetadata>(tuple->getOperand(2));
1436 int spec_id = cast<ConstantInt>(spec_id_md->getValue())->getSExtValue();
1437
1438 max_local_spec_id_ = std::max(max_local_spec_id_, spec_id + 1);
1439 LocalArgSpecIds[arg] = spec_id;
1440 if (LocalSpecIdInfoMap.count(spec_id)) continue;
1441
1442 // We haven't seen this SpecId yet, so generate the LocalArgInfo for it.
1443 LocalArgInfo info{nextID, arg->getType()->getPointerElementType(),
1444 nextID + 1, nextID + 2,
1445 nextID + 3, spec_id};
1446 LocalSpecIdInfoMap[spec_id] = info;
1447 nextID += 4;
1448
1449 // Ensure the types necessary for this argument get generated.
1450 Type *IdxTy = Type::getInt32Ty(M.getContext());
1451 FindConstant(ConstantInt::get(IdxTy, 0));
1452 FindType(IdxTy);
1453 FindType(arg->getType());
1454 }
1455}
1456
David Neto22f144c2017-06-12 14:26:21 -04001457void SPIRVProducerPass::FindType(Type *Ty) {
1458 TypeList &TyList = getTypeList();
1459
1460 if (0 != TyList.idFor(Ty)) {
1461 return;
1462 }
1463
1464 if (Ty->isPointerTy()) {
1465 auto AddrSpace = Ty->getPointerAddressSpace();
1466 if ((AddressSpace::Constant == AddrSpace) ||
1467 (AddressSpace::Global == AddrSpace)) {
1468 auto PointeeTy = Ty->getPointerElementType();
1469
1470 if (PointeeTy->isStructTy() &&
1471 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1472 FindType(PointeeTy);
1473 auto ActualPointerTy =
1474 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1475 FindType(ActualPointerTy);
1476 return;
1477 }
1478 }
1479 }
1480
David Neto862b7d82018-06-14 18:48:37 -04001481 // By convention, LLVM array type with 0 elements will map to
1482 // OpTypeRuntimeArray. Otherwise, it will map to OpTypeArray, which
1483 // has a constant number of elements. We need to support type of the
1484 // constant.
1485 if (auto *arrayTy = dyn_cast<ArrayType>(Ty)) {
1486 if (arrayTy->getNumElements() > 0) {
1487 LLVMContext &Context = Ty->getContext();
1488 FindType(Type::getInt32Ty(Context));
1489 }
David Neto22f144c2017-06-12 14:26:21 -04001490 }
1491
1492 for (Type *SubTy : Ty->subtypes()) {
1493 FindType(SubTy);
1494 }
1495
1496 TyList.insert(Ty);
1497}
1498
1499void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1500 // If the global variable has a (non undef) initializer.
1501 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
David Neto862b7d82018-06-14 18:48:37 -04001502 // Generate the constant if it's not the initializer to a module scope
1503 // constant that we will expect in a storage buffer.
1504 const bool module_scope_constant_external_init =
1505 (GV.getType()->getPointerAddressSpace() == AddressSpace::Constant) &&
1506 clspv::Option::ModuleConstantsInStorageBuffer();
1507 if (!module_scope_constant_external_init) {
1508 FindConstant(GV.getInitializer());
1509 }
David Neto22f144c2017-06-12 14:26:21 -04001510 }
1511}
1512
1513void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1514 // Investigate constants in function body.
1515 for (BasicBlock &BB : F) {
1516 for (Instruction &I : BB) {
David Neto862b7d82018-06-14 18:48:37 -04001517 if (auto *call = dyn_cast<CallInst>(&I)) {
1518 auto name = call->getCalledFunction()->getName();
1519 if (name == "clspv.sampler.var.literal") {
1520 // We've handled these constants elsewhere, so skip it.
1521 continue;
1522 }
Alan Baker202c8c72018-08-13 13:47:44 -04001523 if (name.startswith(clspv::ResourceAccessorFunction())) {
1524 continue;
1525 }
1526 if (name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04001527 continue;
1528 }
David Neto22f144c2017-06-12 14:26:21 -04001529 }
1530
1531 if (isa<AllocaInst>(I)) {
1532 // Alloca instruction has constant for the number of element. Ignore it.
1533 continue;
1534 } else if (isa<ShuffleVectorInst>(I)) {
1535 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1536 // Ignore constant for mask of shuffle vector instruction.
1537 if (i == 2) {
1538 continue;
1539 }
1540
1541 if (isa<Constant>(I.getOperand(i)) &&
1542 !isa<GlobalValue>(I.getOperand(i))) {
1543 FindConstant(I.getOperand(i));
1544 }
1545 }
1546
1547 continue;
1548 } else if (isa<InsertElementInst>(I)) {
1549 // Handle InsertElement with <4 x i8> specially.
1550 Type *CompositeTy = I.getOperand(0)->getType();
1551 if (is4xi8vec(CompositeTy)) {
1552 LLVMContext &Context = CompositeTy->getContext();
1553 if (isa<Constant>(I.getOperand(0))) {
1554 FindConstant(I.getOperand(0));
1555 }
1556
1557 if (isa<Constant>(I.getOperand(1))) {
1558 FindConstant(I.getOperand(1));
1559 }
1560
1561 // Add mask constant 0xFF.
1562 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1563 FindConstant(CstFF);
1564
1565 // Add shift amount constant.
1566 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1567 uint64_t Idx = CI->getZExtValue();
1568 Constant *CstShiftAmount =
1569 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1570 FindConstant(CstShiftAmount);
1571 }
1572
1573 continue;
1574 }
1575
1576 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1577 // Ignore constant for index of InsertElement instruction.
1578 if (i == 2) {
1579 continue;
1580 }
1581
1582 if (isa<Constant>(I.getOperand(i)) &&
1583 !isa<GlobalValue>(I.getOperand(i))) {
1584 FindConstant(I.getOperand(i));
1585 }
1586 }
1587
1588 continue;
1589 } else if (isa<ExtractElementInst>(I)) {
1590 // Handle ExtractElement with <4 x i8> specially.
1591 Type *CompositeTy = I.getOperand(0)->getType();
1592 if (is4xi8vec(CompositeTy)) {
1593 LLVMContext &Context = CompositeTy->getContext();
1594 if (isa<Constant>(I.getOperand(0))) {
1595 FindConstant(I.getOperand(0));
1596 }
1597
1598 // Add mask constant 0xFF.
1599 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1600 FindConstant(CstFF);
1601
1602 // Add shift amount constant.
1603 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1604 uint64_t Idx = CI->getZExtValue();
1605 Constant *CstShiftAmount =
1606 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1607 FindConstant(CstShiftAmount);
1608 } else {
1609 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1610 FindConstant(Cst8);
1611 }
1612
1613 continue;
1614 }
1615
1616 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1617 // Ignore constant for index of ExtractElement instruction.
1618 if (i == 1) {
1619 continue;
1620 }
1621
1622 if (isa<Constant>(I.getOperand(i)) &&
1623 !isa<GlobalValue>(I.getOperand(i))) {
1624 FindConstant(I.getOperand(i));
1625 }
1626 }
1627
1628 continue;
1629 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1630 // 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
1631 bool foundConstantTrue = false;
1632 for (Use &Op : I.operands()) {
1633 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1634 auto CI = cast<ConstantInt>(Op);
1635
1636 if (CI->isZero() || foundConstantTrue) {
1637 // 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.
1638 FindConstant(Op);
1639 } else {
1640 foundConstantTrue = true;
1641 }
1642 }
1643 }
1644
1645 continue;
David Netod2de94a2017-08-28 17:27:47 -04001646 } else if (isa<TruncInst>(I)) {
1647 // For truncation to i8 we mask against 255.
1648 Type *ToTy = I.getType();
1649 if (8u == ToTy->getPrimitiveSizeInBits()) {
1650 LLVMContext &Context = ToTy->getContext();
1651 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1652 FindConstant(Cst255);
1653 }
1654 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001655 } else if (isa<AtomicRMWInst>(I)) {
1656 LLVMContext &Context = I.getContext();
1657
1658 FindConstant(
1659 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1660 FindConstant(ConstantInt::get(
1661 Type::getInt32Ty(Context),
1662 spv::MemorySemanticsUniformMemoryMask |
1663 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001664 }
1665
1666 for (Use &Op : I.operands()) {
1667 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1668 FindConstant(Op);
1669 }
1670 }
1671 }
1672 }
1673}
1674
1675void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001676 ValueList &CstList = getConstantList();
1677
David Netofb9a7972017-08-25 17:08:24 -04001678 // If V is already tracked, ignore it.
1679 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001680 return;
1681 }
1682
David Neto862b7d82018-06-14 18:48:37 -04001683 if (isa<GlobalValue>(V) && clspv::Option::ModuleConstantsInStorageBuffer()) {
1684 return;
1685 }
1686
David Neto22f144c2017-06-12 14:26:21 -04001687 Constant *Cst = cast<Constant>(V);
David Neto862b7d82018-06-14 18:48:37 -04001688 Type *CstTy = Cst->getType();
David Neto22f144c2017-06-12 14:26:21 -04001689
1690 // Handle constant with <4 x i8> type specially.
David Neto22f144c2017-06-12 14:26:21 -04001691 if (is4xi8vec(CstTy)) {
1692 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001693 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001694 }
1695 }
1696
1697 if (Cst->getNumOperands()) {
1698 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1699 ++I) {
1700 FindConstant(*I);
1701 }
1702
David Netofb9a7972017-08-25 17:08:24 -04001703 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001704 return;
1705 } else if (const ConstantDataSequential *CDS =
1706 dyn_cast<ConstantDataSequential>(Cst)) {
1707 // Add constants for each element to constant list.
1708 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1709 Constant *EleCst = CDS->getElementAsConstant(i);
1710 FindConstant(EleCst);
1711 }
1712 }
1713
1714 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001715 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001716 }
1717}
1718
1719spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1720 switch (AddrSpace) {
1721 default:
1722 llvm_unreachable("Unsupported OpenCL address space");
1723 case AddressSpace::Private:
1724 return spv::StorageClassFunction;
1725 case AddressSpace::Global:
David Neto22f144c2017-06-12 14:26:21 -04001726 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001727 case AddressSpace::Constant:
1728 return clspv::Option::ConstantArgsInUniformBuffer()
1729 ? spv::StorageClassUniform
1730 : spv::StorageClassStorageBuffer;
David Neto22f144c2017-06-12 14:26:21 -04001731 case AddressSpace::Input:
1732 return spv::StorageClassInput;
1733 case AddressSpace::Local:
1734 return spv::StorageClassWorkgroup;
1735 case AddressSpace::UniformConstant:
1736 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001737 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001738 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001739 case AddressSpace::ModuleScopePrivate:
1740 return spv::StorageClassPrivate;
1741 }
1742}
1743
David Neto862b7d82018-06-14 18:48:37 -04001744spv::StorageClass
1745SPIRVProducerPass::GetStorageClassForArgKind(clspv::ArgKind arg_kind) const {
1746 switch (arg_kind) {
1747 case clspv::ArgKind::Buffer:
1748 return spv::StorageClassStorageBuffer;
Alan Bakerfcda9482018-10-02 17:09:59 -04001749 case clspv::ArgKind::BufferUBO:
1750 return spv::StorageClassUniform;
David Neto862b7d82018-06-14 18:48:37 -04001751 case clspv::ArgKind::Pod:
1752 return clspv::Option::PodArgsInUniformBuffer()
1753 ? spv::StorageClassUniform
1754 : spv::StorageClassStorageBuffer;
1755 case clspv::ArgKind::Local:
1756 return spv::StorageClassWorkgroup;
1757 case clspv::ArgKind::ReadOnlyImage:
1758 case clspv::ArgKind::WriteOnlyImage:
1759 case clspv::ArgKind::Sampler:
1760 return spv::StorageClassUniformConstant;
1761 }
1762}
1763
David Neto22f144c2017-06-12 14:26:21 -04001764spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1765 return StringSwitch<spv::BuiltIn>(Name)
1766 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1767 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1768 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1769 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1770 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1771 .Default(spv::BuiltInMax);
1772}
1773
1774void SPIRVProducerPass::GenerateExtInstImport() {
1775 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1776 uint32_t &ExtInstImportID = getOpExtInstImportID();
1777
1778 //
1779 // Generate OpExtInstImport.
1780 //
1781 // Ops[0] ... Ops[n] = Name (Literal String)
David Neto22f144c2017-06-12 14:26:21 -04001782 ExtInstImportID = nextID;
David Neto87846742018-04-11 17:36:22 -04001783 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpExtInstImport, nextID++,
1784 MkString("GLSL.std.450")));
David Neto22f144c2017-06-12 14:26:21 -04001785}
1786
Alan Bakerfcda9482018-10-02 17:09:59 -04001787void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, Module &module) {
David Neto22f144c2017-06-12 14:26:21 -04001788 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1789 ValueMapType &VMap = getValueMap();
1790 ValueMapType &AllocatedVMap = getAllocatedValueMap();
Alan Bakerfcda9482018-10-02 17:09:59 -04001791 const auto &DL = module.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04001792
1793 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1794 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1795 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1796
1797 for (Type *Ty : getTypeList()) {
1798 // Update TypeMap with nextID for reference later.
1799 TypeMap[Ty] = nextID;
1800
1801 switch (Ty->getTypeID()) {
1802 default: {
1803 Ty->print(errs());
1804 llvm_unreachable("Unsupported type???");
1805 break;
1806 }
1807 case Type::MetadataTyID:
1808 case Type::LabelTyID: {
1809 // Ignore these types.
1810 break;
1811 }
1812 case Type::PointerTyID: {
1813 PointerType *PTy = cast<PointerType>(Ty);
1814 unsigned AddrSpace = PTy->getAddressSpace();
1815
1816 // For the purposes of our Vulkan SPIR-V type system, constant and global
1817 // are conflated.
1818 bool UseExistingOpTypePointer = false;
1819 if (AddressSpace::Constant == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001820 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1821 AddrSpace = AddressSpace::Global;
1822 // Check to see if we already created this type (for instance, if we had
1823 // a constant <type>* and a global <type>*, the type would be created by
1824 // one of these types, and shared by both).
1825 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1826 if (0 < TypeMap.count(GlobalTy)) {
1827 TypeMap[PTy] = TypeMap[GlobalTy];
1828 UseExistingOpTypePointer = true;
1829 break;
1830 }
David Neto22f144c2017-06-12 14:26:21 -04001831 }
1832 } else if (AddressSpace::Global == AddrSpace) {
Alan Bakerfcda9482018-10-02 17:09:59 -04001833 if (!clspv::Option::ConstantArgsInUniformBuffer()) {
1834 AddrSpace = AddressSpace::Constant;
David Neto22f144c2017-06-12 14:26:21 -04001835
Alan Bakerfcda9482018-10-02 17:09:59 -04001836 // Check to see if we already created this type (for instance, if we had
1837 // a constant <type>* and a global <type>*, the type would be created by
1838 // one of these types, and shared by both).
1839 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1840 if (0 < TypeMap.count(ConstantTy)) {
1841 TypeMap[PTy] = TypeMap[ConstantTy];
1842 UseExistingOpTypePointer = true;
1843 }
David Neto22f144c2017-06-12 14:26:21 -04001844 }
1845 }
1846
David Neto862b7d82018-06-14 18:48:37 -04001847 const bool HasArgUser = true;
David Neto22f144c2017-06-12 14:26:21 -04001848
David Neto862b7d82018-06-14 18:48:37 -04001849 if (HasArgUser && !UseExistingOpTypePointer) {
David Neto22f144c2017-06-12 14:26:21 -04001850 //
1851 // Generate OpTypePointer.
1852 //
1853
1854 // OpTypePointer
1855 // Ops[0] = Storage Class
1856 // Ops[1] = Element Type ID
1857 SPIRVOperandList Ops;
1858
David Neto257c3892018-04-11 13:19:45 -04001859 Ops << MkNum(GetStorageClass(AddrSpace))
1860 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001861
David Neto87846742018-04-11 17:36:22 -04001862 auto *Inst = new SPIRVInstruction(spv::OpTypePointer, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001863 SPIRVInstList.push_back(Inst);
1864 }
David Neto22f144c2017-06-12 14:26:21 -04001865 break;
1866 }
1867 case Type::StructTyID: {
David Neto22f144c2017-06-12 14:26:21 -04001868 StructType *STy = cast<StructType>(Ty);
1869
1870 // Handle sampler type.
1871 if (STy->isOpaque()) {
1872 if (STy->getName().equals("opencl.sampler_t")) {
1873 //
1874 // Generate OpTypeSampler
1875 //
1876 // Empty Ops.
1877 SPIRVOperandList Ops;
1878
David Neto87846742018-04-11 17:36:22 -04001879 auto *Inst = new SPIRVInstruction(spv::OpTypeSampler, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001880 SPIRVInstList.push_back(Inst);
1881 break;
1882 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1883 STy->getName().equals("opencl.image2d_wo_t") ||
1884 STy->getName().equals("opencl.image3d_ro_t") ||
1885 STy->getName().equals("opencl.image3d_wo_t")) {
1886 //
1887 // Generate OpTypeImage
1888 //
1889 // Ops[0] = Sampled Type ID
1890 // Ops[1] = Dim ID
1891 // Ops[2] = Depth (Literal Number)
1892 // Ops[3] = Arrayed (Literal Number)
1893 // Ops[4] = MS (Literal Number)
1894 // Ops[5] = Sampled (Literal Number)
1895 // Ops[6] = Image Format ID
1896 //
1897 SPIRVOperandList Ops;
1898
1899 // TODO: Changed Sampled Type according to situations.
1900 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001901 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001902
1903 spv::Dim DimID = spv::Dim2D;
1904 if (STy->getName().equals("opencl.image3d_ro_t") ||
1905 STy->getName().equals("opencl.image3d_wo_t")) {
1906 DimID = spv::Dim3D;
1907 }
David Neto257c3892018-04-11 13:19:45 -04001908 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001909
1910 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001911 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001912
1913 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001914 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001915
1916 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001917 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001918
1919 // TODO: Set up Sampled.
1920 //
1921 // From Spec
1922 //
1923 // 0 indicates this is only known at run time, not at compile time
1924 // 1 indicates will be used with sampler
1925 // 2 indicates will be used without a sampler (a storage image)
1926 uint32_t Sampled = 1;
1927 if (STy->getName().equals("opencl.image2d_wo_t") ||
1928 STy->getName().equals("opencl.image3d_wo_t")) {
1929 Sampled = 2;
1930 }
David Neto257c3892018-04-11 13:19:45 -04001931 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001932
1933 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001934 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001935
David Neto87846742018-04-11 17:36:22 -04001936 auto *Inst = new SPIRVInstruction(spv::OpTypeImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001937 SPIRVInstList.push_back(Inst);
1938 break;
1939 }
1940 }
1941
1942 //
1943 // Generate OpTypeStruct
1944 //
1945 // Ops[0] ... Ops[n] = Member IDs
1946 SPIRVOperandList Ops;
1947
1948 for (auto *EleTy : STy->elements()) {
David Neto862b7d82018-06-14 18:48:37 -04001949 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001950 }
1951
David Neto22f144c2017-06-12 14:26:21 -04001952 uint32_t STyID = nextID;
1953
David Neto87846742018-04-11 17:36:22 -04001954 auto *Inst =
1955 new SPIRVInstruction(spv::OpTypeStruct, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001956 SPIRVInstList.push_back(Inst);
1957
1958 // Generate OpMemberDecorate.
1959 auto DecoInsertPoint =
1960 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1961 [](SPIRVInstruction *Inst) -> bool {
1962 return Inst->getOpcode() != spv::OpDecorate &&
1963 Inst->getOpcode() != spv::OpMemberDecorate &&
1964 Inst->getOpcode() != spv::OpExtInstImport;
1965 });
1966
David Netoc463b372017-08-10 15:32:21 -04001967 const auto StructLayout = DL.getStructLayout(STy);
Alan Bakerfcda9482018-10-02 17:09:59 -04001968 // Search for the correct offsets if this type was remapped.
1969 std::vector<uint32_t> *offsets = nullptr;
1970 auto iter = RemappedUBOTypeOffsets.find(STy);
1971 if (iter != RemappedUBOTypeOffsets.end()) {
1972 offsets = &iter->second;
1973 }
David Netoc463b372017-08-10 15:32:21 -04001974
David Neto862b7d82018-06-14 18:48:37 -04001975 // #error TODO(dneto): Only do this if in TypesNeedingLayout.
David Neto22f144c2017-06-12 14:26:21 -04001976 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1977 MemberIdx++) {
1978 // Ops[0] = Structure Type ID
1979 // Ops[1] = Member Index(Literal Number)
1980 // Ops[2] = Decoration (Offset)
1981 // Ops[3] = Byte Offset (Literal Number)
1982 Ops.clear();
1983
David Neto257c3892018-04-11 13:19:45 -04001984 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001985
Alan Bakerfcda9482018-10-02 17:09:59 -04001986 auto ByteOffset = StructLayout->getElementOffset(MemberIdx);
1987 if (offsets) {
1988 ByteOffset = (*offsets)[MemberIdx];
1989 }
1990 //const auto ByteOffset =
1991 // uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001992 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001993
David Neto87846742018-04-11 17:36:22 -04001994 auto *DecoInst = new SPIRVInstruction(spv::OpMemberDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04001995 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001996 }
1997
1998 // Generate OpDecorate.
David Neto862b7d82018-06-14 18:48:37 -04001999 if (StructTypesNeedingBlock.idFor(STy)) {
2000 Ops.clear();
2001 // Use Block decorations with StorageBuffer storage class.
2002 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04002003
David Neto862b7d82018-06-14 18:48:37 -04002004 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2005 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002006 }
2007 break;
2008 }
2009 case Type::IntegerTyID: {
2010 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2011
2012 if (BitWidth == 1) {
David Neto87846742018-04-11 17:36:22 -04002013 auto *Inst = new SPIRVInstruction(spv::OpTypeBool, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002014 SPIRVInstList.push_back(Inst);
2015 } else {
2016 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04002017 // No matter what LLVM type is requested first, always alias the
2018 // second one's SPIR-V type to be the same as the one we generated
2019 // first.
Neil Henning39672102017-09-29 14:33:13 +01002020 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04002021 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04002022 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04002023 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04002024 } else if (BitWidth == 32) {
2025 aliasToWidth = 8;
2026 }
2027 if (aliasToWidth) {
2028 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
2029 auto where = TypeMap.find(otherType);
2030 if (where == TypeMap.end()) {
2031 // Go ahead and make it, but also map the other type to it.
2032 TypeMap[otherType] = nextID;
2033 } else {
2034 // Alias this SPIR-V type the existing type.
2035 TypeMap[Ty] = where->second;
2036 break;
2037 }
David Neto22f144c2017-06-12 14:26:21 -04002038 }
2039
David Neto257c3892018-04-11 13:19:45 -04002040 SPIRVOperandList Ops;
2041 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04002042
2043 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002044 new SPIRVInstruction(spv::OpTypeInt, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002045 }
2046 break;
2047 }
2048 case Type::HalfTyID:
2049 case Type::FloatTyID:
2050 case Type::DoubleTyID: {
2051 SPIRVOperand *WidthOp = new SPIRVOperand(
2052 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
2053
2054 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002055 new SPIRVInstruction(spv::OpTypeFloat, nextID++, WidthOp));
David Neto22f144c2017-06-12 14:26:21 -04002056 break;
2057 }
2058 case Type::ArrayTyID: {
David Neto22f144c2017-06-12 14:26:21 -04002059 ArrayType *ArrTy = cast<ArrayType>(Ty);
David Neto862b7d82018-06-14 18:48:37 -04002060 const uint64_t Length = ArrTy->getArrayNumElements();
2061 if (Length == 0) {
2062 // By convention, map it to a RuntimeArray.
David Neto22f144c2017-06-12 14:26:21 -04002063
David Neto862b7d82018-06-14 18:48:37 -04002064 // Only generate the type once.
2065 // TODO(dneto): Can it ever be generated more than once?
2066 // Doesn't LLVM type uniqueness guarantee we'll only see this
2067 // once?
2068 Type *EleTy = ArrTy->getArrayElementType();
2069 if (OpRuntimeTyMap.count(EleTy) == 0) {
2070 uint32_t OpTypeRuntimeArrayID = nextID;
2071 OpRuntimeTyMap[Ty] = nextID;
David Neto22f144c2017-06-12 14:26:21 -04002072
David Neto862b7d82018-06-14 18:48:37 -04002073 //
2074 // Generate OpTypeRuntimeArray.
2075 //
David Neto22f144c2017-06-12 14:26:21 -04002076
David Neto862b7d82018-06-14 18:48:37 -04002077 // OpTypeRuntimeArray
2078 // Ops[0] = Element Type ID
2079 SPIRVOperandList Ops;
2080 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04002081
David Neto862b7d82018-06-14 18:48:37 -04002082 SPIRVInstList.push_back(
2083 new SPIRVInstruction(spv::OpTypeRuntimeArray, nextID++, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002084
David Neto862b7d82018-06-14 18:48:37 -04002085 if (Hack_generate_runtime_array_stride_early) {
2086 // Generate OpDecorate.
2087 auto DecoInsertPoint = std::find_if(
2088 SPIRVInstList.begin(), SPIRVInstList.end(),
2089 [](SPIRVInstruction *Inst) -> bool {
2090 return Inst->getOpcode() != spv::OpDecorate &&
2091 Inst->getOpcode() != spv::OpMemberDecorate &&
2092 Inst->getOpcode() != spv::OpExtInstImport;
2093 });
David Neto22f144c2017-06-12 14:26:21 -04002094
David Neto862b7d82018-06-14 18:48:37 -04002095 // Ops[0] = Target ID
2096 // Ops[1] = Decoration (ArrayStride)
2097 // Ops[2] = Stride Number(Literal Number)
2098 Ops.clear();
David Neto85082642018-03-24 06:55:20 -07002099
David Neto862b7d82018-06-14 18:48:37 -04002100 Ops << MkId(OpTypeRuntimeArrayID)
2101 << MkNum(spv::DecorationArrayStride)
Alan Bakerfcda9482018-10-02 17:09:59 -04002102 << MkNum(static_cast<uint32_t>(GetTypeAllocSize(EleTy, DL)));
David Neto22f144c2017-06-12 14:26:21 -04002103
David Neto862b7d82018-06-14 18:48:37 -04002104 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
2105 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
2106 }
2107 }
David Neto22f144c2017-06-12 14:26:21 -04002108
David Neto862b7d82018-06-14 18:48:37 -04002109 } else {
David Neto22f144c2017-06-12 14:26:21 -04002110
David Neto862b7d82018-06-14 18:48:37 -04002111 //
2112 // Generate OpConstant and OpTypeArray.
2113 //
2114
2115 //
2116 // Generate OpConstant for array length.
2117 //
2118 // Ops[0] = Result Type ID
2119 // Ops[1] .. Ops[n] = Values LiteralNumber
2120 SPIRVOperandList Ops;
2121
2122 Type *LengthTy = Type::getInt32Ty(Context);
2123 uint32_t ResTyID = lookupType(LengthTy);
2124 Ops << MkId(ResTyID);
2125
2126 assert(Length < UINT32_MAX);
2127 Ops << MkNum(static_cast<uint32_t>(Length));
2128
2129 // Add constant for length to constant list.
2130 Constant *CstLength = ConstantInt::get(LengthTy, Length);
2131 AllocatedVMap[CstLength] = nextID;
2132 VMap[CstLength] = nextID;
2133 uint32_t LengthID = nextID;
2134
2135 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
2136 SPIRVInstList.push_back(CstInst);
2137
2138 // Remember to generate ArrayStride later
2139 getTypesNeedingArrayStride().insert(Ty);
2140
2141 //
2142 // Generate OpTypeArray.
2143 //
2144 // Ops[0] = Element Type ID
2145 // Ops[1] = Array Length Constant ID
2146 Ops.clear();
2147
2148 uint32_t EleTyID = lookupType(ArrTy->getElementType());
2149 Ops << MkId(EleTyID) << MkId(LengthID);
2150
2151 // Update TypeMap with nextID.
2152 TypeMap[Ty] = nextID;
2153
2154 auto *ArrayInst = new SPIRVInstruction(spv::OpTypeArray, nextID++, Ops);
2155 SPIRVInstList.push_back(ArrayInst);
2156 }
David Neto22f144c2017-06-12 14:26:21 -04002157 break;
2158 }
2159 case Type::VectorTyID: {
2160 // <4 x i8> is changed to i32.
David Neto22f144c2017-06-12 14:26:21 -04002161 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
2162 if (Ty->getVectorNumElements() == 4) {
2163 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
2164 break;
2165 } else {
2166 Ty->print(errs());
2167 llvm_unreachable("Support above i8 vector type");
2168 }
2169 }
2170
2171 // Ops[0] = Component Type ID
2172 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04002173 SPIRVOperandList Ops;
2174 Ops << MkId(lookupType(Ty->getVectorElementType()))
2175 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002176
David Neto87846742018-04-11 17:36:22 -04002177 SPIRVInstruction* inst = new SPIRVInstruction(spv::OpTypeVector, nextID++, Ops);
David Netoc6f3ab22018-04-06 18:02:31 -04002178 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002179 break;
2180 }
2181 case Type::VoidTyID: {
David Neto87846742018-04-11 17:36:22 -04002182 auto *Inst = new SPIRVInstruction(spv::OpTypeVoid, nextID++, {});
David Neto22f144c2017-06-12 14:26:21 -04002183 SPIRVInstList.push_back(Inst);
2184 break;
2185 }
2186 case Type::FunctionTyID: {
2187 // Generate SPIRV instruction for function type.
2188 FunctionType *FTy = cast<FunctionType>(Ty);
2189
2190 // Ops[0] = Return Type ID
2191 // Ops[1] ... Ops[n] = Parameter Type IDs
2192 SPIRVOperandList Ops;
2193
2194 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002195 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002196
2197 // Find SPIRV instructions for parameter types
2198 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2199 // Find SPIRV instruction for parameter type.
2200 auto ParamTy = FTy->getParamType(k);
2201 if (ParamTy->isPointerTy()) {
2202 auto PointeeTy = ParamTy->getPointerElementType();
2203 if (PointeeTy->isStructTy() &&
2204 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2205 ParamTy = PointeeTy;
2206 }
2207 }
2208
David Netoc6f3ab22018-04-06 18:02:31 -04002209 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002210 }
2211
David Neto87846742018-04-11 17:36:22 -04002212 auto *Inst = new SPIRVInstruction(spv::OpTypeFunction, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002213 SPIRVInstList.push_back(Inst);
2214 break;
2215 }
2216 }
2217 }
2218
2219 // Generate OpTypeSampledImage.
2220 TypeMapType &OpImageTypeMap = getImageTypeMap();
2221 for (auto &ImageType : OpImageTypeMap) {
2222 //
2223 // Generate OpTypeSampledImage.
2224 //
2225 // Ops[0] = Image Type ID
2226 //
2227 SPIRVOperandList Ops;
2228
2229 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002230 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002231
2232 // Update OpImageTypeMap.
2233 ImageType.second = nextID;
2234
David Neto87846742018-04-11 17:36:22 -04002235 auto *Inst = new SPIRVInstruction(spv::OpTypeSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002236 SPIRVInstList.push_back(Inst);
2237 }
David Netoc6f3ab22018-04-06 18:02:31 -04002238
2239 // Generate types for pointer-to-local arguments.
Alan Baker202c8c72018-08-13 13:47:44 -04002240 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2241 ++spec_id) {
2242 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002243
2244 // Generate the spec constant.
2245 SPIRVOperandList Ops;
2246 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04002247 SPIRVInstList.push_back(
2248 new SPIRVInstruction(spv::OpSpecConstant, arg_info.array_size_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002249
2250 // Generate the array type.
2251 Ops.clear();
2252 // The element type must have been created.
2253 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2254 assert(elem_ty_id);
2255 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2256
2257 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002258 new SPIRVInstruction(spv::OpTypeArray, arg_info.array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002259
2260 Ops.clear();
2261 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
David Neto87846742018-04-11 17:36:22 -04002262 SPIRVInstList.push_back(new SPIRVInstruction(
2263 spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002264 }
David Neto22f144c2017-06-12 14:26:21 -04002265}
2266
2267void SPIRVProducerPass::GenerateSPIRVConstants() {
2268 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2269 ValueMapType &VMap = getValueMap();
2270 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2271 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002272 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002273
2274 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002275 // UniqueVector ids are 1-based.
2276 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002277
2278 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002279 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002280 continue;
2281 }
2282
David Netofb9a7972017-08-25 17:08:24 -04002283 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002284 VMap[Cst] = nextID;
2285
2286 //
2287 // Generate OpConstant.
2288 //
2289
2290 // Ops[0] = Result Type ID
2291 // Ops[1] .. Ops[n] = Values LiteralNumber
2292 SPIRVOperandList Ops;
2293
David Neto257c3892018-04-11 13:19:45 -04002294 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002295
2296 std::vector<uint32_t> LiteralNum;
David Neto22f144c2017-06-12 14:26:21 -04002297 spv::Op Opcode = spv::OpNop;
2298
2299 if (isa<UndefValue>(Cst)) {
2300 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002301 Opcode = spv::OpUndef;
Alan Baker9bf93fb2018-08-28 16:59:26 -04002302 if (hack_undef && IsTypeNullable(Cst->getType())) {
2303 Opcode = spv::OpConstantNull;
David Netoc66b3352017-10-20 14:28:46 -04002304 }
David Neto22f144c2017-06-12 14:26:21 -04002305 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2306 unsigned BitWidth = CI->getBitWidth();
2307 if (BitWidth == 1) {
2308 // If the bitwidth of constant is 1, generate OpConstantTrue or
2309 // OpConstantFalse.
2310 if (CI->getZExtValue()) {
2311 // Ops[0] = Result Type ID
2312 Opcode = spv::OpConstantTrue;
2313 } else {
2314 // Ops[0] = Result Type ID
2315 Opcode = spv::OpConstantFalse;
2316 }
David Neto22f144c2017-06-12 14:26:21 -04002317 } else {
2318 auto V = CI->getZExtValue();
2319 LiteralNum.push_back(V & 0xFFFFFFFF);
2320
2321 if (BitWidth > 32) {
2322 LiteralNum.push_back(V >> 32);
2323 }
2324
2325 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002326
David Neto257c3892018-04-11 13:19:45 -04002327 Ops << MkInteger(LiteralNum);
2328
2329 if (BitWidth == 32 && V == 0) {
2330 constant_i32_zero_id_ = nextID;
2331 }
David Neto22f144c2017-06-12 14:26:21 -04002332 }
2333 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2334 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2335 Type *CFPTy = CFP->getType();
2336 if (CFPTy->isFloatTy()) {
2337 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2338 } else {
2339 CFPTy->print(errs());
2340 llvm_unreachable("Implement this ConstantFP Type");
2341 }
2342
2343 Opcode = spv::OpConstant;
David Neto22f144c2017-06-12 14:26:21 -04002344
David Neto257c3892018-04-11 13:19:45 -04002345 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002346 } else if (isa<ConstantDataSequential>(Cst) &&
2347 cast<ConstantDataSequential>(Cst)->isString()) {
2348 Cst->print(errs());
2349 llvm_unreachable("Implement this Constant");
2350
2351 } else if (const ConstantDataSequential *CDS =
2352 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002353 // Let's convert <4 x i8> constant to int constant specially.
2354 // This case occurs when all the values are specified as constant
2355 // ints.
2356 Type *CstTy = Cst->getType();
2357 if (is4xi8vec(CstTy)) {
2358 LLVMContext &Context = CstTy->getContext();
2359
2360 //
2361 // Generate OpConstant with OpTypeInt 32 0.
2362 //
Neil Henning39672102017-09-29 14:33:13 +01002363 uint32_t IntValue = 0;
2364 for (unsigned k = 0; k < 4; k++) {
2365 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002366 IntValue = (IntValue << 8) | (Val & 0xffu);
2367 }
2368
2369 Type *i32 = Type::getInt32Ty(Context);
2370 Constant *CstInt = ConstantInt::get(i32, IntValue);
2371 // If this constant is already registered on VMap, use it.
2372 if (VMap.count(CstInt)) {
2373 uint32_t CstID = VMap[CstInt];
2374 VMap[Cst] = CstID;
2375 continue;
2376 }
2377
David Neto257c3892018-04-11 13:19:45 -04002378 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002379
David Neto87846742018-04-11 17:36:22 -04002380 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto49351ac2017-08-26 17:32:20 -04002381 SPIRVInstList.push_back(CstInst);
2382
2383 continue;
2384 }
2385
2386 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002387 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2388 Constant *EleCst = CDS->getElementAsConstant(k);
2389 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002390 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002391 }
2392
2393 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002394 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2395 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002396 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002397 Type *CstTy = Cst->getType();
2398 if (is4xi8vec(CstTy)) {
2399 LLVMContext &Context = CstTy->getContext();
2400
2401 //
2402 // Generate OpConstant with OpTypeInt 32 0.
2403 //
Neil Henning39672102017-09-29 14:33:13 +01002404 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002405 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2406 I != E; ++I) {
2407 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002408 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002409 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2410 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002411 }
David Neto49351ac2017-08-26 17:32:20 -04002412 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002413 }
2414
David Neto49351ac2017-08-26 17:32:20 -04002415 Type *i32 = Type::getInt32Ty(Context);
2416 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002417 // If this constant is already registered on VMap, use it.
2418 if (VMap.count(CstInt)) {
2419 uint32_t CstID = VMap[CstInt];
2420 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002421 continue;
David Neto22f144c2017-06-12 14:26:21 -04002422 }
2423
David Neto257c3892018-04-11 13:19:45 -04002424 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002425
David Neto87846742018-04-11 17:36:22 -04002426 auto *CstInst = new SPIRVInstruction(spv::OpConstant, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002427 SPIRVInstList.push_back(CstInst);
2428
David Neto19a1bad2017-08-25 15:01:41 -04002429 continue;
David Neto22f144c2017-06-12 14:26:21 -04002430 }
2431
2432 // We use a constant composite in SPIR-V for our constant aggregate in
2433 // LLVM.
2434 Opcode = spv::OpConstantComposite;
David Neto22f144c2017-06-12 14:26:21 -04002435
2436 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2437 // Look up the ID of the element of this aggregate (which we will
2438 // previously have created a constant for).
2439 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2440
2441 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002442 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002443 }
2444 } else if (Cst->isNullValue()) {
2445 Opcode = spv::OpConstantNull;
David Neto22f144c2017-06-12 14:26:21 -04002446 } else {
2447 Cst->print(errs());
2448 llvm_unreachable("Unsupported Constant???");
2449 }
2450
David Neto87846742018-04-11 17:36:22 -04002451 auto *CstInst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002452 SPIRVInstList.push_back(CstInst);
2453 }
2454}
2455
2456void SPIRVProducerPass::GenerateSamplers(Module &M) {
2457 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2458 ValueMapType &VMap = getValueMap();
2459
David Neto862b7d82018-06-14 18:48:37 -04002460 auto& sampler_map = getSamplerMap();
2461 SamplerMapIndexToIDMap.clear();
David Neto22f144c2017-06-12 14:26:21 -04002462 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
David Neto862b7d82018-06-14 18:48:37 -04002463 DenseMap<unsigned, unsigned> SamplerLiteralToDescriptorSetMap;
2464 DenseMap<unsigned, unsigned> SamplerLiteralToBindingMap;
David Neto22f144c2017-06-12 14:26:21 -04002465
David Neto862b7d82018-06-14 18:48:37 -04002466 // We might have samplers in the sampler map that are not used
2467 // in the translation unit. We need to allocate variables
2468 // for them and bindings too.
2469 DenseSet<unsigned> used_bindings;
David Neto22f144c2017-06-12 14:26:21 -04002470
David Neto862b7d82018-06-14 18:48:37 -04002471 auto* var_fn = M.getFunction("clspv.sampler.var.literal");
2472 if (!var_fn) return;
2473 for (auto user : var_fn->users()) {
2474 // Populate SamplerLiteralToDescriptorSetMap and
2475 // SamplerLiteralToBindingMap.
2476 //
2477 // Look for calls like
2478 // call %opencl.sampler_t addrspace(2)*
2479 // @clspv.sampler.var.literal(
2480 // i32 descriptor,
2481 // i32 binding,
2482 // i32 index-into-sampler-map)
2483 if (auto* call = dyn_cast<CallInst>(user)) {
2484 const auto index_into_sampler_map =
2485 dyn_cast<ConstantInt>(call->getArgOperand(2))->getZExtValue();
2486 if (index_into_sampler_map >= sampler_map.size()) {
2487 errs() << "Out of bounds index to sampler map: " << index_into_sampler_map;
2488 llvm_unreachable("bad sampler init: out of bounds");
2489 }
2490
2491 auto sampler_value = sampler_map[index_into_sampler_map].first;
2492 const auto descriptor_set = static_cast<unsigned>(
2493 dyn_cast<ConstantInt>(call->getArgOperand(0))->getZExtValue());
2494 const auto binding = static_cast<unsigned>(
2495 dyn_cast<ConstantInt>(call->getArgOperand(1))->getZExtValue());
2496
2497 SamplerLiteralToDescriptorSetMap[sampler_value] = descriptor_set;
2498 SamplerLiteralToBindingMap[sampler_value] = binding;
2499 used_bindings.insert(binding);
2500 }
2501 }
2502
2503 unsigned index = 0;
2504 for (auto SamplerLiteral : sampler_map) {
David Neto22f144c2017-06-12 14:26:21 -04002505 // Generate OpVariable.
2506 //
2507 // GIDOps[0] : Result Type ID
2508 // GIDOps[1] : Storage Class
2509 SPIRVOperandList Ops;
2510
David Neto257c3892018-04-11 13:19:45 -04002511 Ops << MkId(lookupType(SamplerTy))
2512 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002513
David Neto862b7d82018-06-14 18:48:37 -04002514 auto sampler_var_id = nextID++;
2515 auto *Inst = new SPIRVInstruction(spv::OpVariable, sampler_var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002516 SPIRVInstList.push_back(Inst);
2517
David Neto862b7d82018-06-14 18:48:37 -04002518 SamplerMapIndexToIDMap[index] = sampler_var_id;
2519 SamplerLiteralToIDMap[SamplerLiteral.first] = sampler_var_id;
David Neto22f144c2017-06-12 14:26:21 -04002520
2521 // Find Insert Point for OpDecorate.
2522 auto DecoInsertPoint =
2523 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2524 [](SPIRVInstruction *Inst) -> bool {
2525 return Inst->getOpcode() != spv::OpDecorate &&
2526 Inst->getOpcode() != spv::OpMemberDecorate &&
2527 Inst->getOpcode() != spv::OpExtInstImport;
2528 });
2529
2530 // Ops[0] = Target ID
2531 // Ops[1] = Decoration (DescriptorSet)
2532 // Ops[2] = LiteralNumber according to Decoration
2533 Ops.clear();
2534
David Neto862b7d82018-06-14 18:48:37 -04002535 unsigned descriptor_set;
2536 unsigned binding;
2537 if(SamplerLiteralToBindingMap.find(SamplerLiteral.first) == SamplerLiteralToBindingMap.end()) {
2538 // This sampler is not actually used. Find the next one.
2539 for (binding = 0; used_bindings.count(binding); binding++)
2540 ;
2541 descriptor_set = 0; // Literal samplers always use descriptor set 0.
2542 used_bindings.insert(binding);
2543 } else {
2544 descriptor_set = SamplerLiteralToDescriptorSetMap[SamplerLiteral.first];
2545 binding = SamplerLiteralToBindingMap[SamplerLiteral.first];
2546 }
2547
2548 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationDescriptorSet)
2549 << MkNum(descriptor_set);
David Neto22f144c2017-06-12 14:26:21 -04002550
David Neto44795152017-07-13 15:45:28 -04002551 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002552 << SamplerLiteral.second << "\",descriptorSet,"
David Neto862b7d82018-06-14 18:48:37 -04002553 << descriptor_set << ",binding," << binding << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002554
David Neto87846742018-04-11 17:36:22 -04002555 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002556 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2557
2558 // Ops[0] = Target ID
2559 // Ops[1] = Decoration (Binding)
2560 // Ops[2] = LiteralNumber according to Decoration
2561 Ops.clear();
David Neto862b7d82018-06-14 18:48:37 -04002562 Ops << MkId(sampler_var_id) << MkNum(spv::DecorationBinding)
2563 << MkNum(binding);
David Neto22f144c2017-06-12 14:26:21 -04002564
David Neto87846742018-04-11 17:36:22 -04002565 auto *BindDecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002566 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
David Neto862b7d82018-06-14 18:48:37 -04002567
2568 index++;
David Neto22f144c2017-06-12 14:26:21 -04002569 }
David Neto862b7d82018-06-14 18:48:37 -04002570}
David Neto22f144c2017-06-12 14:26:21 -04002571
David Neto862b7d82018-06-14 18:48:37 -04002572void SPIRVProducerPass::GenerateResourceVars(Module &M) {
2573 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2574 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04002575
David Neto862b7d82018-06-14 18:48:37 -04002576 // Generate variables. Make one for each of resource var info object.
2577 for (auto *info : ModuleOrderedResourceVars) {
2578 Type *type = info->var_fn->getReturnType();
2579 // Remap the address space for opaque types.
2580 switch (info->arg_kind) {
2581 case clspv::ArgKind::Sampler:
2582 case clspv::ArgKind::ReadOnlyImage:
2583 case clspv::ArgKind::WriteOnlyImage:
2584 type = PointerType::get(type->getPointerElementType(),
2585 clspv::AddressSpace::UniformConstant);
2586 break;
2587 default:
2588 break;
2589 }
David Neto22f144c2017-06-12 14:26:21 -04002590
David Neto862b7d82018-06-14 18:48:37 -04002591 info->var_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002592
David Neto862b7d82018-06-14 18:48:37 -04002593 const auto type_id = lookupType(type);
2594 const auto sc = GetStorageClassForArgKind(info->arg_kind);
2595 SPIRVOperandList Ops;
2596 Ops << MkId(type_id) << MkNum(sc);
David Neto22f144c2017-06-12 14:26:21 -04002597
David Neto862b7d82018-06-14 18:48:37 -04002598 auto *Inst = new SPIRVInstruction(spv::OpVariable, info->var_id, Ops);
2599 SPIRVInstList.push_back(Inst);
2600
2601 // Map calls to the variable-builtin-function.
2602 for (auto &U : info->var_fn->uses()) {
2603 if (auto *call = dyn_cast<CallInst>(U.getUser())) {
2604 const auto set = unsigned(
2605 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
2606 const auto binding = unsigned(
2607 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
2608 if (set == info->descriptor_set && binding == info->binding) {
2609 switch (info->arg_kind) {
2610 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002611 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002612 case clspv::ArgKind::Pod:
2613 // The call maps to the variable directly.
2614 VMap[call] = info->var_id;
2615 break;
2616 case clspv::ArgKind::Sampler:
2617 case clspv::ArgKind::ReadOnlyImage:
2618 case clspv::ArgKind::WriteOnlyImage:
2619 // The call maps to a load we generate later.
2620 ResourceVarDeferredLoadCalls[call] = info->var_id;
2621 break;
2622 default:
2623 llvm_unreachable("Unhandled arg kind");
2624 }
2625 }
David Neto22f144c2017-06-12 14:26:21 -04002626 }
David Neto862b7d82018-06-14 18:48:37 -04002627 }
2628 }
David Neto22f144c2017-06-12 14:26:21 -04002629
David Neto862b7d82018-06-14 18:48:37 -04002630 // Generate associated decorations.
David Neto22f144c2017-06-12 14:26:21 -04002631
David Neto862b7d82018-06-14 18:48:37 -04002632 // Find Insert Point for OpDecorate.
2633 auto DecoInsertPoint =
2634 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2635 [](SPIRVInstruction *Inst) -> bool {
2636 return Inst->getOpcode() != spv::OpDecorate &&
2637 Inst->getOpcode() != spv::OpMemberDecorate &&
2638 Inst->getOpcode() != spv::OpExtInstImport;
2639 });
2640
2641 SPIRVOperandList Ops;
2642 for (auto *info : ModuleOrderedResourceVars) {
2643 // Decorate with DescriptorSet and Binding.
2644 Ops.clear();
2645 Ops << MkId(info->var_id) << MkNum(spv::DecorationDescriptorSet)
2646 << MkNum(info->descriptor_set);
2647 SPIRVInstList.insert(DecoInsertPoint,
2648 new SPIRVInstruction(spv::OpDecorate, Ops));
2649
2650 Ops.clear();
2651 Ops << MkId(info->var_id) << MkNum(spv::DecorationBinding)
2652 << MkNum(info->binding);
2653 SPIRVInstList.insert(DecoInsertPoint,
2654 new SPIRVInstruction(spv::OpDecorate, Ops));
2655
2656 // Generate NonWritable and NonReadable
2657 switch (info->arg_kind) {
2658 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -04002659 case clspv::ArgKind::BufferUBO:
David Neto862b7d82018-06-14 18:48:37 -04002660 if (info->var_fn->getReturnType()->getPointerAddressSpace() ==
2661 clspv::AddressSpace::Constant) {
2662 Ops.clear();
2663 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2664 SPIRVInstList.insert(DecoInsertPoint,
2665 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002666 }
David Neto862b7d82018-06-14 18:48:37 -04002667 break;
2668 case clspv::ArgKind::ReadOnlyImage:
2669 Ops.clear();
2670 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonWritable);
2671 SPIRVInstList.insert(DecoInsertPoint,
2672 new SPIRVInstruction(spv::OpDecorate, Ops));
2673 break;
2674 case clspv::ArgKind::WriteOnlyImage:
2675 Ops.clear();
2676 Ops << MkId(info->var_id) << MkNum(spv::DecorationNonReadable);
2677 SPIRVInstList.insert(DecoInsertPoint,
2678 new SPIRVInstruction(spv::OpDecorate, Ops));
2679 break;
2680 default:
2681 break;
David Neto22f144c2017-06-12 14:26:21 -04002682 }
2683 }
2684}
2685
2686void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
David Neto78383442018-06-15 20:31:56 -04002687 Module& M = *GV.getParent();
David Neto22f144c2017-06-12 14:26:21 -04002688 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2689 ValueMapType &VMap = getValueMap();
2690 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002691 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002692
2693 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2694 Type *Ty = GV.getType();
2695 PointerType *PTy = cast<PointerType>(Ty);
2696
2697 uint32_t InitializerID = 0;
2698
2699 // Workgroup size is handled differently (it goes into a constant)
2700 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2701 std::vector<bool> HasMDVec;
2702 uint32_t PrevXDimCst = 0xFFFFFFFF;
2703 uint32_t PrevYDimCst = 0xFFFFFFFF;
2704 uint32_t PrevZDimCst = 0xFFFFFFFF;
2705 for (Function &Func : *GV.getParent()) {
2706 if (Func.isDeclaration()) {
2707 continue;
2708 }
2709
2710 // We only need to check kernels.
2711 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2712 continue;
2713 }
2714
2715 if (const MDNode *MD =
2716 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2717 uint32_t CurXDimCst = static_cast<uint32_t>(
2718 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2719 uint32_t CurYDimCst = static_cast<uint32_t>(
2720 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2721 uint32_t CurZDimCst = static_cast<uint32_t>(
2722 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2723
2724 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2725 PrevZDimCst == 0xFFFFFFFF) {
2726 PrevXDimCst = CurXDimCst;
2727 PrevYDimCst = CurYDimCst;
2728 PrevZDimCst = CurZDimCst;
2729 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2730 CurZDimCst != PrevZDimCst) {
2731 llvm_unreachable(
2732 "reqd_work_group_size must be the same across all kernels");
2733 } else {
2734 continue;
2735 }
2736
2737 //
2738 // Generate OpConstantComposite.
2739 //
2740 // Ops[0] : Result Type ID
2741 // Ops[1] : Constant size for x dimension.
2742 // Ops[2] : Constant size for y dimension.
2743 // Ops[3] : Constant size for z dimension.
2744 SPIRVOperandList Ops;
2745
2746 uint32_t XDimCstID =
2747 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2748 uint32_t YDimCstID =
2749 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2750 uint32_t ZDimCstID =
2751 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2752
2753 InitializerID = nextID;
2754
David Neto257c3892018-04-11 13:19:45 -04002755 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2756 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002757
David Neto87846742018-04-11 17:36:22 -04002758 auto *Inst =
2759 new SPIRVInstruction(spv::OpConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002760 SPIRVInstList.push_back(Inst);
2761
2762 HasMDVec.push_back(true);
2763 } else {
2764 HasMDVec.push_back(false);
2765 }
2766 }
2767
2768 // Check all kernels have same definitions for work_group_size.
2769 bool HasMD = false;
2770 if (!HasMDVec.empty()) {
2771 HasMD = HasMDVec[0];
2772 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2773 if (HasMD != HasMDVec[i]) {
2774 llvm_unreachable(
2775 "Kernels should have consistent work group size definition");
2776 }
2777 }
2778 }
2779
2780 // If all kernels do not have metadata for reqd_work_group_size, generate
2781 // OpSpecConstants for x/y/z dimension.
2782 if (!HasMD) {
2783 //
2784 // Generate OpSpecConstants for x/y/z dimension.
2785 //
2786 // Ops[0] : Result Type ID
2787 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2788 uint32_t XDimCstID = 0;
2789 uint32_t YDimCstID = 0;
2790 uint32_t ZDimCstID = 0;
2791
David Neto22f144c2017-06-12 14:26:21 -04002792 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002793 uint32_t result_type_id =
2794 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002795
David Neto257c3892018-04-11 13:19:45 -04002796 // X Dimension
2797 Ops << MkId(result_type_id) << MkNum(1);
2798 XDimCstID = nextID++;
2799 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002800 new SPIRVInstruction(spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002801
2802 // Y Dimension
2803 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002804 Ops << MkId(result_type_id) << MkNum(1);
2805 YDimCstID = nextID++;
2806 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002807 new SPIRVInstruction(spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002808
2809 // Z Dimension
2810 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002811 Ops << MkId(result_type_id) << MkNum(1);
2812 ZDimCstID = nextID++;
2813 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002814 new SPIRVInstruction(spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002815
David Neto22f144c2017-06-12 14:26:21 -04002816
David Neto257c3892018-04-11 13:19:45 -04002817 BuiltinDimVec.push_back(XDimCstID);
2818 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002819 BuiltinDimVec.push_back(ZDimCstID);
2820
David Neto22f144c2017-06-12 14:26:21 -04002821
2822 //
2823 // Generate OpSpecConstantComposite.
2824 //
2825 // Ops[0] : Result Type ID
2826 // Ops[1] : Constant size for x dimension.
2827 // Ops[2] : Constant size for y dimension.
2828 // Ops[3] : Constant size for z dimension.
2829 InitializerID = nextID;
2830
2831 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002832 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2833 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002834
David Neto87846742018-04-11 17:36:22 -04002835 auto *Inst =
2836 new SPIRVInstruction(spv::OpSpecConstantComposite, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002837 SPIRVInstList.push_back(Inst);
2838 }
2839 }
2840
David Neto22f144c2017-06-12 14:26:21 -04002841 VMap[&GV] = nextID;
2842
2843 //
2844 // Generate OpVariable.
2845 //
2846 // GIDOps[0] : Result Type ID
2847 // GIDOps[1] : Storage Class
2848 SPIRVOperandList Ops;
2849
David Neto85082642018-03-24 06:55:20 -07002850 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002851 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002852
David Neto85082642018-03-24 06:55:20 -07002853 if (GV.hasInitializer()) {
2854 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002855 }
2856
David Neto85082642018-03-24 06:55:20 -07002857 const bool module_scope_constant_external_init =
David Neto862b7d82018-06-14 18:48:37 -04002858 (AS == AddressSpace::Constant) && GV.hasInitializer() &&
David Neto85082642018-03-24 06:55:20 -07002859 clspv::Option::ModuleConstantsInStorageBuffer();
2860
2861 if (0 != InitializerID) {
2862 if (!module_scope_constant_external_init) {
2863 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002864 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002865 }
2866 }
2867 const uint32_t var_id = nextID++;
2868
David Neto87846742018-04-11 17:36:22 -04002869 auto *Inst = new SPIRVInstruction(spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002870 SPIRVInstList.push_back(Inst);
2871
2872 // If we have a builtin.
2873 if (spv::BuiltInMax != BuiltinType) {
2874 // Find Insert Point for OpDecorate.
2875 auto DecoInsertPoint =
2876 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2877 [](SPIRVInstruction *Inst) -> bool {
2878 return Inst->getOpcode() != spv::OpDecorate &&
2879 Inst->getOpcode() != spv::OpMemberDecorate &&
2880 Inst->getOpcode() != spv::OpExtInstImport;
2881 });
2882 //
2883 // Generate OpDecorate.
2884 //
2885 // DOps[0] = Target ID
2886 // DOps[1] = Decoration (Builtin)
2887 // DOps[2] = BuiltIn ID
2888 uint32_t ResultID;
2889
2890 // WorkgroupSize is different, we decorate the constant composite that has
2891 // its value, rather than the variable that we use to access the value.
2892 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2893 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002894 // Save both the value and variable IDs for later.
2895 WorkgroupSizeValueID = InitializerID;
2896 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002897 } else {
2898 ResultID = VMap[&GV];
2899 }
2900
2901 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002902 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2903 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002904
David Neto87846742018-04-11 17:36:22 -04002905 auto *DescDecoInst = new SPIRVInstruction(spv::OpDecorate, DOps);
David Neto22f144c2017-06-12 14:26:21 -04002906 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002907 } else if (module_scope_constant_external_init) {
2908 // This module scope constant is initialized from a storage buffer with data
2909 // provided by the host at binding 0 of the next descriptor set.
David Neto78383442018-06-15 20:31:56 -04002910 const uint32_t descriptor_set = TakeDescriptorIndex(&M);
David Neto85082642018-03-24 06:55:20 -07002911
David Neto862b7d82018-06-14 18:48:37 -04002912 // Emit the intializer to the descriptor map file.
David Neto85082642018-03-24 06:55:20 -07002913 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2914 // that later to other types, like uniform buffer.
2915 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2916 << ",binding,0,kind,buffer,hexbytes,";
2917 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2918 descriptorMapOut << "\n";
2919
2920 // Find Insert Point for OpDecorate.
2921 auto DecoInsertPoint =
2922 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2923 [](SPIRVInstruction *Inst) -> bool {
2924 return Inst->getOpcode() != spv::OpDecorate &&
2925 Inst->getOpcode() != spv::OpMemberDecorate &&
2926 Inst->getOpcode() != spv::OpExtInstImport;
2927 });
2928
David Neto257c3892018-04-11 13:19:45 -04002929 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002930 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002931 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2932 DecoInsertPoint = SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04002933 DecoInsertPoint, new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto85082642018-03-24 06:55:20 -07002934
2935 // OpDecorate %var DescriptorSet <descriptor_set>
2936 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002937 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2938 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002939 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04002940 new SPIRVInstruction(spv::OpDecorate, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002941 }
2942}
2943
David Netoc6f3ab22018-04-06 18:02:31 -04002944void SPIRVProducerPass::GenerateWorkgroupVars() {
2945 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
Alan Baker202c8c72018-08-13 13:47:44 -04002946 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
2947 ++spec_id) {
2948 LocalArgInfo& info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04002949
2950 // Generate OpVariable.
2951 //
2952 // GIDOps[0] : Result Type ID
2953 // GIDOps[1] : Storage Class
2954 SPIRVOperandList Ops;
2955 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2956
2957 SPIRVInstList.push_back(
David Neto87846742018-04-11 17:36:22 -04002958 new SPIRVInstruction(spv::OpVariable, info.variable_id, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04002959 }
2960}
2961
David Neto862b7d82018-06-14 18:48:37 -04002962void SPIRVProducerPass::GenerateDescriptorMapInfo(const DataLayout &DL,
2963 Function &F) {
David Netoc5fb5242018-07-30 13:28:31 -04002964 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2965 return;
2966 }
David Neto862b7d82018-06-14 18:48:37 -04002967 // Gather the list of resources that are used by this function's arguments.
2968 auto &resource_var_at_index = FunctionToResourceVarsMap[&F];
2969
2970 auto remap_arg_kind = [](StringRef argKind) {
2971 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2972 ? "pod_ubo"
2973 : argKind;
2974 };
2975
2976 auto *fty = F.getType()->getPointerElementType();
2977 auto *func_ty = dyn_cast<FunctionType>(fty);
2978
2979 // If we've clustereed POD arguments, then argument details are in metadata.
2980 // If an argument maps to a resource variable, then get descriptor set and
2981 // binding from the resoure variable. Other info comes from the metadata.
2982 const auto *arg_map = F.getMetadata("kernel_arg_map");
2983 if (arg_map) {
2984 for (const auto &arg : arg_map->operands()) {
2985 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
Kévin PETITa353c832018-03-20 23:21:21 +00002986 assert(arg_node->getNumOperands() == 7);
David Neto862b7d82018-06-14 18:48:37 -04002987 const auto name =
2988 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2989 const auto old_index =
2990 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2991 // Remapped argument index
2992 const auto new_index =
2993 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2994 const auto offset =
2995 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
Kévin PETITa353c832018-03-20 23:21:21 +00002996 const auto arg_size =
2997 dyn_extract<ConstantInt>(arg_node->getOperand(4))->getZExtValue();
David Neto862b7d82018-06-14 18:48:37 -04002998 const auto argKind = remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00002999 dyn_cast<MDString>(arg_node->getOperand(5))->getString());
David Neto862b7d82018-06-14 18:48:37 -04003000 const auto spec_id =
Kévin PETITa353c832018-03-20 23:21:21 +00003001 dyn_extract<ConstantInt>(arg_node->getOperand(6))->getSExtValue();
David Neto862b7d82018-06-14 18:48:37 -04003002 if (spec_id > 0) {
3003 // This was a pointer-to-local argument. It is not associated with a
3004 // resource variable.
3005 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
3006 << ",argOrdinal," << old_index << ",argKind,"
3007 << argKind << ",arrayElemSize,"
Alan Bakerfcda9482018-10-02 17:09:59 -04003008 << GetTypeAllocSize(
David Neto862b7d82018-06-14 18:48:37 -04003009 func_ty->getParamType(unsigned(new_index))
Alan Bakerfcda9482018-10-02 17:09:59 -04003010 ->getPointerElementType(), DL)
David Neto862b7d82018-06-14 18:48:37 -04003011 << ",arrayNumElemSpecId," << spec_id << "\n";
3012 } else {
3013 auto *info = resource_var_at_index[new_index];
3014 assert(info);
3015 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
3016 << ",argOrdinal," << old_index << ",descriptorSet,"
3017 << info->descriptor_set << ",binding," << info->binding
Kévin PETITa353c832018-03-20 23:21:21 +00003018 << ",offset," << offset << ",argKind," << argKind;
3019 if (argKind.startswith("pod")) {
3020 descriptorMapOut << ",argSize," << arg_size;
3021 }
3022 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003023 }
3024 }
3025 } else {
3026 // There is no argument map.
3027 // Take descriptor info from the resource variable calls.
Kévin PETITa353c832018-03-20 23:21:21 +00003028 // Take argument name and size from the arguments list.
David Neto862b7d82018-06-14 18:48:37 -04003029
3030 SmallVector<Argument *, 4> arguments;
3031 for (auto &arg : F.args()) {
3032 arguments.push_back(&arg);
3033 }
3034
3035 unsigned arg_index = 0;
3036 for (auto *info : resource_var_at_index) {
3037 if (info) {
Kévin PETITa353c832018-03-20 23:21:21 +00003038 auto arg = arguments[arg_index];
3039 unsigned arg_size;
3040 if (info->arg_kind == clspv::ArgKind::Pod) {
3041 arg_size = DL.getTypeStoreSize(arg->getType());
3042 }
3043
David Neto862b7d82018-06-14 18:48:37 -04003044 descriptorMapOut << "kernel," << F.getName() << ",arg,"
Kévin PETITa353c832018-03-20 23:21:21 +00003045 << arg->getName() << ",argOrdinal,"
David Neto862b7d82018-06-14 18:48:37 -04003046 << arg_index << ",descriptorSet,"
3047 << info->descriptor_set << ",binding," << info->binding
3048 << ",offset," << 0 << ",argKind,"
3049 << remap_arg_kind(
Kévin PETITa353c832018-03-20 23:21:21 +00003050 clspv::GetArgKindName(info->arg_kind));
3051 if (info->arg_kind == clspv::ArgKind::Pod) {
3052 descriptorMapOut << ",argSize," << arg_size;
3053 }
3054 descriptorMapOut << "\n";
David Neto862b7d82018-06-14 18:48:37 -04003055 }
3056 arg_index++;
3057 }
3058 // Generate mappings for pointer-to-local arguments.
3059 for (arg_index = 0; arg_index < arguments.size(); ++arg_index) {
3060 Argument *arg = arguments[arg_index];
Alan Baker202c8c72018-08-13 13:47:44 -04003061 auto where = LocalArgSpecIds.find(arg);
3062 if (where != LocalArgSpecIds.end()) {
3063 auto &local_arg_info = LocalSpecIdInfoMap[where->second];
David Neto862b7d82018-06-14 18:48:37 -04003064 descriptorMapOut << "kernel," << F.getName() << ",arg,"
3065 << arg->getName() << ",argOrdinal," << arg_index
3066 << ",argKind,"
3067 << "local"
3068 << ",arrayElemSize,"
Alan Bakerfcda9482018-10-02 17:09:59 -04003069 << GetTypeAllocSize(local_arg_info.elem_type, DL)
David Neto862b7d82018-06-14 18:48:37 -04003070 << ",arrayNumElemSpecId," << local_arg_info.spec_id
3071 << "\n";
3072 }
3073 }
3074 }
3075}
3076
David Neto22f144c2017-06-12 14:26:21 -04003077void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Neto78383442018-06-15 20:31:56 -04003078 Module& M = *F.getParent();
3079 const DataLayout &DL = M.getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04003080 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3081 ValueMapType &VMap = getValueMap();
3082 EntryPointVecType &EntryPoints = getEntryPointVec();
David Neto22f144c2017-06-12 14:26:21 -04003083 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
3084 auto &GlobalConstArgSet = getGlobalConstArgSet();
3085
3086 FunctionType *FTy = F.getFunctionType();
3087
3088 //
David Neto22f144c2017-06-12 14:26:21 -04003089 // Generate OPFunction.
3090 //
3091
3092 // FOps[0] : Result Type ID
3093 // FOps[1] : Function Control
3094 // FOps[2] : Function Type ID
3095 SPIRVOperandList FOps;
3096
3097 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04003098 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04003099
3100 // Check function attributes for SPIRV Function Control.
3101 uint32_t FuncControl = spv::FunctionControlMaskNone;
3102 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
3103 FuncControl |= spv::FunctionControlInlineMask;
3104 }
3105 if (F.hasFnAttribute(Attribute::NoInline)) {
3106 FuncControl |= spv::FunctionControlDontInlineMask;
3107 }
3108 // TODO: Check llvm attribute for Function Control Pure.
3109 if (F.hasFnAttribute(Attribute::ReadOnly)) {
3110 FuncControl |= spv::FunctionControlPureMask;
3111 }
3112 // TODO: Check llvm attribute for Function Control Const.
3113 if (F.hasFnAttribute(Attribute::ReadNone)) {
3114 FuncControl |= spv::FunctionControlConstMask;
3115 }
3116
David Neto257c3892018-04-11 13:19:45 -04003117 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04003118
3119 uint32_t FTyID;
3120 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3121 SmallVector<Type *, 4> NewFuncParamTys;
3122 FunctionType *NewFTy =
3123 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
3124 FTyID = lookupType(NewFTy);
3125 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07003126 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04003127 if (GlobalConstFuncTyMap.count(FTy)) {
3128 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
3129 } else {
3130 FTyID = lookupType(FTy);
3131 }
3132 }
3133
David Neto257c3892018-04-11 13:19:45 -04003134 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04003135
3136 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3137 EntryPoints.push_back(std::make_pair(&F, nextID));
3138 }
3139
3140 VMap[&F] = nextID;
3141
David Neto482550a2018-03-24 05:21:07 -07003142 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05003143 errs() << "Function " << F.getName() << " is " << nextID << "\n";
3144 }
David Neto22f144c2017-06-12 14:26:21 -04003145 // Generate SPIRV instruction for function.
David Neto87846742018-04-11 17:36:22 -04003146 auto *FuncInst = new SPIRVInstruction(spv::OpFunction, nextID++, FOps);
David Neto22f144c2017-06-12 14:26:21 -04003147 SPIRVInstList.push_back(FuncInst);
3148
3149 //
3150 // Generate OpFunctionParameter for Normal function.
3151 //
3152
3153 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3154 // Iterate Argument for name instead of param type from function type.
3155 unsigned ArgIdx = 0;
3156 for (Argument &Arg : F.args()) {
3157 VMap[&Arg] = nextID;
3158
3159 // ParamOps[0] : Result Type ID
3160 SPIRVOperandList ParamOps;
3161
3162 // Find SPIRV instruction for parameter type.
3163 uint32_t ParamTyID = lookupType(Arg.getType());
3164 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
3165 if (GlobalConstFuncTyMap.count(FTy)) {
3166 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
3167 Type *EleTy = PTy->getPointerElementType();
3168 Type *ArgTy =
3169 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
3170 ParamTyID = lookupType(ArgTy);
3171 GlobalConstArgSet.insert(&Arg);
3172 }
3173 }
3174 }
David Neto257c3892018-04-11 13:19:45 -04003175 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04003176
3177 // Generate SPIRV instruction for parameter.
David Neto87846742018-04-11 17:36:22 -04003178 auto *ParamInst =
3179 new SPIRVInstruction(spv::OpFunctionParameter, nextID++, ParamOps);
David Neto22f144c2017-06-12 14:26:21 -04003180 SPIRVInstList.push_back(ParamInst);
3181
3182 ArgIdx++;
3183 }
3184 }
3185}
3186
David Neto5c22a252018-03-15 16:07:41 -04003187void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04003188 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3189 EntryPointVecType &EntryPoints = getEntryPointVec();
3190 ValueMapType &VMap = getValueMap();
3191 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
3192 uint32_t &ExtInstImportID = getOpExtInstImportID();
3193 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
3194
3195 // Set up insert point.
3196 auto InsertPoint = SPIRVInstList.begin();
3197
3198 //
3199 // Generate OpCapability
3200 //
3201 // TODO: Which llvm information is mapped to SPIRV Capapbility?
3202
3203 // Ops[0] = Capability
3204 SPIRVOperandList Ops;
3205
David Neto87846742018-04-11 17:36:22 -04003206 auto *CapInst =
3207 new SPIRVInstruction(spv::OpCapability, {MkNum(spv::CapabilityShader)});
David Neto22f144c2017-06-12 14:26:21 -04003208 SPIRVInstList.insert(InsertPoint, CapInst);
3209
3210 for (Type *Ty : getTypeList()) {
3211 // Find the i16 type.
3212 if (Ty->isIntegerTy(16)) {
3213 // Generate OpCapability for i16 type.
David Neto87846742018-04-11 17:36:22 -04003214 SPIRVInstList.insert(InsertPoint,
3215 new SPIRVInstruction(spv::OpCapability,
3216 {MkNum(spv::CapabilityInt16)}));
David Neto22f144c2017-06-12 14:26:21 -04003217 } else if (Ty->isIntegerTy(64)) {
3218 // Generate OpCapability for i64 type.
David Neto87846742018-04-11 17:36:22 -04003219 SPIRVInstList.insert(InsertPoint,
3220 new SPIRVInstruction(spv::OpCapability,
3221 {MkNum(spv::CapabilityInt64)}));
David Neto22f144c2017-06-12 14:26:21 -04003222 } else if (Ty->isHalfTy()) {
3223 // Generate OpCapability for half type.
3224 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003225 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3226 {MkNum(spv::CapabilityFloat16)}));
David Neto22f144c2017-06-12 14:26:21 -04003227 } else if (Ty->isDoubleTy()) {
3228 // Generate OpCapability for double type.
3229 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04003230 InsertPoint, new SPIRVInstruction(spv::OpCapability,
3231 {MkNum(spv::CapabilityFloat64)}));
David Neto22f144c2017-06-12 14:26:21 -04003232 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3233 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003234 if (STy->getName().equals("opencl.image2d_wo_t") ||
3235 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003236 // Generate OpCapability for write only image type.
3237 SPIRVInstList.insert(
3238 InsertPoint,
3239 new SPIRVInstruction(
David Neto87846742018-04-11 17:36:22 -04003240 spv::OpCapability,
3241 {MkNum(spv::CapabilityStorageImageWriteWithoutFormat)}));
David Neto22f144c2017-06-12 14:26:21 -04003242 }
3243 }
3244 }
3245 }
3246
David Neto5c22a252018-03-15 16:07:41 -04003247 { // OpCapability ImageQuery
3248 bool hasImageQuery = false;
3249 for (const char *imageQuery : {
3250 "_Z15get_image_width14ocl_image2d_ro",
3251 "_Z15get_image_width14ocl_image2d_wo",
3252 "_Z16get_image_height14ocl_image2d_ro",
3253 "_Z16get_image_height14ocl_image2d_wo",
3254 }) {
3255 if (module.getFunction(imageQuery)) {
3256 hasImageQuery = true;
3257 break;
3258 }
3259 }
3260 if (hasImageQuery) {
David Neto87846742018-04-11 17:36:22 -04003261 auto *ImageQueryCapInst = new SPIRVInstruction(
3262 spv::OpCapability, {MkNum(spv::CapabilityImageQuery)});
David Neto5c22a252018-03-15 16:07:41 -04003263 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3264 }
3265 }
3266
David Neto22f144c2017-06-12 14:26:21 -04003267 if (hasVariablePointers()) {
3268 //
3269 // Generate OpCapability and OpExtension
3270 //
3271
3272 //
3273 // Generate OpCapability.
3274 //
3275 // Ops[0] = Capability
3276 //
3277 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003278 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003279
David Neto87846742018-04-11 17:36:22 -04003280 SPIRVInstList.insert(InsertPoint,
3281 new SPIRVInstruction(spv::OpCapability, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003282
3283 //
3284 // Generate OpExtension.
3285 //
3286 // Ops[0] = Name (Literal String)
3287 //
David Netoa772fd12017-08-04 14:17:33 -04003288 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3289 "SPV_KHR_variable_pointers"}) {
David Neto22f144c2017-06-12 14:26:21 -04003290
David Neto87846742018-04-11 17:36:22 -04003291 auto *ExtensionInst =
3292 new SPIRVInstruction(spv::OpExtension, {MkString(extension)});
David Netoa772fd12017-08-04 14:17:33 -04003293 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003294 }
David Neto22f144c2017-06-12 14:26:21 -04003295 }
3296
3297 if (ExtInstImportID) {
3298 ++InsertPoint;
3299 }
3300
3301 //
3302 // Generate OpMemoryModel
3303 //
3304 // Memory model for Vulkan will always be GLSL450.
3305
3306 // Ops[0] = Addressing Model
3307 // Ops[1] = Memory Model
3308 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003309 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003310
David Neto87846742018-04-11 17:36:22 -04003311 auto *MemModelInst = new SPIRVInstruction(spv::OpMemoryModel, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003312 SPIRVInstList.insert(InsertPoint, MemModelInst);
3313
3314 //
3315 // Generate OpEntryPoint
3316 //
3317 for (auto EntryPoint : EntryPoints) {
3318 // Ops[0] = Execution Model
3319 // Ops[1] = EntryPoint ID
3320 // Ops[2] = Name (Literal String)
3321 // ...
3322 //
3323 // TODO: Do we need to consider Interface ID for forward references???
3324 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003325 const StringRef& name = EntryPoint.first->getName();
3326 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3327 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003328
David Neto22f144c2017-06-12 14:26:21 -04003329 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003330 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003331 }
3332
David Neto87846742018-04-11 17:36:22 -04003333 auto *EntryPointInst = new SPIRVInstruction(spv::OpEntryPoint, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003334 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3335 }
3336
3337 for (auto EntryPoint : EntryPoints) {
3338 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3339 ->getMetadata("reqd_work_group_size")) {
3340
3341 if (!BuiltinDimVec.empty()) {
3342 llvm_unreachable(
3343 "Kernels should have consistent work group size definition");
3344 }
3345
3346 //
3347 // Generate OpExecutionMode
3348 //
3349
3350 // Ops[0] = Entry Point ID
3351 // Ops[1] = Execution Mode
3352 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3353 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003354 Ops << MkId(EntryPoint.second)
3355 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003356
3357 uint32_t XDim = static_cast<uint32_t>(
3358 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3359 uint32_t YDim = static_cast<uint32_t>(
3360 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3361 uint32_t ZDim = static_cast<uint32_t>(
3362 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3363
David Neto257c3892018-04-11 13:19:45 -04003364 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003365
David Neto87846742018-04-11 17:36:22 -04003366 auto *ExecModeInst = new SPIRVInstruction(spv::OpExecutionMode, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003367 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3368 }
3369 }
3370
3371 //
3372 // Generate OpSource.
3373 //
3374 // Ops[0] = SourceLanguage ID
3375 // Ops[1] = Version (LiteralNum)
3376 //
3377 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003378 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003379
David Neto87846742018-04-11 17:36:22 -04003380 auto *OpenSourceInst = new SPIRVInstruction(spv::OpSource, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003381 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3382
3383 if (!BuiltinDimVec.empty()) {
3384 //
3385 // Generate OpDecorates for x/y/z dimension.
3386 //
3387 // Ops[0] = Target ID
3388 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003389 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003390
3391 // X Dimension
3392 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003393 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
David Neto87846742018-04-11 17:36:22 -04003394 SPIRVInstList.insert(InsertPoint,
3395 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003396
3397 // Y Dimension
3398 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003399 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
David Neto87846742018-04-11 17:36:22 -04003400 SPIRVInstList.insert(InsertPoint,
3401 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003402
3403 // Z Dimension
3404 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003405 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
David Neto87846742018-04-11 17:36:22 -04003406 SPIRVInstList.insert(InsertPoint,
3407 new SPIRVInstruction(spv::OpDecorate, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003408 }
3409}
3410
David Netob6e2e062018-04-25 10:32:06 -04003411void SPIRVProducerPass::GenerateEntryPointInitialStores() {
3412 // Work around a driver bug. Initializers on Private variables might not
3413 // work. So the start of the kernel should store the initializer value to the
3414 // variables. Yes, *every* entry point pays this cost if *any* entry point
3415 // uses this builtin. At this point I judge this to be an acceptable tradeoff
3416 // of complexity vs. runtime, for a broken driver.
3417 // TODO(dneto): Remove this at some point once fixed drivers are widely available.
3418 if (WorkgroupSizeVarID) {
3419 assert(WorkgroupSizeValueID);
3420
3421 SPIRVOperandList Ops;
3422 Ops << MkId(WorkgroupSizeVarID) << MkId(WorkgroupSizeValueID);
3423
3424 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
3425 getSPIRVInstList().push_back(Inst);
3426 }
3427}
3428
David Neto22f144c2017-06-12 14:26:21 -04003429void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3430 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3431 ValueMapType &VMap = getValueMap();
3432
David Netob6e2e062018-04-25 10:32:06 -04003433 const bool IsKernel = F.getCallingConv() == CallingConv::SPIR_KERNEL;
David Neto22f144c2017-06-12 14:26:21 -04003434
3435 for (BasicBlock &BB : F) {
3436 // Register BasicBlock to ValueMap.
3437 VMap[&BB] = nextID;
3438
3439 //
3440 // Generate OpLabel for Basic Block.
3441 //
3442 SPIRVOperandList Ops;
David Neto87846742018-04-11 17:36:22 -04003443 auto *Inst = new SPIRVInstruction(spv::OpLabel, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003444 SPIRVInstList.push_back(Inst);
3445
David Neto6dcd4712017-06-23 11:06:47 -04003446 // OpVariable instructions must come first.
3447 for (Instruction &I : BB) {
3448 if (isa<AllocaInst>(I)) {
3449 GenerateInstruction(I);
3450 }
3451 }
3452
David Neto22f144c2017-06-12 14:26:21 -04003453 if (&BB == &F.getEntryBlock() && IsKernel) {
David Netob6e2e062018-04-25 10:32:06 -04003454 if (clspv::Option::HackInitializers()) {
3455 GenerateEntryPointInitialStores();
3456 }
David Neto22f144c2017-06-12 14:26:21 -04003457 }
3458
3459 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003460 if (!isa<AllocaInst>(I)) {
3461 GenerateInstruction(I);
3462 }
David Neto22f144c2017-06-12 14:26:21 -04003463 }
3464 }
3465}
3466
3467spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3468 const std::map<CmpInst::Predicate, spv::Op> Map = {
3469 {CmpInst::ICMP_EQ, spv::OpIEqual},
3470 {CmpInst::ICMP_NE, spv::OpINotEqual},
3471 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3472 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3473 {CmpInst::ICMP_ULT, spv::OpULessThan},
3474 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3475 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3476 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3477 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3478 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3479 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3480 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3481 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3482 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3483 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3484 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3485 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3486 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3487 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3488 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3489 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3490 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3491
3492 assert(0 != Map.count(I->getPredicate()));
3493
3494 return Map.at(I->getPredicate());
3495}
3496
3497spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3498 const std::map<unsigned, spv::Op> Map{
3499 {Instruction::Trunc, spv::OpUConvert},
3500 {Instruction::ZExt, spv::OpUConvert},
3501 {Instruction::SExt, spv::OpSConvert},
3502 {Instruction::FPToUI, spv::OpConvertFToU},
3503 {Instruction::FPToSI, spv::OpConvertFToS},
3504 {Instruction::UIToFP, spv::OpConvertUToF},
3505 {Instruction::SIToFP, spv::OpConvertSToF},
3506 {Instruction::FPTrunc, spv::OpFConvert},
3507 {Instruction::FPExt, spv::OpFConvert},
3508 {Instruction::BitCast, spv::OpBitcast}};
3509
3510 assert(0 != Map.count(I.getOpcode()));
3511
3512 return Map.at(I.getOpcode());
3513}
3514
3515spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
Kévin Petit24272b62018-10-18 19:16:12 +00003516 if (I.getType()->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003517 switch (I.getOpcode()) {
3518 default:
3519 break;
3520 case Instruction::Or:
3521 return spv::OpLogicalOr;
3522 case Instruction::And:
3523 return spv::OpLogicalAnd;
3524 case Instruction::Xor:
3525 return spv::OpLogicalNotEqual;
3526 }
3527 }
3528
3529 const std::map<unsigned, spv::Op> Map {
3530 {Instruction::Add, spv::OpIAdd},
3531 {Instruction::FAdd, spv::OpFAdd},
3532 {Instruction::Sub, spv::OpISub},
3533 {Instruction::FSub, spv::OpFSub},
3534 {Instruction::Mul, spv::OpIMul},
3535 {Instruction::FMul, spv::OpFMul},
3536 {Instruction::UDiv, spv::OpUDiv},
3537 {Instruction::SDiv, spv::OpSDiv},
3538 {Instruction::FDiv, spv::OpFDiv},
3539 {Instruction::URem, spv::OpUMod},
3540 {Instruction::SRem, spv::OpSRem},
3541 {Instruction::FRem, spv::OpFRem},
3542 {Instruction::Or, spv::OpBitwiseOr},
3543 {Instruction::Xor, spv::OpBitwiseXor},
3544 {Instruction::And, spv::OpBitwiseAnd},
3545 {Instruction::Shl, spv::OpShiftLeftLogical},
3546 {Instruction::LShr, spv::OpShiftRightLogical},
3547 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3548
3549 assert(0 != Map.count(I.getOpcode()));
3550
3551 return Map.at(I.getOpcode());
3552}
3553
3554void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3555 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3556 ValueMapType &VMap = getValueMap();
David Neto22f144c2017-06-12 14:26:21 -04003557 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3558 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3559
3560 // Register Instruction to ValueMap.
3561 if (0 == VMap[&I]) {
3562 VMap[&I] = nextID;
3563 }
3564
3565 switch (I.getOpcode()) {
3566 default: {
3567 if (Instruction::isCast(I.getOpcode())) {
3568 //
3569 // Generate SPIRV instructions for cast operators.
3570 //
3571
David Netod2de94a2017-08-28 17:27:47 -04003572
3573 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003574 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003575 auto toI8 = Ty == Type::getInt8Ty(Context);
3576 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003577 // Handle zext, sext and uitofp with i1 type specially.
3578 if ((I.getOpcode() == Instruction::ZExt ||
3579 I.getOpcode() == Instruction::SExt ||
3580 I.getOpcode() == Instruction::UIToFP) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003581 OpTy->isIntOrIntVectorTy(1)) {
David Neto22f144c2017-06-12 14:26:21 -04003582 //
3583 // Generate OpSelect.
3584 //
3585
3586 // Ops[0] = Result Type ID
3587 // Ops[1] = Condition ID
3588 // Ops[2] = True Constant ID
3589 // Ops[3] = False Constant ID
3590 SPIRVOperandList Ops;
3591
David Neto257c3892018-04-11 13:19:45 -04003592 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003593
David Neto22f144c2017-06-12 14:26:21 -04003594 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003595 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003596
3597 uint32_t TrueID = 0;
3598 if (I.getOpcode() == Instruction::ZExt) {
3599 APInt One(32, 1);
3600 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3601 } else if (I.getOpcode() == Instruction::SExt) {
3602 APInt MinusOne(32, UINT64_MAX, true);
3603 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3604 } else {
3605 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3606 }
David Neto257c3892018-04-11 13:19:45 -04003607 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003608
3609 uint32_t FalseID = 0;
3610 if (I.getOpcode() == Instruction::ZExt) {
3611 FalseID = VMap[Constant::getNullValue(I.getType())];
3612 } else if (I.getOpcode() == Instruction::SExt) {
3613 FalseID = VMap[Constant::getNullValue(I.getType())];
3614 } else {
3615 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3616 }
David Neto257c3892018-04-11 13:19:45 -04003617 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003618
David Neto87846742018-04-11 17:36:22 -04003619 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003620 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003621 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3622 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3623 // 8 bits.
3624 // Before:
3625 // %result = trunc i32 %a to i8
3626 // After
3627 // %result = OpBitwiseAnd %uint %a %uint_255
3628
3629 SPIRVOperandList Ops;
3630
David Neto257c3892018-04-11 13:19:45 -04003631 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003632
3633 Type *UintTy = Type::getInt32Ty(Context);
3634 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003636
David Neto87846742018-04-11 17:36:22 -04003637 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Netod2de94a2017-08-28 17:27:47 -04003638 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003639 } else {
3640 // Ops[0] = Result Type ID
3641 // Ops[1] = Source Value ID
3642 SPIRVOperandList Ops;
3643
David Neto257c3892018-04-11 13:19:45 -04003644 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003645
David Neto87846742018-04-11 17:36:22 -04003646 auto *Inst = new SPIRVInstruction(GetSPIRVCastOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003647 SPIRVInstList.push_back(Inst);
3648 }
3649 } else if (isa<BinaryOperator>(I)) {
3650 //
3651 // Generate SPIRV instructions for binary operators.
3652 //
3653
3654 // Handle xor with i1 type specially.
3655 if (I.getOpcode() == Instruction::Xor &&
3656 I.getType() == Type::getInt1Ty(Context) &&
Kévin Petit24272b62018-10-18 19:16:12 +00003657 ((isa<ConstantInt>(I.getOperand(0)) &&
3658 !cast<ConstantInt>(I.getOperand(0))->isZero()) ||
3659 (isa<ConstantInt>(I.getOperand(1)) &&
3660 !cast<ConstantInt>(I.getOperand(1))->isZero()))) {
David Neto22f144c2017-06-12 14:26:21 -04003661 //
3662 // Generate OpLogicalNot.
3663 //
3664 // Ops[0] = Result Type ID
3665 // Ops[1] = Operand
3666 SPIRVOperandList Ops;
3667
David Neto257c3892018-04-11 13:19:45 -04003668 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003669
3670 Value *CondV = I.getOperand(0);
3671 if (isa<Constant>(I.getOperand(0))) {
3672 CondV = I.getOperand(1);
3673 }
David Neto257c3892018-04-11 13:19:45 -04003674 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003675
David Neto87846742018-04-11 17:36:22 -04003676 auto *Inst = new SPIRVInstruction(spv::OpLogicalNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003677 SPIRVInstList.push_back(Inst);
3678 } else {
3679 // Ops[0] = Result Type ID
3680 // Ops[1] = Operand 0
3681 // Ops[2] = Operand 1
3682 SPIRVOperandList Ops;
3683
David Neto257c3892018-04-11 13:19:45 -04003684 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3685 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003686
David Neto87846742018-04-11 17:36:22 -04003687 auto *Inst =
3688 new SPIRVInstruction(GetSPIRVBinaryOpcode(I), nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003689 SPIRVInstList.push_back(Inst);
3690 }
3691 } else {
3692 I.print(errs());
3693 llvm_unreachable("Unsupported instruction???");
3694 }
3695 break;
3696 }
3697 case Instruction::GetElementPtr: {
3698 auto &GlobalConstArgSet = getGlobalConstArgSet();
3699
3700 //
3701 // Generate OpAccessChain.
3702 //
3703 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3704
3705 //
3706 // Generate OpAccessChain.
3707 //
3708
3709 // Ops[0] = Result Type ID
3710 // Ops[1] = Base ID
3711 // Ops[2] ... Ops[n] = Indexes ID
3712 SPIRVOperandList Ops;
3713
David Neto1a1a0582017-07-07 12:01:44 -04003714 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003715 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3716 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3717 // Use pointer type with private address space for global constant.
3718 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003719 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003720 }
David Neto257c3892018-04-11 13:19:45 -04003721
3722 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003723
David Neto862b7d82018-06-14 18:48:37 -04003724 // Generate the base pointer.
3725 Ops << MkId(VMap[GEP->getPointerOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04003726
David Neto862b7d82018-06-14 18:48:37 -04003727 // TODO(dneto): Simplify the following?
David Neto22f144c2017-06-12 14:26:21 -04003728
3729 //
3730 // Follows below rules for gep.
3731 //
David Neto862b7d82018-06-14 18:48:37 -04003732 // 1. If gep's first index is 0 generate OpAccessChain and ignore gep's
3733 // first index.
David Neto22f144c2017-06-12 14:26:21 -04003734 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3735 // first index.
3736 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3737 // use gep's first index.
3738 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3739 // gep's first index.
3740 //
3741 spv::Op Opcode = spv::OpAccessChain;
3742 unsigned offset = 0;
3743 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
David Neto862b7d82018-06-14 18:48:37 -04003744 if (CstInt->getZExtValue() == 0) {
David Neto22f144c2017-06-12 14:26:21 -04003745 offset = 1;
David Neto862b7d82018-06-14 18:48:37 -04003746 } else if (CstInt->getZExtValue() != 0) {
David Neto22f144c2017-06-12 14:26:21 -04003747 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003748 }
David Neto862b7d82018-06-14 18:48:37 -04003749 } else {
David Neto22f144c2017-06-12 14:26:21 -04003750 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003751 }
3752
3753 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003754 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003755 // Do we need to generate ArrayStride? Check against the GEP result type
3756 // rather than the pointer type of the base because when indexing into
3757 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3758 // for something else in the SPIR-V.
3759 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
Alan Bakerfcda9482018-10-02 17:09:59 -04003760 switch (GetStorageClass(ResultType->getAddressSpace())) {
3761 case spv::StorageClassStorageBuffer:
3762 case spv::StorageClassUniform:
David Neto1a1a0582017-07-07 12:01:44 -04003763 // Save the need to generate an ArrayStride decoration. But defer
3764 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003765 getTypesNeedingArrayStride().insert(ResultType);
Alan Bakerfcda9482018-10-02 17:09:59 -04003766 break;
3767 default:
3768 break;
David Neto1a1a0582017-07-07 12:01:44 -04003769 }
David Neto22f144c2017-06-12 14:26:21 -04003770 }
3771
3772 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003773 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003774 }
3775
David Neto87846742018-04-11 17:36:22 -04003776 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003777 SPIRVInstList.push_back(Inst);
3778 break;
3779 }
3780 case Instruction::ExtractValue: {
3781 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3782 // Ops[0] = Result Type ID
3783 // Ops[1] = Composite ID
3784 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3785 SPIRVOperandList Ops;
3786
David Neto257c3892018-04-11 13:19:45 -04003787 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003788
3789 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003790 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003791
3792 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003793 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003794 }
3795
David Neto87846742018-04-11 17:36:22 -04003796 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003797 SPIRVInstList.push_back(Inst);
3798 break;
3799 }
3800 case Instruction::InsertValue: {
3801 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3802 // Ops[0] = Result Type ID
3803 // Ops[1] = Object ID
3804 // Ops[2] = Composite ID
3805 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3806 SPIRVOperandList Ops;
3807
3808 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003809 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003810
3811 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003812 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003813
3814 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003815 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003816
3817 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003818 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003819 }
3820
David Neto87846742018-04-11 17:36:22 -04003821 auto *Inst = new SPIRVInstruction(spv::OpCompositeInsert, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003822 SPIRVInstList.push_back(Inst);
3823 break;
3824 }
3825 case Instruction::Select: {
3826 //
3827 // Generate OpSelect.
3828 //
3829
3830 // Ops[0] = Result Type ID
3831 // Ops[1] = Condition ID
3832 // Ops[2] = True Constant ID
3833 // Ops[3] = False Constant ID
3834 SPIRVOperandList Ops;
3835
3836 // Find SPIRV instruction for parameter type.
3837 auto Ty = I.getType();
3838 if (Ty->isPointerTy()) {
3839 auto PointeeTy = Ty->getPointerElementType();
3840 if (PointeeTy->isStructTy() &&
3841 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3842 Ty = PointeeTy;
3843 }
3844 }
3845
David Neto257c3892018-04-11 13:19:45 -04003846 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3847 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003848
David Neto87846742018-04-11 17:36:22 -04003849 auto *Inst = new SPIRVInstruction(spv::OpSelect, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003850 SPIRVInstList.push_back(Inst);
3851 break;
3852 }
3853 case Instruction::ExtractElement: {
3854 // Handle <4 x i8> type manually.
3855 Type *CompositeTy = I.getOperand(0)->getType();
3856 if (is4xi8vec(CompositeTy)) {
3857 //
3858 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3859 // <4 x i8>.
3860 //
3861
3862 //
3863 // Generate OpShiftRightLogical
3864 //
3865 // Ops[0] = Result Type ID
3866 // Ops[1] = Operand 0
3867 // Ops[2] = Operand 1
3868 //
3869 SPIRVOperandList Ops;
3870
David Neto257c3892018-04-11 13:19:45 -04003871 Ops << MkId(lookupType(CompositeTy));
David Neto22f144c2017-06-12 14:26:21 -04003872
3873 uint32_t Op0ID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003874 Ops << MkId(Op0ID);
David Neto22f144c2017-06-12 14:26:21 -04003875
3876 uint32_t Op1ID = 0;
3877 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3878 // Handle constant index.
3879 uint64_t Idx = CI->getZExtValue();
3880 Value *ShiftAmount =
3881 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3882 Op1ID = VMap[ShiftAmount];
3883 } else {
3884 // Handle variable index.
3885 SPIRVOperandList TmpOps;
3886
David Neto257c3892018-04-11 13:19:45 -04003887 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3888 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003889
3890 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003891 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003892
3893 Op1ID = nextID;
3894
David Neto87846742018-04-11 17:36:22 -04003895 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003896 SPIRVInstList.push_back(TmpInst);
3897 }
David Neto257c3892018-04-11 13:19:45 -04003898 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003899
3900 uint32_t ShiftID = nextID;
3901
David Neto87846742018-04-11 17:36:22 -04003902 auto *Inst =
3903 new SPIRVInstruction(spv::OpShiftRightLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003904 SPIRVInstList.push_back(Inst);
3905
3906 //
3907 // Generate OpBitwiseAnd
3908 //
3909 // Ops[0] = Result Type ID
3910 // Ops[1] = Operand 0
3911 // Ops[2] = Operand 1
3912 //
3913 Ops.clear();
3914
David Neto257c3892018-04-11 13:19:45 -04003915 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003916
3917 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003918 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003919
David Neto9b2d6252017-09-06 15:47:37 -04003920 // Reset mapping for this value to the result of the bitwise and.
3921 VMap[&I] = nextID;
3922
David Neto87846742018-04-11 17:36:22 -04003923 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003924 SPIRVInstList.push_back(Inst);
3925 break;
3926 }
3927
3928 // Ops[0] = Result Type ID
3929 // Ops[1] = Composite ID
3930 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3931 SPIRVOperandList Ops;
3932
David Neto257c3892018-04-11 13:19:45 -04003933 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003934
3935 spv::Op Opcode = spv::OpCompositeExtract;
3936 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003937 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003938 } else {
David Neto257c3892018-04-11 13:19:45 -04003939 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003940 Opcode = spv::OpVectorExtractDynamic;
3941 }
3942
David Neto87846742018-04-11 17:36:22 -04003943 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003944 SPIRVInstList.push_back(Inst);
3945 break;
3946 }
3947 case Instruction::InsertElement: {
3948 // Handle <4 x i8> type manually.
3949 Type *CompositeTy = I.getOperand(0)->getType();
3950 if (is4xi8vec(CompositeTy)) {
3951 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3952 uint32_t CstFFID = VMap[CstFF];
3953
3954 uint32_t ShiftAmountID = 0;
3955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3956 // Handle constant index.
3957 uint64_t Idx = CI->getZExtValue();
3958 Value *ShiftAmount =
3959 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3960 ShiftAmountID = VMap[ShiftAmount];
3961 } else {
3962 // Handle variable index.
3963 SPIRVOperandList TmpOps;
3964
David Neto257c3892018-04-11 13:19:45 -04003965 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3966 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003967
3968 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003969 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003970
3971 ShiftAmountID = nextID;
3972
David Neto87846742018-04-11 17:36:22 -04003973 auto *TmpInst = new SPIRVInstruction(spv::OpIMul, nextID++, TmpOps);
David Neto22f144c2017-06-12 14:26:21 -04003974 SPIRVInstList.push_back(TmpInst);
3975 }
3976
3977 //
3978 // Generate mask operations.
3979 //
3980
3981 // ShiftLeft mask according to index of insertelement.
3982 SPIRVOperandList Ops;
3983
David Neto257c3892018-04-11 13:19:45 -04003984 const uint32_t ResTyID = lookupType(CompositeTy);
3985 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003986
3987 uint32_t MaskID = nextID;
3988
David Neto87846742018-04-11 17:36:22 -04003989 auto *Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003990 SPIRVInstList.push_back(Inst);
3991
3992 // Inverse mask.
3993 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003994 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04003995
3996 uint32_t InvMaskID = nextID;
3997
David Neto87846742018-04-11 17:36:22 -04003998 Inst = new SPIRVInstruction(spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04003999 SPIRVInstList.push_back(Inst);
4000
4001 // Apply mask.
4002 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004003 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004004
4005 uint32_t OrgValID = nextID;
4006
David Neto87846742018-04-11 17:36:22 -04004007 Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004008 SPIRVInstList.push_back(Inst);
4009
4010 // Create correct value according to index of insertelement.
4011 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004012 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004013
4014 uint32_t InsertValID = nextID;
4015
David Neto87846742018-04-11 17:36:22 -04004016 Inst = new SPIRVInstruction(spv::OpShiftLeftLogical, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004017 SPIRVInstList.push_back(Inst);
4018
4019 // Insert value to original value.
4020 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004021 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004022
David Netoa394f392017-08-26 20:45:29 -04004023 VMap[&I] = nextID;
4024
David Neto87846742018-04-11 17:36:22 -04004025 Inst = new SPIRVInstruction(spv::OpBitwiseOr, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004026 SPIRVInstList.push_back(Inst);
4027
4028 break;
4029 }
4030
David Neto22f144c2017-06-12 14:26:21 -04004031 SPIRVOperandList Ops;
4032
James Priced26efea2018-06-09 23:28:32 +01004033 // Ops[0] = Result Type ID
4034 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004035
4036 spv::Op Opcode = spv::OpCompositeInsert;
4037 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004038 const auto value = CI->getZExtValue();
4039 assert(value <= UINT32_MAX);
James Priced26efea2018-06-09 23:28:32 +01004040 // Ops[1] = Object ID
4041 // Ops[2] = Composite ID
4042 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4043 Ops << MkId(VMap[I.getOperand(1)])
4044 << MkId(VMap[I.getOperand(0)])
4045 << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004046 } else {
James Priced26efea2018-06-09 23:28:32 +01004047 // Ops[1] = Composite ID
4048 // Ops[2] = Object ID
4049 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4050 Ops << MkId(VMap[I.getOperand(0)])
4051 << MkId(VMap[I.getOperand(1)])
4052 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04004053 Opcode = spv::OpVectorInsertDynamic;
4054 }
4055
David Neto87846742018-04-11 17:36:22 -04004056 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004057 SPIRVInstList.push_back(Inst);
4058 break;
4059 }
4060 case Instruction::ShuffleVector: {
4061 // Ops[0] = Result Type ID
4062 // Ops[1] = Vector 1 ID
4063 // Ops[2] = Vector 2 ID
4064 // Ops[3] ... Ops[n] = Components (Literal Number)
4065 SPIRVOperandList Ops;
4066
David Neto257c3892018-04-11 13:19:45 -04004067 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4068 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004069
4070 uint64_t NumElements = 0;
4071 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4072 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4073
4074 if (Cst->isNullValue()) {
4075 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004076 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004077 }
4078 } else if (const ConstantDataSequential *CDS =
4079 dyn_cast<ConstantDataSequential>(Cst)) {
4080 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4081 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004082 const auto value = CDS->getElementAsInteger(i);
4083 assert(value <= UINT32_MAX);
4084 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004085 }
4086 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4087 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4088 auto Op = CV->getOperand(i);
4089
4090 uint32_t literal = 0;
4091
4092 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4093 literal = static_cast<uint32_t>(CI->getZExtValue());
4094 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4095 literal = 0xFFFFFFFFu;
4096 } else {
4097 Op->print(errs());
4098 llvm_unreachable("Unsupported element in ConstantVector!");
4099 }
4100
David Neto257c3892018-04-11 13:19:45 -04004101 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004102 }
4103 } else {
4104 Cst->print(errs());
4105 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4106 }
4107 }
4108
David Neto87846742018-04-11 17:36:22 -04004109 auto *Inst = new SPIRVInstruction(spv::OpVectorShuffle, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004110 SPIRVInstList.push_back(Inst);
4111 break;
4112 }
4113 case Instruction::ICmp:
4114 case Instruction::FCmp: {
4115 CmpInst *CmpI = cast<CmpInst>(&I);
4116
David Netod4ca2e62017-07-06 18:47:35 -04004117 // Pointer equality is invalid.
4118 Type* ArgTy = CmpI->getOperand(0)->getType();
4119 if (isa<PointerType>(ArgTy)) {
4120 CmpI->print(errs());
4121 std::string name = I.getParent()->getParent()->getName();
4122 errs()
4123 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4124 << "in function " << name << "\n";
4125 llvm_unreachable("Pointer equality check is invalid");
4126 break;
4127 }
4128
David Neto257c3892018-04-11 13:19:45 -04004129 // Ops[0] = Result Type ID
4130 // Ops[1] = Operand 1 ID
4131 // Ops[2] = Operand 2 ID
4132 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004133
David Neto257c3892018-04-11 13:19:45 -04004134 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4135 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004136
4137 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
David Neto87846742018-04-11 17:36:22 -04004138 auto *Inst = new SPIRVInstruction(Opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004139 SPIRVInstList.push_back(Inst);
4140 break;
4141 }
4142 case Instruction::Br: {
4143 // Branch instrucion is deferred because it needs label's ID. Record slot's
4144 // location on SPIRVInstructionList.
4145 DeferredInsts.push_back(
4146 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4147 break;
4148 }
4149 case Instruction::Switch: {
4150 I.print(errs());
4151 llvm_unreachable("Unsupported instruction???");
4152 break;
4153 }
4154 case Instruction::IndirectBr: {
4155 I.print(errs());
4156 llvm_unreachable("Unsupported instruction???");
4157 break;
4158 }
4159 case Instruction::PHI: {
4160 // Branch instrucion is deferred because it needs label's ID. Record slot's
4161 // location on SPIRVInstructionList.
4162 DeferredInsts.push_back(
4163 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4164 break;
4165 }
4166 case Instruction::Alloca: {
4167 //
4168 // Generate OpVariable.
4169 //
4170 // Ops[0] : Result Type ID
4171 // Ops[1] : Storage Class
4172 SPIRVOperandList Ops;
4173
David Neto257c3892018-04-11 13:19:45 -04004174 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004175
David Neto87846742018-04-11 17:36:22 -04004176 auto *Inst = new SPIRVInstruction(spv::OpVariable, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004177 SPIRVInstList.push_back(Inst);
4178 break;
4179 }
4180 case Instruction::Load: {
4181 LoadInst *LD = cast<LoadInst>(&I);
4182 //
4183 // Generate OpLoad.
4184 //
4185
David Neto0a2f98d2017-09-15 19:38:40 -04004186 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004187 uint32_t PointerID = VMap[LD->getPointerOperand()];
4188
4189 // This is a hack to work around what looks like a driver bug.
4190 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004191 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4192 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004193 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004194 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004195 // Generate a bitwise-and of the original value with itself.
4196 // We should have been able to get away with just an OpCopyObject,
4197 // but we need something more complex to get past certain driver bugs.
4198 // This is ridiculous, but necessary.
4199 // TODO(dneto): Revisit this once drivers fix their bugs.
4200
4201 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004202 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4203 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004204
David Neto87846742018-04-11 17:36:22 -04004205 auto *Inst = new SPIRVInstruction(spv::OpBitwiseAnd, nextID++, Ops);
David Neto0a2f98d2017-09-15 19:38:40 -04004206 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004207 break;
4208 }
4209
4210 // This is the normal path. Generate a load.
4211
David Neto22f144c2017-06-12 14:26:21 -04004212 // Ops[0] = Result Type ID
4213 // Ops[1] = Pointer ID
4214 // Ops[2] ... Ops[n] = Optional Memory Access
4215 //
4216 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004217
David Neto22f144c2017-06-12 14:26:21 -04004218 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004219 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004220
David Neto87846742018-04-11 17:36:22 -04004221 auto *Inst = new SPIRVInstruction(spv::OpLoad, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004222 SPIRVInstList.push_back(Inst);
4223 break;
4224 }
4225 case Instruction::Store: {
4226 StoreInst *ST = cast<StoreInst>(&I);
4227 //
4228 // Generate OpStore.
4229 //
4230
4231 // Ops[0] = Pointer ID
4232 // Ops[1] = Object ID
4233 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4234 //
4235 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004236 SPIRVOperandList Ops;
4237 Ops << MkId(VMap[ST->getPointerOperand()])
4238 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004239
David Neto87846742018-04-11 17:36:22 -04004240 auto *Inst = new SPIRVInstruction(spv::OpStore, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004241 SPIRVInstList.push_back(Inst);
4242 break;
4243 }
4244 case Instruction::AtomicCmpXchg: {
4245 I.print(errs());
4246 llvm_unreachable("Unsupported instruction???");
4247 break;
4248 }
4249 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004250 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4251
4252 spv::Op opcode;
4253
4254 switch (AtomicRMW->getOperation()) {
4255 default:
4256 I.print(errs());
4257 llvm_unreachable("Unsupported instruction???");
4258 case llvm::AtomicRMWInst::Add:
4259 opcode = spv::OpAtomicIAdd;
4260 break;
4261 case llvm::AtomicRMWInst::Sub:
4262 opcode = spv::OpAtomicISub;
4263 break;
4264 case llvm::AtomicRMWInst::Xchg:
4265 opcode = spv::OpAtomicExchange;
4266 break;
4267 case llvm::AtomicRMWInst::Min:
4268 opcode = spv::OpAtomicSMin;
4269 break;
4270 case llvm::AtomicRMWInst::Max:
4271 opcode = spv::OpAtomicSMax;
4272 break;
4273 case llvm::AtomicRMWInst::UMin:
4274 opcode = spv::OpAtomicUMin;
4275 break;
4276 case llvm::AtomicRMWInst::UMax:
4277 opcode = spv::OpAtomicUMax;
4278 break;
4279 case llvm::AtomicRMWInst::And:
4280 opcode = spv::OpAtomicAnd;
4281 break;
4282 case llvm::AtomicRMWInst::Or:
4283 opcode = spv::OpAtomicOr;
4284 break;
4285 case llvm::AtomicRMWInst::Xor:
4286 opcode = spv::OpAtomicXor;
4287 break;
4288 }
4289
4290 //
4291 // Generate OpAtomic*.
4292 //
4293 SPIRVOperandList Ops;
4294
David Neto257c3892018-04-11 13:19:45 -04004295 Ops << MkId(lookupType(I.getType()))
4296 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004297
4298 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004299 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004300 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004301
4302 const auto ConstantMemorySemantics = ConstantInt::get(
4303 IntTy, spv::MemorySemanticsUniformMemoryMask |
4304 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004305 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004306
David Neto257c3892018-04-11 13:19:45 -04004307 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004308
4309 VMap[&I] = nextID;
4310
David Neto87846742018-04-11 17:36:22 -04004311 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
Neil Henning39672102017-09-29 14:33:13 +01004312 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004313 break;
4314 }
4315 case Instruction::Fence: {
4316 I.print(errs());
4317 llvm_unreachable("Unsupported instruction???");
4318 break;
4319 }
4320 case Instruction::Call: {
4321 CallInst *Call = dyn_cast<CallInst>(&I);
4322 Function *Callee = Call->getCalledFunction();
4323
Alan Baker202c8c72018-08-13 13:47:44 -04004324 if (Callee->getName().startswith(clspv::ResourceAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04004325 if (ResourceVarDeferredLoadCalls.count(Call) && Call->hasNUsesOrMore(1)) {
4326 // Generate an OpLoad
4327 SPIRVOperandList Ops;
4328 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004329
David Neto862b7d82018-06-14 18:48:37 -04004330 Ops << MkId(lookupType(Call->getType()->getPointerElementType()))
4331 << MkId(ResourceVarDeferredLoadCalls[Call]);
4332
4333 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
4334 SPIRVInstList.push_back(Inst);
4335 VMap[Call] = load_id;
4336 break;
4337
4338 } else {
4339 // This maps to an OpVariable we've already generated.
4340 // No code is generated for the call.
4341 }
4342 break;
Alan Baker202c8c72018-08-13 13:47:44 -04004343 } else if (Callee->getName().startswith(clspv::WorkgroupAccessorFunction())) {
4344 // Don't codegen an instruction here, but instead map this call directly
4345 // to the workgroup variable id.
4346 int spec_id = cast<ConstantInt>(Call->getOperand(0))->getSExtValue();
4347 const auto &info = LocalSpecIdInfoMap[spec_id];
4348 VMap[Call] = info.variable_id;
4349 break;
David Neto862b7d82018-06-14 18:48:37 -04004350 }
4351
4352 // Sampler initializers become a load of the corresponding sampler.
4353
4354 if (Callee->getName().equals("clspv.sampler.var.literal")) {
4355 // Map this to a load from the variable.
4356 const auto index_into_sampler_map =
4357 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4358
4359 // Generate an OpLoad
David Neto22f144c2017-06-12 14:26:21 -04004360 SPIRVOperandList Ops;
David Neto862b7d82018-06-14 18:48:37 -04004361 const auto load_id = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04004362
David Neto257c3892018-04-11 13:19:45 -04004363 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
David Neto862b7d82018-06-14 18:48:37 -04004364 << MkId(SamplerMapIndexToIDMap[index_into_sampler_map]);
David Neto22f144c2017-06-12 14:26:21 -04004365
David Neto862b7d82018-06-14 18:48:37 -04004366 auto *Inst = new SPIRVInstruction(spv::OpLoad, load_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004367 SPIRVInstList.push_back(Inst);
David Neto862b7d82018-06-14 18:48:37 -04004368 VMap[Call] = load_id;
David Neto22f144c2017-06-12 14:26:21 -04004369 break;
4370 }
4371
4372 if (Callee->getName().startswith("spirv.atomic")) {
4373 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4374 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4375 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4376 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4377 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4378 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4379 .Case("spirv.atomic_compare_exchange",
4380 spv::OpAtomicCompareExchange)
4381 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4382 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4383 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4384 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4385 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4386 .Case("spirv.atomic_or", spv::OpAtomicOr)
4387 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4388 .Default(spv::OpNop);
4389
4390 //
4391 // Generate OpAtomic*.
4392 //
4393 SPIRVOperandList Ops;
4394
David Neto257c3892018-04-11 13:19:45 -04004395 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004396
4397 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004398 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004399 }
4400
4401 VMap[&I] = nextID;
4402
David Neto87846742018-04-11 17:36:22 -04004403 auto *Inst = new SPIRVInstruction(opcode, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004404 SPIRVInstList.push_back(Inst);
4405 break;
4406 }
4407
4408 if (Callee->getName().startswith("_Z3dot")) {
4409 // If the argument is a vector type, generate OpDot
4410 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4411 //
4412 // Generate OpDot.
4413 //
4414 SPIRVOperandList Ops;
4415
David Neto257c3892018-04-11 13:19:45 -04004416 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004417
4418 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004419 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004420 }
4421
4422 VMap[&I] = nextID;
4423
David Neto87846742018-04-11 17:36:22 -04004424 auto *Inst = new SPIRVInstruction(spv::OpDot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004425 SPIRVInstList.push_back(Inst);
4426 } else {
4427 //
4428 // Generate OpFMul.
4429 //
4430 SPIRVOperandList Ops;
4431
David Neto257c3892018-04-11 13:19:45 -04004432 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004433
4434 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004435 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004436 }
4437
4438 VMap[&I] = nextID;
4439
David Neto87846742018-04-11 17:36:22 -04004440 auto *Inst = new SPIRVInstruction(spv::OpFMul, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004441 SPIRVInstList.push_back(Inst);
4442 }
4443 break;
4444 }
4445
David Neto8505ebf2017-10-13 18:50:50 -04004446 if (Callee->getName().startswith("_Z4fmod")) {
4447 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4448 // The sign for a non-zero result is taken from x.
4449 // (Try an example.)
4450 // So translate to OpFRem
4451
4452 SPIRVOperandList Ops;
4453
David Neto257c3892018-04-11 13:19:45 -04004454 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004455
4456 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004457 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004458 }
4459
4460 VMap[&I] = nextID;
4461
David Neto87846742018-04-11 17:36:22 -04004462 auto *Inst = new SPIRVInstruction(spv::OpFRem, nextID++, Ops);
David Neto8505ebf2017-10-13 18:50:50 -04004463 SPIRVInstList.push_back(Inst);
4464 break;
4465 }
4466
David Neto22f144c2017-06-12 14:26:21 -04004467 // spirv.store_null.* intrinsics become OpStore's.
4468 if (Callee->getName().startswith("spirv.store_null")) {
4469 //
4470 // Generate OpStore.
4471 //
4472
4473 // Ops[0] = Pointer ID
4474 // Ops[1] = Object ID
4475 // Ops[2] ... Ops[n]
4476 SPIRVOperandList Ops;
4477
4478 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004479 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004480 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004481
David Neto87846742018-04-11 17:36:22 -04004482 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpStore, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004483
4484 break;
4485 }
4486
4487 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4488 if (Callee->getName().startswith("spirv.copy_memory")) {
4489 //
4490 // Generate OpCopyMemory.
4491 //
4492
4493 // Ops[0] = Dst ID
4494 // Ops[1] = Src ID
4495 // Ops[2] = Memory Access
4496 // Ops[3] = Alignment
4497
4498 auto IsVolatile =
4499 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4500
4501 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4502 : spv::MemoryAccessMaskNone;
4503
4504 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4505
4506 auto Alignment =
4507 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4508
David Neto257c3892018-04-11 13:19:45 -04004509 SPIRVOperandList Ops;
4510 Ops << MkId(VMap[Call->getArgOperand(0)])
4511 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4512 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004513
David Neto87846742018-04-11 17:36:22 -04004514 auto *Inst = new SPIRVInstruction(spv::OpCopyMemory, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004515
4516 SPIRVInstList.push_back(Inst);
4517
4518 break;
4519 }
4520
4521 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4522 // with unit.
4523 if (Callee->getName().equals("_Z3absj") ||
4524 Callee->getName().equals("_Z3absDv2_j") ||
4525 Callee->getName().equals("_Z3absDv3_j") ||
4526 Callee->getName().equals("_Z3absDv4_j")) {
4527 VMap[&I] = VMap[Call->getOperand(0)];
4528 break;
4529 }
4530
4531 // barrier is converted to OpControlBarrier
4532 if (Callee->getName().equals("__spirv_control_barrier")) {
4533 //
4534 // Generate OpControlBarrier.
4535 //
4536 // Ops[0] = Execution Scope ID
4537 // Ops[1] = Memory Scope ID
4538 // Ops[2] = Memory Semantics ID
4539 //
4540 Value *ExecutionScope = Call->getArgOperand(0);
4541 Value *MemoryScope = Call->getArgOperand(1);
4542 Value *MemorySemantics = Call->getArgOperand(2);
4543
David Neto257c3892018-04-11 13:19:45 -04004544 SPIRVOperandList Ops;
4545 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4546 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004547
David Neto87846742018-04-11 17:36:22 -04004548 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpControlBarrier, Ops));
David Neto22f144c2017-06-12 14:26:21 -04004549 break;
4550 }
4551
4552 // memory barrier is converted to OpMemoryBarrier
4553 if (Callee->getName().equals("__spirv_memory_barrier")) {
4554 //
4555 // Generate OpMemoryBarrier.
4556 //
4557 // Ops[0] = Memory Scope ID
4558 // Ops[1] = Memory Semantics ID
4559 //
4560 SPIRVOperandList Ops;
4561
David Neto257c3892018-04-11 13:19:45 -04004562 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4563 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004564
David Neto257c3892018-04-11 13:19:45 -04004565 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004566
David Neto87846742018-04-11 17:36:22 -04004567 auto *Inst = new SPIRVInstruction(spv::OpMemoryBarrier, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004568 SPIRVInstList.push_back(Inst);
4569 break;
4570 }
4571
4572 // isinf is converted to OpIsInf
4573 if (Callee->getName().equals("__spirv_isinff") ||
4574 Callee->getName().equals("__spirv_isinfDv2_f") ||
4575 Callee->getName().equals("__spirv_isinfDv3_f") ||
4576 Callee->getName().equals("__spirv_isinfDv4_f")) {
4577 //
4578 // Generate OpIsInf.
4579 //
4580 // Ops[0] = Result Type ID
4581 // Ops[1] = X ID
4582 //
4583 SPIRVOperandList Ops;
4584
David Neto257c3892018-04-11 13:19:45 -04004585 Ops << MkId(lookupType(I.getType()))
4586 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004587
4588 VMap[&I] = nextID;
4589
David Neto87846742018-04-11 17:36:22 -04004590 auto *Inst = new SPIRVInstruction(spv::OpIsInf, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004591 SPIRVInstList.push_back(Inst);
4592 break;
4593 }
4594
4595 // isnan is converted to OpIsNan
4596 if (Callee->getName().equals("__spirv_isnanf") ||
4597 Callee->getName().equals("__spirv_isnanDv2_f") ||
4598 Callee->getName().equals("__spirv_isnanDv3_f") ||
4599 Callee->getName().equals("__spirv_isnanDv4_f")) {
4600 //
4601 // Generate OpIsInf.
4602 //
4603 // Ops[0] = Result Type ID
4604 // Ops[1] = X ID
4605 //
4606 SPIRVOperandList Ops;
4607
David Neto257c3892018-04-11 13:19:45 -04004608 Ops << MkId(lookupType(I.getType()))
4609 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004610
4611 VMap[&I] = nextID;
4612
David Neto87846742018-04-11 17:36:22 -04004613 auto *Inst = new SPIRVInstruction(spv::OpIsNan, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004614 SPIRVInstList.push_back(Inst);
4615 break;
4616 }
4617
4618 // all is converted to OpAll
4619 if (Callee->getName().equals("__spirv_allDv2_i") ||
4620 Callee->getName().equals("__spirv_allDv3_i") ||
4621 Callee->getName().equals("__spirv_allDv4_i")) {
4622 //
4623 // Generate OpAll.
4624 //
4625 // Ops[0] = Result Type ID
4626 // Ops[1] = Vector ID
4627 //
4628 SPIRVOperandList Ops;
4629
David Neto257c3892018-04-11 13:19:45 -04004630 Ops << MkId(lookupType(I.getType()))
4631 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004632
4633 VMap[&I] = nextID;
4634
David Neto87846742018-04-11 17:36:22 -04004635 auto *Inst = new SPIRVInstruction(spv::OpAll, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004636 SPIRVInstList.push_back(Inst);
4637 break;
4638 }
4639
4640 // any is converted to OpAny
4641 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4642 Callee->getName().equals("__spirv_anyDv3_i") ||
4643 Callee->getName().equals("__spirv_anyDv4_i")) {
4644 //
4645 // Generate OpAny.
4646 //
4647 // Ops[0] = Result Type ID
4648 // Ops[1] = Vector ID
4649 //
4650 SPIRVOperandList Ops;
4651
David Neto257c3892018-04-11 13:19:45 -04004652 Ops << MkId(lookupType(I.getType()))
4653 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004654
4655 VMap[&I] = nextID;
4656
David Neto87846742018-04-11 17:36:22 -04004657 auto *Inst = new SPIRVInstruction(spv::OpAny, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004658 SPIRVInstList.push_back(Inst);
4659 break;
4660 }
4661
4662 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4663 // Additionally, OpTypeSampledImage is generated.
4664 if (Callee->getName().equals(
4665 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4666 Callee->getName().equals(
4667 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4668 //
4669 // Generate OpSampledImage.
4670 //
4671 // Ops[0] = Result Type ID
4672 // Ops[1] = Image ID
4673 // Ops[2] = Sampler ID
4674 //
4675 SPIRVOperandList Ops;
4676
4677 Value *Image = Call->getArgOperand(0);
4678 Value *Sampler = Call->getArgOperand(1);
4679 Value *Coordinate = Call->getArgOperand(2);
4680
4681 TypeMapType &OpImageTypeMap = getImageTypeMap();
4682 Type *ImageTy = Image->getType()->getPointerElementType();
4683 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004684 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004685 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004686
4687 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004688
4689 uint32_t SampledImageID = nextID;
4690
David Neto87846742018-04-11 17:36:22 -04004691 auto *Inst = new SPIRVInstruction(spv::OpSampledImage, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004692 SPIRVInstList.push_back(Inst);
4693
4694 //
4695 // Generate OpImageSampleExplicitLod.
4696 //
4697 // Ops[0] = Result Type ID
4698 // Ops[1] = Sampled Image ID
4699 // Ops[2] = Coordinate ID
4700 // Ops[3] = Image Operands Type ID
4701 // Ops[4] ... Ops[n] = Operands ID
4702 //
4703 Ops.clear();
4704
David Neto257c3892018-04-11 13:19:45 -04004705 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4706 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004707
4708 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004709 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004710
4711 VMap[&I] = nextID;
4712
David Neto87846742018-04-11 17:36:22 -04004713 Inst = new SPIRVInstruction(spv::OpImageSampleExplicitLod, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004714 SPIRVInstList.push_back(Inst);
4715 break;
4716 }
4717
4718 // write_imagef is mapped to OpImageWrite.
4719 if (Callee->getName().equals(
4720 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4721 Callee->getName().equals(
4722 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4723 //
4724 // Generate OpImageWrite.
4725 //
4726 // Ops[0] = Image ID
4727 // Ops[1] = Coordinate ID
4728 // Ops[2] = Texel ID
4729 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4730 // Ops[4] ... Ops[n] = (Optional) Operands ID
4731 //
4732 SPIRVOperandList Ops;
4733
4734 Value *Image = Call->getArgOperand(0);
4735 Value *Coordinate = Call->getArgOperand(1);
4736 Value *Texel = Call->getArgOperand(2);
4737
4738 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004739 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004740 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004741 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004742
David Neto87846742018-04-11 17:36:22 -04004743 auto *Inst = new SPIRVInstruction(spv::OpImageWrite, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004744 SPIRVInstList.push_back(Inst);
4745 break;
4746 }
4747
David Neto5c22a252018-03-15 16:07:41 -04004748 // get_image_width is mapped to OpImageQuerySize
4749 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4750 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4751 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4752 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4753 //
4754 // Generate OpImageQuerySize, then pull out the right component.
4755 // Assume 2D image for now.
4756 //
4757 // Ops[0] = Image ID
4758 //
4759 // %sizes = OpImageQuerySizes %uint2 %im
4760 // %result = OpCompositeExtract %uint %sizes 0-or-1
4761 SPIRVOperandList Ops;
4762
4763 // Implement:
4764 // %sizes = OpImageQuerySizes %uint2 %im
4765 uint32_t SizesTypeID =
4766 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004767 Value *Image = Call->getArgOperand(0);
4768 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004769 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004770
4771 uint32_t SizesID = nextID++;
David Neto87846742018-04-11 17:36:22 -04004772 auto *QueryInst =
4773 new SPIRVInstruction(spv::OpImageQuerySize, SizesID, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004774 SPIRVInstList.push_back(QueryInst);
4775
4776 // Reset value map entry since we generated an intermediate instruction.
4777 VMap[&I] = nextID;
4778
4779 // Implement:
4780 // %result = OpCompositeExtract %uint %sizes 0-or-1
4781 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004782 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004783
4784 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004785 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004786
David Neto87846742018-04-11 17:36:22 -04004787 auto *Inst = new SPIRVInstruction(spv::OpCompositeExtract, nextID++, Ops);
David Neto5c22a252018-03-15 16:07:41 -04004788 SPIRVInstList.push_back(Inst);
4789 break;
4790 }
4791
David Neto22f144c2017-06-12 14:26:21 -04004792 // Call instrucion is deferred because it needs function's ID. Record
4793 // slot's location on SPIRVInstructionList.
4794 DeferredInsts.push_back(
4795 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4796
David Neto3fbb4072017-10-16 11:28:14 -04004797 // Check whether the implementation of this call uses an extended
4798 // instruction plus one more value-producing instruction. If so, then
4799 // reserve the id for the extra value-producing slot.
4800 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4801 if (EInst != kGlslExtInstBad) {
4802 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004803 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004804 VMap[&I] = nextID;
4805 nextID++;
4806 }
4807 break;
4808 }
4809 case Instruction::Ret: {
4810 unsigned NumOps = I.getNumOperands();
4811 if (NumOps == 0) {
4812 //
4813 // Generate OpReturn.
4814 //
David Neto87846742018-04-11 17:36:22 -04004815 SPIRVInstList.push_back(new SPIRVInstruction(spv::OpReturn, {}));
David Neto22f144c2017-06-12 14:26:21 -04004816 } else {
4817 //
4818 // Generate OpReturnValue.
4819 //
4820
4821 // Ops[0] = Return Value ID
4822 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004823
4824 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004825
David Neto87846742018-04-11 17:36:22 -04004826 auto *Inst = new SPIRVInstruction(spv::OpReturnValue, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004827 SPIRVInstList.push_back(Inst);
4828 break;
4829 }
4830 break;
4831 }
4832 }
4833}
4834
4835void SPIRVProducerPass::GenerateFuncEpilogue() {
4836 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4837
4838 //
4839 // Generate OpFunctionEnd
4840 //
4841
David Neto87846742018-04-11 17:36:22 -04004842 auto *Inst = new SPIRVInstruction(spv::OpFunctionEnd, {});
David Neto22f144c2017-06-12 14:26:21 -04004843 SPIRVInstList.push_back(Inst);
4844}
4845
4846bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4847 LLVMContext &Context = Ty->getContext();
4848 if (Ty->isVectorTy()) {
4849 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4850 Ty->getVectorNumElements() == 4) {
4851 return true;
4852 }
4853 }
4854
4855 return false;
4856}
4857
David Neto257c3892018-04-11 13:19:45 -04004858uint32_t SPIRVProducerPass::GetI32Zero() {
4859 if (0 == constant_i32_zero_id_) {
4860 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4861 "defined in the SPIR-V module");
4862 }
4863 return constant_i32_zero_id_;
4864}
4865
David Neto22f144c2017-06-12 14:26:21 -04004866void SPIRVProducerPass::HandleDeferredInstruction() {
4867 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4868 ValueMapType &VMap = getValueMap();
4869 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4870
4871 for (auto DeferredInst = DeferredInsts.rbegin();
4872 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4873 Value *Inst = std::get<0>(*DeferredInst);
4874 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4875 if (InsertPoint != SPIRVInstList.end()) {
4876 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4877 ++InsertPoint;
4878 }
4879 }
4880
4881 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4882 // Check whether basic block, which has this branch instruction, is loop
4883 // header or not. If it is loop header, generate OpLoopMerge and
4884 // OpBranchConditional.
4885 Function *Func = Br->getParent()->getParent();
4886 DominatorTree &DT =
4887 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4888 const LoopInfo &LI =
4889 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4890
4891 BasicBlock *BrBB = Br->getParent();
4892 if (LI.isLoopHeader(BrBB)) {
4893 Value *ContinueBB = nullptr;
4894 Value *MergeBB = nullptr;
4895
4896 Loop *L = LI.getLoopFor(BrBB);
4897 MergeBB = L->getExitBlock();
4898 if (!MergeBB) {
4899 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4900 // has regions with single entry/exit. As a result, loop should not
4901 // have multiple exits.
4902 llvm_unreachable("Loop has multiple exits???");
4903 }
4904
4905 if (L->isLoopLatch(BrBB)) {
4906 ContinueBB = BrBB;
4907 } else {
4908 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4909 // block.
4910 BasicBlock *Header = L->getHeader();
4911 BasicBlock *Latch = L->getLoopLatch();
4912 for (BasicBlock *BB : L->blocks()) {
4913 if (BB == Header) {
4914 continue;
4915 }
4916
4917 // Check whether block dominates block with back-edge.
4918 if (DT.dominates(BB, Latch)) {
4919 ContinueBB = BB;
4920 }
4921 }
4922
4923 if (!ContinueBB) {
4924 llvm_unreachable("Wrong continue block from loop");
4925 }
4926 }
4927
4928 //
4929 // Generate OpLoopMerge.
4930 //
4931 // Ops[0] = Merge Block ID
4932 // Ops[1] = Continue Target ID
4933 // Ops[2] = Selection Control
4934 SPIRVOperandList Ops;
4935
4936 // StructurizeCFG pass already manipulated CFG. Just use false block of
4937 // branch instruction as merge block.
4938 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004939 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004940 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4941 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004942
David Neto87846742018-04-11 17:36:22 -04004943 auto *MergeInst = new SPIRVInstruction(spv::OpLoopMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004944 SPIRVInstList.insert(InsertPoint, MergeInst);
4945
4946 } else if (Br->isConditional()) {
4947 bool HasBackEdge = false;
4948
4949 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4950 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4951 HasBackEdge = true;
4952 }
4953 }
4954 if (!HasBackEdge) {
4955 //
4956 // Generate OpSelectionMerge.
4957 //
4958 // Ops[0] = Merge Block ID
4959 // Ops[1] = Selection Control
4960 SPIRVOperandList Ops;
4961
4962 // StructurizeCFG pass already manipulated CFG. Just use false block
4963 // of branch instruction as merge block.
4964 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004965 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004966
David Neto87846742018-04-11 17:36:22 -04004967 auto *MergeInst = new SPIRVInstruction(spv::OpSelectionMerge, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004968 SPIRVInstList.insert(InsertPoint, MergeInst);
4969 }
4970 }
4971
4972 if (Br->isConditional()) {
4973 //
4974 // Generate OpBranchConditional.
4975 //
4976 // Ops[0] = Condition ID
4977 // Ops[1] = True Label ID
4978 // Ops[2] = False Label ID
4979 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4980 SPIRVOperandList Ops;
4981
4982 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004983 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004984 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004985
4986 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004987
David Neto87846742018-04-11 17:36:22 -04004988 auto *BrInst = new SPIRVInstruction(spv::OpBranchConditional, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004989 SPIRVInstList.insert(InsertPoint, BrInst);
4990 } else {
4991 //
4992 // Generate OpBranch.
4993 //
4994 // Ops[0] = Target Label ID
4995 SPIRVOperandList Ops;
4996
4997 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04004998 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04004999
David Neto87846742018-04-11 17:36:22 -04005000 SPIRVInstList.insert(InsertPoint,
5001 new SPIRVInstruction(spv::OpBranch, Ops));
David Neto22f144c2017-06-12 14:26:21 -04005002 }
5003 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5004 //
5005 // Generate OpPhi.
5006 //
5007 // Ops[0] = Result Type ID
5008 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5009 SPIRVOperandList Ops;
5010
David Neto257c3892018-04-11 13:19:45 -04005011 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005012
David Neto22f144c2017-06-12 14:26:21 -04005013 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5014 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005015 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005016 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005017 }
5018
5019 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005020 InsertPoint,
5021 new SPIRVInstruction(spv::OpPhi, std::get<2>(*DeferredInst), Ops));
David Neto22f144c2017-06-12 14:26:21 -04005022 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5023 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005024 auto callee_name = Callee->getName();
5025 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005026
5027 if (EInst) {
5028 uint32_t &ExtInstImportID = getOpExtInstImportID();
5029
5030 //
5031 // Generate OpExtInst.
5032 //
5033
5034 // Ops[0] = Result Type ID
5035 // Ops[1] = Set ID (OpExtInstImport ID)
5036 // Ops[2] = Instruction Number (Literal Number)
5037 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5038 SPIRVOperandList Ops;
5039
David Neto862b7d82018-06-14 18:48:37 -04005040 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID)
5041 << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005042
David Neto22f144c2017-06-12 14:26:21 -04005043 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5044 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005045 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005046 }
5047
David Neto87846742018-04-11 17:36:22 -04005048 auto *ExtInst = new SPIRVInstruction(spv::OpExtInst,
5049 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005050 SPIRVInstList.insert(InsertPoint, ExtInst);
5051
David Neto3fbb4072017-10-16 11:28:14 -04005052 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5053 if (IndirectExtInst != kGlslExtInstBad) {
5054 // Generate one more instruction that uses the result of the extended
5055 // instruction. Its result id is one more than the id of the
5056 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005057 LLVMContext &Context =
5058 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005059
David Neto3fbb4072017-10-16 11:28:14 -04005060 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5061 &VMap, &SPIRVInstList, &InsertPoint](
5062 spv::Op opcode, Constant *constant) {
5063 //
5064 // Generate instruction like:
5065 // result = opcode constant <extinst-result>
5066 //
5067 // Ops[0] = Result Type ID
5068 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5069 // Ops[2] = Operand 1 ;; the result of the extended instruction
5070 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005071
David Neto3fbb4072017-10-16 11:28:14 -04005072 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005073 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005074
5075 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5076 constant = ConstantVector::getSplat(
5077 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5078 }
David Neto257c3892018-04-11 13:19:45 -04005079 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005080
5081 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005082 InsertPoint, new SPIRVInstruction(
5083 opcode, std::get<2>(*DeferredInst) + 1, Ops));
David Neto3fbb4072017-10-16 11:28:14 -04005084 };
5085
5086 switch (IndirectExtInst) {
5087 case glsl::ExtInstFindUMsb: // Implementing clz
5088 generate_extra_inst(
5089 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5090 break;
5091 case glsl::ExtInstAcos: // Implementing acospi
5092 case glsl::ExtInstAsin: // Implementing asinpi
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005093 case glsl::ExtInstAtan: // Implementing atanpi
David Neto3fbb4072017-10-16 11:28:14 -04005094 case glsl::ExtInstAtan2: // Implementing atan2pi
5095 generate_extra_inst(
5096 spv::OpFMul,
5097 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5098 break;
5099
5100 default:
5101 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005102 }
David Neto22f144c2017-06-12 14:26:21 -04005103 }
David Neto3fbb4072017-10-16 11:28:14 -04005104
David Neto862b7d82018-06-14 18:48:37 -04005105 } else if (callee_name.equals("_Z8popcounti") ||
5106 callee_name.equals("_Z8popcountj") ||
5107 callee_name.equals("_Z8popcountDv2_i") ||
5108 callee_name.equals("_Z8popcountDv3_i") ||
5109 callee_name.equals("_Z8popcountDv4_i") ||
5110 callee_name.equals("_Z8popcountDv2_j") ||
5111 callee_name.equals("_Z8popcountDv3_j") ||
5112 callee_name.equals("_Z8popcountDv4_j")) {
David Neto22f144c2017-06-12 14:26:21 -04005113 //
5114 // Generate OpBitCount
5115 //
5116 // Ops[0] = Result Type ID
5117 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005118 SPIRVOperandList Ops;
5119 Ops << MkId(lookupType(Call->getType()))
5120 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005121
5122 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005123 InsertPoint, new SPIRVInstruction(spv::OpBitCount,
David Neto22f144c2017-06-12 14:26:21 -04005124 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005125
David Neto862b7d82018-06-14 18:48:37 -04005126 } else if (callee_name.startswith(kCompositeConstructFunctionPrefix)) {
David Netoab03f432017-11-03 17:00:44 -04005127
5128 // Generate an OpCompositeConstruct
5129 SPIRVOperandList Ops;
5130
5131 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005132 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005133
5134 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005135 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005136 }
5137
5138 SPIRVInstList.insert(
David Neto87846742018-04-11 17:36:22 -04005139 InsertPoint, new SPIRVInstruction(spv::OpCompositeConstruct,
5140 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005141
Alan Baker202c8c72018-08-13 13:47:44 -04005142 } else if (callee_name.startswith(clspv::ResourceAccessorFunction())) {
5143
5144 // We have already mapped the call's result value to an ID.
5145 // Don't generate any code now.
5146
5147 } else if (callee_name.startswith(clspv::WorkgroupAccessorFunction())) {
David Neto862b7d82018-06-14 18:48:37 -04005148
5149 // We have already mapped the call's result value to an ID.
5150 // Don't generate any code now.
5151
David Neto22f144c2017-06-12 14:26:21 -04005152 } else {
5153 //
5154 // Generate OpFunctionCall.
5155 //
5156
5157 // Ops[0] = Result Type ID
5158 // Ops[1] = Callee Function ID
5159 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5160 SPIRVOperandList Ops;
5161
David Neto862b7d82018-06-14 18:48:37 -04005162 Ops << MkId(lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005163
5164 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005165 if (CalleeID == 0) {
5166 errs() << "Can't translate function call. Missing builtin? "
David Neto862b7d82018-06-14 18:48:37 -04005167 << callee_name << " in: " << *Call << "\n";
David Neto43568eb2017-10-13 18:25:25 -04005168 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5169 // causes an infinite loop. Instead, go ahead and generate
5170 // the bad function call. A validator will catch the 0-Id.
5171 // llvm_unreachable("Can't translate function call");
5172 }
David Neto22f144c2017-06-12 14:26:21 -04005173
David Neto257c3892018-04-11 13:19:45 -04005174 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005175
David Neto22f144c2017-06-12 14:26:21 -04005176 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5177 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005178 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005179 }
5180
David Neto87846742018-04-11 17:36:22 -04005181 auto *CallInst = new SPIRVInstruction(spv::OpFunctionCall,
5182 std::get<2>(*DeferredInst), Ops);
David Neto22f144c2017-06-12 14:26:21 -04005183 SPIRVInstList.insert(InsertPoint, CallInst);
5184 }
5185 }
5186 }
5187}
5188
David Neto1a1a0582017-07-07 12:01:44 -04005189void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
Alan Baker202c8c72018-08-13 13:47:44 -04005190 if (getTypesNeedingArrayStride().empty() && LocalArgSpecIds.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005191 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005192 }
David Neto1a1a0582017-07-07 12:01:44 -04005193
5194 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005195
5196 // Find an iterator pointing just past the last decoration.
5197 bool seen_decorations = false;
5198 auto DecoInsertPoint =
5199 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5200 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5201 const bool is_decoration =
5202 Inst->getOpcode() == spv::OpDecorate ||
5203 Inst->getOpcode() == spv::OpMemberDecorate;
5204 if (is_decoration) {
5205 seen_decorations = true;
5206 return false;
5207 } else {
5208 return seen_decorations;
5209 }
5210 });
5211
David Netoc6f3ab22018-04-06 18:02:31 -04005212 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5213 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005214 for (auto *type : getTypesNeedingArrayStride()) {
5215 Type *elemTy = nullptr;
5216 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5217 elemTy = ptrTy->getElementType();
5218 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5219 elemTy = arrayTy->getArrayElementType();
5220 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5221 elemTy = seqTy->getSequentialElementType();
5222 } else {
5223 errs() << "Unhandled strided type " << *type << "\n";
5224 llvm_unreachable("Unhandled strided type");
5225 }
David Neto1a1a0582017-07-07 12:01:44 -04005226
5227 // Ops[0] = Target ID
5228 // Ops[1] = Decoration (ArrayStride)
5229 // Ops[2] = Stride number (Literal Number)
5230 SPIRVOperandList Ops;
5231
David Neto85082642018-03-24 06:55:20 -07005232 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Alan Bakerfcda9482018-10-02 17:09:59 -04005233 const uint32_t stride = static_cast<uint32_t>(GetTypeAllocSize(elemTy, DL));
David Neto257c3892018-04-11 13:19:45 -04005234
5235 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5236 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005237
David Neto87846742018-04-11 17:36:22 -04005238 auto *DecoInst = new SPIRVInstruction(spv::OpDecorate, Ops);
David Neto1a1a0582017-07-07 12:01:44 -04005239 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5240 }
David Netoc6f3ab22018-04-06 18:02:31 -04005241
5242 // Emit SpecId decorations targeting the array size value.
Alan Baker202c8c72018-08-13 13:47:44 -04005243 for (auto spec_id = clspv::FirstLocalSpecId(); spec_id < max_local_spec_id_;
5244 ++spec_id) {
5245 LocalArgInfo& arg_info = LocalSpecIdInfoMap[spec_id];
David Netoc6f3ab22018-04-06 18:02:31 -04005246 SPIRVOperandList Ops;
5247 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5248 << MkNum(arg_info.spec_id);
5249 SPIRVInstList.insert(DecoInsertPoint,
David Neto87846742018-04-11 17:36:22 -04005250 new SPIRVInstruction(spv::OpDecorate, Ops));
David Netoc6f3ab22018-04-06 18:02:31 -04005251 }
David Neto1a1a0582017-07-07 12:01:44 -04005252}
5253
David Neto22f144c2017-06-12 14:26:21 -04005254glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5255 return StringSwitch<glsl::ExtInst>(Name)
5256 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5257 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5258 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5259 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5260 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5261 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5262 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5263 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5264 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5265 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5266 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5267 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5268 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5269 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5270 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5271 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005272 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5273 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5274 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5275 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5276 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5277 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5278 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5279 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5280 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5281 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5282 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5283 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5284 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5285 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5286 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5287 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5288 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5289 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5290 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5291 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5292 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5293 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5294 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5295 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5296 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5297 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5298 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5299 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5300 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5301 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5302 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5303 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5304 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5305 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5306 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5307 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5308 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5309 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5310 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5311 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5312 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5313 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5314 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5315 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5316 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5317 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5318 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5319 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5320 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5321 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5322 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5323 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5324 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5325 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5326 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5327 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5328 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5329 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5330 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5331 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5332 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5333 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
kpet3458e942018-10-03 14:35:21 +01005334 .StartsWith("_Z3fma", glsl::ExtInst::ExtInstFma)
David Neto22f144c2017-06-12 14:26:21 -04005335 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5336 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5337 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5338 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5339 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5340 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5341 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5342 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5343 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5344 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5345 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5346 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5347 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5348 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5349 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5350 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5351 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005352 .StartsWith("_Z11fast_length", glsl::ExtInst::ExtInstLength)
David Neto22f144c2017-06-12 14:26:21 -04005353 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005354 .StartsWith("_Z13fast_distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005355 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
kpet6fd2a262018-10-03 14:48:01 +01005356 .StartsWith("_Z10smoothstep", glsl::ExtInst::ExtInstSmoothStep)
David Neto22f144c2017-06-12 14:26:21 -04005357 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5358 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
Kévin Petit7d09cec2018-09-22 15:43:38 +01005359 .StartsWith("_Z14fast_normalize", glsl::ExtInst::ExtInstNormalize)
David Neto22f144c2017-06-12 14:26:21 -04005360 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5361 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5362 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005363 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5364 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5365 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5366 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005367 .Default(kGlslExtInstBad);
5368}
5369
5370glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5371 // Check indirect cases.
5372 return StringSwitch<glsl::ExtInst>(Name)
5373 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5374 // Use exact match on float arg because these need a multiply
5375 // of a constant of the right floating point type.
5376 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5377 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5378 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5379 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5380 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5381 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5382 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5383 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
Kévin Petiteb9f90a2018-09-29 12:29:34 +01005384 .Case("_Z6atanpif", glsl::ExtInst::ExtInstAtan)
5385 .Case("_Z6atanpiDv2_f", glsl::ExtInst::ExtInstAtan)
5386 .Case("_Z6atanpiDv3_f", glsl::ExtInst::ExtInstAtan)
5387 .Case("_Z6atanpiDv4_f", glsl::ExtInst::ExtInstAtan)
David Neto3fbb4072017-10-16 11:28:14 -04005388 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5389 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5390 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5391 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5392 .Default(kGlslExtInstBad);
5393}
5394
5395glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5396 auto direct = getExtInstEnum(Name);
5397 if (direct != kGlslExtInstBad)
5398 return direct;
5399 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005400}
5401
5402void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5403 out << "%" << Inst->getResultID();
5404}
5405
5406void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5407 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5408 out << "\t" << spv::getOpName(Opcode);
5409}
5410
5411void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5412 SPIRVOperandType OpTy = Op->getType();
5413 switch (OpTy) {
5414 default: {
5415 llvm_unreachable("Unsupported SPIRV Operand Type???");
5416 break;
5417 }
5418 case SPIRVOperandType::NUMBERID: {
5419 out << "%" << Op->getNumID();
5420 break;
5421 }
5422 case SPIRVOperandType::LITERAL_STRING: {
5423 out << "\"" << Op->getLiteralStr() << "\"";
5424 break;
5425 }
5426 case SPIRVOperandType::LITERAL_INTEGER: {
5427 // TODO: Handle LiteralNum carefully.
5428 for (auto Word : Op->getLiteralNum()) {
5429 out << Word;
5430 }
5431 break;
5432 }
5433 case SPIRVOperandType::LITERAL_FLOAT: {
5434 // TODO: Handle LiteralNum carefully.
5435 for (auto Word : Op->getLiteralNum()) {
5436 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5437 SmallString<8> Str;
5438 APF.toString(Str, 6, 2);
5439 out << Str;
5440 }
5441 break;
5442 }
5443 }
5444}
5445
5446void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5447 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5448 out << spv::getCapabilityName(Cap);
5449}
5450
5451void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5452 auto LiteralNum = Op->getLiteralNum();
5453 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5454 out << glsl::getExtInstName(Ext);
5455}
5456
5457void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5458 spv::AddressingModel AddrModel =
5459 static_cast<spv::AddressingModel>(Op->getNumID());
5460 out << spv::getAddressingModelName(AddrModel);
5461}
5462
5463void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5464 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5465 out << spv::getMemoryModelName(MemModel);
5466}
5467
5468void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5469 spv::ExecutionModel ExecModel =
5470 static_cast<spv::ExecutionModel>(Op->getNumID());
5471 out << spv::getExecutionModelName(ExecModel);
5472}
5473
5474void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5475 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5476 out << spv::getExecutionModeName(ExecMode);
5477}
5478
5479void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5480 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5481 out << spv::getSourceLanguageName(SourceLang);
5482}
5483
5484void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5485 spv::FunctionControlMask FuncCtrl =
5486 static_cast<spv::FunctionControlMask>(Op->getNumID());
5487 out << spv::getFunctionControlName(FuncCtrl);
5488}
5489
5490void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5491 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5492 out << getStorageClassName(StClass);
5493}
5494
5495void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5496 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5497 out << getDecorationName(Deco);
5498}
5499
5500void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5501 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5502 out << getBuiltInName(BIn);
5503}
5504
5505void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5506 spv::SelectionControlMask BIn =
5507 static_cast<spv::SelectionControlMask>(Op->getNumID());
5508 out << getSelectionControlName(BIn);
5509}
5510
5511void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5512 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5513 out << getLoopControlName(BIn);
5514}
5515
5516void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5517 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5518 out << getDimName(DIM);
5519}
5520
5521void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5522 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5523 out << getImageFormatName(Format);
5524}
5525
5526void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5527 out << spv::getMemoryAccessName(
5528 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5529}
5530
5531void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5532 auto LiteralNum = Op->getLiteralNum();
5533 spv::ImageOperandsMask Type =
5534 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5535 out << getImageOperandsName(Type);
5536}
5537
5538void SPIRVProducerPass::WriteSPIRVAssembly() {
5539 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5540
5541 for (auto Inst : SPIRVInstList) {
5542 SPIRVOperandList Ops = Inst->getOperands();
5543 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5544
5545 switch (Opcode) {
5546 default: {
5547 llvm_unreachable("Unsupported SPIRV instruction");
5548 break;
5549 }
5550 case spv::OpCapability: {
5551 // Ops[0] = Capability
5552 PrintOpcode(Inst);
5553 out << " ";
5554 PrintCapability(Ops[0]);
5555 out << "\n";
5556 break;
5557 }
5558 case spv::OpMemoryModel: {
5559 // Ops[0] = Addressing Model
5560 // Ops[1] = Memory Model
5561 PrintOpcode(Inst);
5562 out << " ";
5563 PrintAddrModel(Ops[0]);
5564 out << " ";
5565 PrintMemModel(Ops[1]);
5566 out << "\n";
5567 break;
5568 }
5569 case spv::OpEntryPoint: {
5570 // Ops[0] = Execution Model
5571 // Ops[1] = EntryPoint ID
5572 // Ops[2] = Name (Literal String)
5573 // Ops[3] ... Ops[n] = Interface ID
5574 PrintOpcode(Inst);
5575 out << " ";
5576 PrintExecModel(Ops[0]);
5577 for (uint32_t i = 1; i < Ops.size(); i++) {
5578 out << " ";
5579 PrintOperand(Ops[i]);
5580 }
5581 out << "\n";
5582 break;
5583 }
5584 case spv::OpExecutionMode: {
5585 // Ops[0] = Entry Point ID
5586 // Ops[1] = Execution Mode
5587 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5588 PrintOpcode(Inst);
5589 out << " ";
5590 PrintOperand(Ops[0]);
5591 out << " ";
5592 PrintExecMode(Ops[1]);
5593 for (uint32_t i = 2; i < Ops.size(); i++) {
5594 out << " ";
5595 PrintOperand(Ops[i]);
5596 }
5597 out << "\n";
5598 break;
5599 }
5600 case spv::OpSource: {
5601 // Ops[0] = SourceLanguage ID
5602 // Ops[1] = Version (LiteralNum)
5603 PrintOpcode(Inst);
5604 out << " ";
5605 PrintSourceLanguage(Ops[0]);
5606 out << " ";
5607 PrintOperand(Ops[1]);
5608 out << "\n";
5609 break;
5610 }
5611 case spv::OpDecorate: {
5612 // Ops[0] = Target ID
5613 // Ops[1] = Decoration (Block or BufferBlock)
5614 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5615 PrintOpcode(Inst);
5616 out << " ";
5617 PrintOperand(Ops[0]);
5618 out << " ";
5619 PrintDecoration(Ops[1]);
5620 // Handle BuiltIn OpDecorate specially.
5621 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5622 out << " ";
5623 PrintBuiltIn(Ops[2]);
5624 } else {
5625 for (uint32_t i = 2; i < Ops.size(); i++) {
5626 out << " ";
5627 PrintOperand(Ops[i]);
5628 }
5629 }
5630 out << "\n";
5631 break;
5632 }
5633 case spv::OpMemberDecorate: {
5634 // Ops[0] = Structure Type ID
5635 // Ops[1] = Member Index(Literal Number)
5636 // Ops[2] = Decoration
5637 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5638 PrintOpcode(Inst);
5639 out << " ";
5640 PrintOperand(Ops[0]);
5641 out << " ";
5642 PrintOperand(Ops[1]);
5643 out << " ";
5644 PrintDecoration(Ops[2]);
5645 for (uint32_t i = 3; i < Ops.size(); i++) {
5646 out << " ";
5647 PrintOperand(Ops[i]);
5648 }
5649 out << "\n";
5650 break;
5651 }
5652 case spv::OpTypePointer: {
5653 // Ops[0] = Storage Class
5654 // Ops[1] = Element Type ID
5655 PrintResID(Inst);
5656 out << " = ";
5657 PrintOpcode(Inst);
5658 out << " ";
5659 PrintStorageClass(Ops[0]);
5660 out << " ";
5661 PrintOperand(Ops[1]);
5662 out << "\n";
5663 break;
5664 }
5665 case spv::OpTypeImage: {
5666 // Ops[0] = Sampled Type ID
5667 // Ops[1] = Dim ID
5668 // Ops[2] = Depth (Literal Number)
5669 // Ops[3] = Arrayed (Literal Number)
5670 // Ops[4] = MS (Literal Number)
5671 // Ops[5] = Sampled (Literal Number)
5672 // Ops[6] = Image Format ID
5673 PrintResID(Inst);
5674 out << " = ";
5675 PrintOpcode(Inst);
5676 out << " ";
5677 PrintOperand(Ops[0]);
5678 out << " ";
5679 PrintDimensionality(Ops[1]);
5680 out << " ";
5681 PrintOperand(Ops[2]);
5682 out << " ";
5683 PrintOperand(Ops[3]);
5684 out << " ";
5685 PrintOperand(Ops[4]);
5686 out << " ";
5687 PrintOperand(Ops[5]);
5688 out << " ";
5689 PrintImageFormat(Ops[6]);
5690 out << "\n";
5691 break;
5692 }
5693 case spv::OpFunction: {
5694 // Ops[0] : Result Type ID
5695 // Ops[1] : Function Control
5696 // Ops[2] : Function Type ID
5697 PrintResID(Inst);
5698 out << " = ";
5699 PrintOpcode(Inst);
5700 out << " ";
5701 PrintOperand(Ops[0]);
5702 out << " ";
5703 PrintFuncCtrl(Ops[1]);
5704 out << " ";
5705 PrintOperand(Ops[2]);
5706 out << "\n";
5707 break;
5708 }
5709 case spv::OpSelectionMerge: {
5710 // Ops[0] = Merge Block ID
5711 // Ops[1] = Selection Control
5712 PrintOpcode(Inst);
5713 out << " ";
5714 PrintOperand(Ops[0]);
5715 out << " ";
5716 PrintSelectionControl(Ops[1]);
5717 out << "\n";
5718 break;
5719 }
5720 case spv::OpLoopMerge: {
5721 // Ops[0] = Merge Block ID
5722 // Ops[1] = Continue Target ID
5723 // Ops[2] = Selection Control
5724 PrintOpcode(Inst);
5725 out << " ";
5726 PrintOperand(Ops[0]);
5727 out << " ";
5728 PrintOperand(Ops[1]);
5729 out << " ";
5730 PrintLoopControl(Ops[2]);
5731 out << "\n";
5732 break;
5733 }
5734 case spv::OpImageSampleExplicitLod: {
5735 // Ops[0] = Result Type ID
5736 // Ops[1] = Sampled Image ID
5737 // Ops[2] = Coordinate ID
5738 // Ops[3] = Image Operands Type ID
5739 // Ops[4] ... Ops[n] = Operands ID
5740 PrintResID(Inst);
5741 out << " = ";
5742 PrintOpcode(Inst);
5743 for (uint32_t i = 0; i < 3; i++) {
5744 out << " ";
5745 PrintOperand(Ops[i]);
5746 }
5747 out << " ";
5748 PrintImageOperandsType(Ops[3]);
5749 for (uint32_t i = 4; i < Ops.size(); i++) {
5750 out << " ";
5751 PrintOperand(Ops[i]);
5752 }
5753 out << "\n";
5754 break;
5755 }
5756 case spv::OpVariable: {
5757 // Ops[0] : Result Type ID
5758 // Ops[1] : Storage Class
5759 // Ops[2] ... Ops[n] = Initializer IDs
5760 PrintResID(Inst);
5761 out << " = ";
5762 PrintOpcode(Inst);
5763 out << " ";
5764 PrintOperand(Ops[0]);
5765 out << " ";
5766 PrintStorageClass(Ops[1]);
5767 for (uint32_t i = 2; i < Ops.size(); i++) {
5768 out << " ";
5769 PrintOperand(Ops[i]);
5770 }
5771 out << "\n";
5772 break;
5773 }
5774 case spv::OpExtInst: {
5775 // Ops[0] = Result Type ID
5776 // Ops[1] = Set ID (OpExtInstImport ID)
5777 // Ops[2] = Instruction Number (Literal Number)
5778 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5779 PrintResID(Inst);
5780 out << " = ";
5781 PrintOpcode(Inst);
5782 out << " ";
5783 PrintOperand(Ops[0]);
5784 out << " ";
5785 PrintOperand(Ops[1]);
5786 out << " ";
5787 PrintExtInst(Ops[2]);
5788 for (uint32_t i = 3; i < Ops.size(); i++) {
5789 out << " ";
5790 PrintOperand(Ops[i]);
5791 }
5792 out << "\n";
5793 break;
5794 }
5795 case spv::OpCopyMemory: {
5796 // Ops[0] = Addressing Model
5797 // Ops[1] = Memory Model
5798 PrintOpcode(Inst);
5799 out << " ";
5800 PrintOperand(Ops[0]);
5801 out << " ";
5802 PrintOperand(Ops[1]);
5803 out << " ";
5804 PrintMemoryAccess(Ops[2]);
5805 out << " ";
5806 PrintOperand(Ops[3]);
5807 out << "\n";
5808 break;
5809 }
5810 case spv::OpExtension:
5811 case spv::OpControlBarrier:
5812 case spv::OpMemoryBarrier:
5813 case spv::OpBranch:
5814 case spv::OpBranchConditional:
5815 case spv::OpStore:
5816 case spv::OpImageWrite:
5817 case spv::OpReturnValue:
5818 case spv::OpReturn:
5819 case spv::OpFunctionEnd: {
5820 PrintOpcode(Inst);
5821 for (uint32_t i = 0; i < Ops.size(); i++) {
5822 out << " ";
5823 PrintOperand(Ops[i]);
5824 }
5825 out << "\n";
5826 break;
5827 }
5828 case spv::OpExtInstImport:
5829 case spv::OpTypeRuntimeArray:
5830 case spv::OpTypeStruct:
5831 case spv::OpTypeSampler:
5832 case spv::OpTypeSampledImage:
5833 case spv::OpTypeInt:
5834 case spv::OpTypeFloat:
5835 case spv::OpTypeArray:
5836 case spv::OpTypeVector:
5837 case spv::OpTypeBool:
5838 case spv::OpTypeVoid:
5839 case spv::OpTypeFunction:
5840 case spv::OpFunctionParameter:
5841 case spv::OpLabel:
5842 case spv::OpPhi:
5843 case spv::OpLoad:
5844 case spv::OpSelect:
5845 case spv::OpAccessChain:
5846 case spv::OpPtrAccessChain:
5847 case spv::OpInBoundsAccessChain:
5848 case spv::OpUConvert:
5849 case spv::OpSConvert:
5850 case spv::OpConvertFToU:
5851 case spv::OpConvertFToS:
5852 case spv::OpConvertUToF:
5853 case spv::OpConvertSToF:
5854 case spv::OpFConvert:
5855 case spv::OpConvertPtrToU:
5856 case spv::OpConvertUToPtr:
5857 case spv::OpBitcast:
5858 case spv::OpIAdd:
5859 case spv::OpFAdd:
5860 case spv::OpISub:
5861 case spv::OpFSub:
5862 case spv::OpIMul:
5863 case spv::OpFMul:
5864 case spv::OpUDiv:
5865 case spv::OpSDiv:
5866 case spv::OpFDiv:
5867 case spv::OpUMod:
5868 case spv::OpSRem:
5869 case spv::OpFRem:
5870 case spv::OpBitwiseOr:
5871 case spv::OpBitwiseXor:
5872 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04005873 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04005874 case spv::OpShiftLeftLogical:
5875 case spv::OpShiftRightLogical:
5876 case spv::OpShiftRightArithmetic:
5877 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04005878 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04005879 case spv::OpCompositeExtract:
5880 case spv::OpVectorExtractDynamic:
5881 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04005882 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04005883 case spv::OpVectorInsertDynamic:
5884 case spv::OpVectorShuffle:
5885 case spv::OpIEqual:
5886 case spv::OpINotEqual:
5887 case spv::OpUGreaterThan:
5888 case spv::OpUGreaterThanEqual:
5889 case spv::OpULessThan:
5890 case spv::OpULessThanEqual:
5891 case spv::OpSGreaterThan:
5892 case spv::OpSGreaterThanEqual:
5893 case spv::OpSLessThan:
5894 case spv::OpSLessThanEqual:
5895 case spv::OpFOrdEqual:
5896 case spv::OpFOrdGreaterThan:
5897 case spv::OpFOrdGreaterThanEqual:
5898 case spv::OpFOrdLessThan:
5899 case spv::OpFOrdLessThanEqual:
5900 case spv::OpFOrdNotEqual:
5901 case spv::OpFUnordEqual:
5902 case spv::OpFUnordGreaterThan:
5903 case spv::OpFUnordGreaterThanEqual:
5904 case spv::OpFUnordLessThan:
5905 case spv::OpFUnordLessThanEqual:
5906 case spv::OpFUnordNotEqual:
5907 case spv::OpSampledImage:
5908 case spv::OpFunctionCall:
5909 case spv::OpConstantTrue:
5910 case spv::OpConstantFalse:
5911 case spv::OpConstant:
5912 case spv::OpSpecConstant:
5913 case spv::OpConstantComposite:
5914 case spv::OpSpecConstantComposite:
5915 case spv::OpConstantNull:
5916 case spv::OpLogicalOr:
5917 case spv::OpLogicalAnd:
5918 case spv::OpLogicalNot:
5919 case spv::OpLogicalNotEqual:
5920 case spv::OpUndef:
5921 case spv::OpIsInf:
5922 case spv::OpIsNan:
5923 case spv::OpAny:
5924 case spv::OpAll:
David Neto5c22a252018-03-15 16:07:41 -04005925 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04005926 case spv::OpAtomicIAdd:
5927 case spv::OpAtomicISub:
5928 case spv::OpAtomicExchange:
5929 case spv::OpAtomicIIncrement:
5930 case spv::OpAtomicIDecrement:
5931 case spv::OpAtomicCompareExchange:
5932 case spv::OpAtomicUMin:
5933 case spv::OpAtomicSMin:
5934 case spv::OpAtomicUMax:
5935 case spv::OpAtomicSMax:
5936 case spv::OpAtomicAnd:
5937 case spv::OpAtomicOr:
5938 case spv::OpAtomicXor:
5939 case spv::OpDot: {
5940 PrintResID(Inst);
5941 out << " = ";
5942 PrintOpcode(Inst);
5943 for (uint32_t i = 0; i < Ops.size(); i++) {
5944 out << " ";
5945 PrintOperand(Ops[i]);
5946 }
5947 out << "\n";
5948 break;
5949 }
5950 }
5951 }
5952}
5953
5954void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005955 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005956}
5957
5958void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5959 WriteOneWord(Inst->getResultID());
5960}
5961
5962void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5963 // High 16 bit : Word Count
5964 // Low 16 bit : Opcode
5965 uint32_t Word = Inst->getOpcode();
David Netoee2660d2018-06-28 16:31:29 -04005966 const uint32_t count = Inst->getWordCount();
5967 if (count > 65535) {
5968 errs() << "Word count limit of 65535 exceeded: " << count << "\n";
5969 llvm_unreachable("Word count too high");
5970 }
David Neto22f144c2017-06-12 14:26:21 -04005971 Word |= Inst->getWordCount() << 16;
5972 WriteOneWord(Word);
5973}
5974
5975void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5976 SPIRVOperandType OpTy = Op->getType();
5977 switch (OpTy) {
5978 default: {
5979 llvm_unreachable("Unsupported SPIRV Operand Type???");
5980 break;
5981 }
5982 case SPIRVOperandType::NUMBERID: {
5983 WriteOneWord(Op->getNumID());
5984 break;
5985 }
5986 case SPIRVOperandType::LITERAL_STRING: {
5987 std::string Str = Op->getLiteralStr();
5988 const char *Data = Str.c_str();
5989 size_t WordSize = Str.size() / 4;
5990 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5991 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5992 }
5993
5994 uint32_t Remainder = Str.size() % 4;
5995 uint32_t LastWord = 0;
5996 if (Remainder) {
5997 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5998 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5999 }
6000 }
6001
6002 WriteOneWord(LastWord);
6003 break;
6004 }
6005 case SPIRVOperandType::LITERAL_INTEGER:
6006 case SPIRVOperandType::LITERAL_FLOAT: {
6007 auto LiteralNum = Op->getLiteralNum();
6008 // TODO: Handle LiteranNum carefully.
6009 for (auto Word : LiteralNum) {
6010 WriteOneWord(Word);
6011 }
6012 break;
6013 }
6014 }
6015}
6016
6017void SPIRVProducerPass::WriteSPIRVBinary() {
6018 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6019
6020 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006021 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006022 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6023
6024 switch (Opcode) {
6025 default: {
David Neto5c22a252018-03-15 16:07:41 -04006026 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006027 llvm_unreachable("Unsupported SPIRV instruction");
6028 break;
6029 }
6030 case spv::OpCapability:
6031 case spv::OpExtension:
6032 case spv::OpMemoryModel:
6033 case spv::OpEntryPoint:
6034 case spv::OpExecutionMode:
6035 case spv::OpSource:
6036 case spv::OpDecorate:
6037 case spv::OpMemberDecorate:
6038 case spv::OpBranch:
6039 case spv::OpBranchConditional:
6040 case spv::OpSelectionMerge:
6041 case spv::OpLoopMerge:
6042 case spv::OpStore:
6043 case spv::OpImageWrite:
6044 case spv::OpReturnValue:
6045 case spv::OpControlBarrier:
6046 case spv::OpMemoryBarrier:
6047 case spv::OpReturn:
6048 case spv::OpFunctionEnd:
6049 case spv::OpCopyMemory: {
6050 WriteWordCountAndOpcode(Inst);
6051 for (uint32_t i = 0; i < Ops.size(); i++) {
6052 WriteOperand(Ops[i]);
6053 }
6054 break;
6055 }
6056 case spv::OpTypeBool:
6057 case spv::OpTypeVoid:
6058 case spv::OpTypeSampler:
6059 case spv::OpLabel:
6060 case spv::OpExtInstImport:
6061 case spv::OpTypePointer:
6062 case spv::OpTypeRuntimeArray:
6063 case spv::OpTypeStruct:
6064 case spv::OpTypeImage:
6065 case spv::OpTypeSampledImage:
6066 case spv::OpTypeInt:
6067 case spv::OpTypeFloat:
6068 case spv::OpTypeArray:
6069 case spv::OpTypeVector:
6070 case spv::OpTypeFunction: {
6071 WriteWordCountAndOpcode(Inst);
6072 WriteResultID(Inst);
6073 for (uint32_t i = 0; i < Ops.size(); i++) {
6074 WriteOperand(Ops[i]);
6075 }
6076 break;
6077 }
6078 case spv::OpFunction:
6079 case spv::OpFunctionParameter:
6080 case spv::OpAccessChain:
6081 case spv::OpPtrAccessChain:
6082 case spv::OpInBoundsAccessChain:
6083 case spv::OpUConvert:
6084 case spv::OpSConvert:
6085 case spv::OpConvertFToU:
6086 case spv::OpConvertFToS:
6087 case spv::OpConvertUToF:
6088 case spv::OpConvertSToF:
6089 case spv::OpFConvert:
6090 case spv::OpConvertPtrToU:
6091 case spv::OpConvertUToPtr:
6092 case spv::OpBitcast:
6093 case spv::OpIAdd:
6094 case spv::OpFAdd:
6095 case spv::OpISub:
6096 case spv::OpFSub:
6097 case spv::OpIMul:
6098 case spv::OpFMul:
6099 case spv::OpUDiv:
6100 case spv::OpSDiv:
6101 case spv::OpFDiv:
6102 case spv::OpUMod:
6103 case spv::OpSRem:
6104 case spv::OpFRem:
6105 case spv::OpBitwiseOr:
6106 case spv::OpBitwiseXor:
6107 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006108 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006109 case spv::OpShiftLeftLogical:
6110 case spv::OpShiftRightLogical:
6111 case spv::OpShiftRightArithmetic:
6112 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006113 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006114 case spv::OpCompositeExtract:
6115 case spv::OpVectorExtractDynamic:
6116 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006117 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006118 case spv::OpVectorInsertDynamic:
6119 case spv::OpVectorShuffle:
6120 case spv::OpIEqual:
6121 case spv::OpINotEqual:
6122 case spv::OpUGreaterThan:
6123 case spv::OpUGreaterThanEqual:
6124 case spv::OpULessThan:
6125 case spv::OpULessThanEqual:
6126 case spv::OpSGreaterThan:
6127 case spv::OpSGreaterThanEqual:
6128 case spv::OpSLessThan:
6129 case spv::OpSLessThanEqual:
6130 case spv::OpFOrdEqual:
6131 case spv::OpFOrdGreaterThan:
6132 case spv::OpFOrdGreaterThanEqual:
6133 case spv::OpFOrdLessThan:
6134 case spv::OpFOrdLessThanEqual:
6135 case spv::OpFOrdNotEqual:
6136 case spv::OpFUnordEqual:
6137 case spv::OpFUnordGreaterThan:
6138 case spv::OpFUnordGreaterThanEqual:
6139 case spv::OpFUnordLessThan:
6140 case spv::OpFUnordLessThanEqual:
6141 case spv::OpFUnordNotEqual:
6142 case spv::OpExtInst:
6143 case spv::OpIsInf:
6144 case spv::OpIsNan:
6145 case spv::OpAny:
6146 case spv::OpAll:
6147 case spv::OpUndef:
6148 case spv::OpConstantNull:
6149 case spv::OpLogicalOr:
6150 case spv::OpLogicalAnd:
6151 case spv::OpLogicalNot:
6152 case spv::OpLogicalNotEqual:
6153 case spv::OpConstantComposite:
6154 case spv::OpSpecConstantComposite:
6155 case spv::OpConstantTrue:
6156 case spv::OpConstantFalse:
6157 case spv::OpConstant:
6158 case spv::OpSpecConstant:
6159 case spv::OpVariable:
6160 case spv::OpFunctionCall:
6161 case spv::OpSampledImage:
6162 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006163 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006164 case spv::OpSelect:
6165 case spv::OpPhi:
6166 case spv::OpLoad:
6167 case spv::OpAtomicIAdd:
6168 case spv::OpAtomicISub:
6169 case spv::OpAtomicExchange:
6170 case spv::OpAtomicIIncrement:
6171 case spv::OpAtomicIDecrement:
6172 case spv::OpAtomicCompareExchange:
6173 case spv::OpAtomicUMin:
6174 case spv::OpAtomicSMin:
6175 case spv::OpAtomicUMax:
6176 case spv::OpAtomicSMax:
6177 case spv::OpAtomicAnd:
6178 case spv::OpAtomicOr:
6179 case spv::OpAtomicXor:
6180 case spv::OpDot: {
6181 WriteWordCountAndOpcode(Inst);
6182 WriteOperand(Ops[0]);
6183 WriteResultID(Inst);
6184 for (uint32_t i = 1; i < Ops.size(); i++) {
6185 WriteOperand(Ops[i]);
6186 }
6187 break;
6188 }
6189 }
6190 }
6191}
Alan Baker9bf93fb2018-08-28 16:59:26 -04006192
6193bool SPIRVProducerPass::IsTypeNullable(const Type* type) const {
6194 switch (type->getTypeID()) {
6195 case Type::HalfTyID:
6196 case Type::FloatTyID:
6197 case Type::DoubleTyID:
6198 case Type::IntegerTyID:
6199 case Type::VectorTyID:
6200 return true;
6201 case Type::PointerTyID: {
6202 const PointerType *pointer_type = cast<PointerType>(type);
6203 if (pointer_type->getPointerAddressSpace() !=
6204 AddressSpace::UniformConstant) {
6205 auto pointee_type = pointer_type->getPointerElementType();
6206 if (pointee_type->isStructTy() &&
6207 cast<StructType>(pointee_type)->isOpaque()) {
6208 // Images and samplers are not nullable.
6209 return false;
6210 }
6211 }
6212 return true;
6213 }
6214 case Type::ArrayTyID:
6215 return IsTypeNullable(cast<CompositeType>(type)->getTypeAtIndex(0u));
6216 case Type::StructTyID: {
6217 const StructType* struct_type = cast<StructType>(type);
6218 // Images and samplers are not nullable.
6219 if (struct_type->isOpaque()) return false;
6220 for (const auto element : struct_type->elements()) {
6221 if (!IsTypeNullable(element)) return false;
6222 }
6223 return true;
6224 }
6225 default:
6226 return false;
6227 }
6228}
Alan Bakerfcda9482018-10-02 17:09:59 -04006229
6230void SPIRVProducerPass::PopulateUBOTypeMaps(Module &module) {
6231 if (auto *offsets_md =
6232 module.getNamedMetadata(clspv::RemappedTypeOffsetMetadataName())) {
6233 // Metdata is stored as key-value pair operands. The first element of each
6234 // operand is the type and the second is a vector of offsets.
6235 for (const auto *operand : offsets_md->operands()) {
6236 const auto *pair = cast<MDTuple>(operand);
6237 auto *type =
6238 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6239 const auto *offset_vector = cast<MDTuple>(pair->getOperand(1));
6240 std::vector<uint32_t> offsets;
6241 for (const Metadata *offset_md : offset_vector->operands()) {
6242 const auto *constant_md = cast<ConstantAsMetadata>(offset_md);
6243 offsets.push_back(
6244 cast<ConstantInt>(constant_md->getValue())->getZExtValue());
6245 }
6246 RemappedUBOTypeOffsets.insert(std::make_pair(type, offsets));
6247 }
6248 }
6249
6250 if (auto *sizes_md =
6251 module.getNamedMetadata(clspv::RemappedTypeSizesMetadataName())) {
6252 // Metadata is stored as key-value pair operands. The first element of each
6253 // operand is the type and the second is a triple of sizes: type size in
6254 // bits, store size and alloc size.
6255 for (const auto *operand : sizes_md->operands()) {
6256 const auto *pair = cast<MDTuple>(operand);
6257 auto *type =
6258 cast<ConstantAsMetadata>(pair->getOperand(0))->getValue()->getType();
6259 const auto *size_triple = cast<MDTuple>(pair->getOperand(1));
6260 uint64_t type_size_in_bits =
6261 cast<ConstantInt>(
6262 cast<ConstantAsMetadata>(size_triple->getOperand(0))->getValue())
6263 ->getZExtValue();
6264 uint64_t type_store_size =
6265 cast<ConstantInt>(
6266 cast<ConstantAsMetadata>(size_triple->getOperand(1))->getValue())
6267 ->getZExtValue();
6268 uint64_t type_alloc_size =
6269 cast<ConstantInt>(
6270 cast<ConstantAsMetadata>(size_triple->getOperand(2))->getValue())
6271 ->getZExtValue();
6272 RemappedUBOTypeSizes.insert(std::make_pair(
6273 type, std::make_tuple(type_size_in_bits, type_store_size,
6274 type_alloc_size)));
6275 }
6276 }
6277}
6278
6279uint64_t SPIRVProducerPass::GetTypeSizeInBits(Type *type,
6280 const DataLayout &DL) {
6281 auto iter = RemappedUBOTypeSizes.find(type);
6282 if (iter != RemappedUBOTypeSizes.end()) {
6283 return std::get<0>(iter->second);
6284 }
6285
6286 return DL.getTypeSizeInBits(type);
6287}
6288
6289uint64_t SPIRVProducerPass::GetTypeStoreSize(Type *type, const DataLayout &DL) {
6290 auto iter = RemappedUBOTypeSizes.find(type);
6291 if (iter != RemappedUBOTypeSizes.end()) {
6292 return std::get<1>(iter->second);
6293 }
6294
6295 return DL.getTypeStoreSize(type);
6296}
6297
6298uint64_t SPIRVProducerPass::GetTypeAllocSize(Type *type, const DataLayout &DL) {
6299 auto iter = RemappedUBOTypeSizes.find(type);
6300 if (iter != RemappedUBOTypeSizes.end()) {
6301 return std::get<2>(iter->second);
6302 }
6303
6304 return DL.getTypeAllocSize(type);
6305}