blob: bf7db0620b60ede3a6cf1c6b015098c7e8edf090 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifdef _MSC_VER
16#pragma warning(push, 0)
17#endif
18
David Neto156783e2017-07-05 15:39:41 -040019#include <cassert>
David Neto257c3892018-04-11 13:19:45 -040020#include <cstring>
21
David Neto5c22a252018-03-15 16:07:41 -040022#include <unordered_set>
David Neto482550a2018-03-24 05:21:07 -070023#include <clspv/Option.h>
David Neto22f144c2017-06-12 14:26:21 -040024#include <clspv/Passes.h>
25
26#include <llvm/ADT/StringSwitch.h>
27#include <llvm/ADT/UniqueVector.h>
28#include <llvm/Analysis/LoopInfo.h>
29#include <llvm/IR/Constants.h>
30#include <llvm/IR/Dominators.h>
31#include <llvm/IR/Instructions.h>
32#include <llvm/IR/Metadata.h>
33#include <llvm/IR/Module.h>
34#include <llvm/Pass.h>
David Netocd8ca5f2017-10-02 23:34:11 -040035#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040036#include <llvm/Support/raw_ostream.h>
37#include <llvm/Transforms/Utils/Cloning.h>
38
David Neto85082642018-03-24 06:55:20 -070039#include "spirv/1.0/spirv.hpp"
40#include "clspv/AddressSpace.h"
41#include "clspv/spirv_c_strings.hpp"
42#include "clspv/spirv_glsl.hpp"
David Neto22f144c2017-06-12 14:26:21 -040043
David Neto4feb7a42017-10-06 17:29:42 -040044#include "ArgKind.h"
David Neto85082642018-03-24 06:55:20 -070045#include "ConstantEmitter.h"
David Neto48f56a42017-10-06 16:44:25 -040046
David Neto22f144c2017-06-12 14:26:21 -040047#include <list>
David Neto0676e6f2017-07-11 18:47:44 -040048#include <iomanip>
David Neto26aaf622017-10-23 18:11:53 -040049#include <set>
David Neto0676e6f2017-07-11 18:47:44 -040050#include <sstream>
David Neto257c3892018-04-11 13:19:45 -040051#include <string>
David Neto26aaf622017-10-23 18:11:53 -040052#include <tuple>
David Neto44795152017-07-13 15:45:28 -040053#include <utility>
David Neto22f144c2017-06-12 14:26:21 -040054
55#if defined(_MSC_VER)
56#pragma warning(pop)
57#endif
58
59using namespace llvm;
60using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040061using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040062
63namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040064
David Neto3fbb4072017-10-16 11:28:14 -040065// The value of 1/pi. This value is from MSDN
66// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
67const double kOneOverPi = 0.318309886183790671538;
68const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
69
David Netoab03f432017-11-03 17:00:44 -040070const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
71
David Neto22f144c2017-06-12 14:26:21 -040072enum SPIRVOperandType {
73 NUMBERID,
74 LITERAL_INTEGER,
75 LITERAL_STRING,
76 LITERAL_FLOAT
77};
78
79struct SPIRVOperand {
80 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
81 : Type(Ty), LiteralNum(1, Num) {}
82 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
83 : Type(Ty), LiteralStr(Str) {}
84 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
85 : Type(Ty), LiteralStr(Str) {}
86 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
87 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
88
89 SPIRVOperandType getType() { return Type; };
90 uint32_t getNumID() { return LiteralNum[0]; };
91 std::string getLiteralStr() { return LiteralStr; };
92 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
93
94private:
95 SPIRVOperandType Type;
96 std::string LiteralStr;
97 SmallVector<uint32_t, 4> LiteralNum;
98};
99
David Netoc6f3ab22018-04-06 18:02:31 -0400100class SPIRVOperandList {
101public:
102 SPIRVOperandList() {}
103 SPIRVOperandList(const SPIRVOperandList& other) = delete;
104 SPIRVOperandList(SPIRVOperandList&& other) {
105 contents_ = std::move(other.contents_);
106 other.contents_.clear();
107 }
108 SPIRVOperandList(ArrayRef<SPIRVOperand *> init)
109 : contents_(init.begin(), init.end()) {}
110 operator ArrayRef<SPIRVOperand *>() { return contents_; }
111 void push_back(SPIRVOperand *op) { contents_.push_back(op); }
112 void clear() { contents_.clear();}
113 size_t size() const { return contents_.size(); }
114 SPIRVOperand *&operator[](size_t i) { return contents_[i]; }
115
116private:
117 SmallVector<SPIRVOperand *,8> contents_;
118};
119
120SPIRVOperandList &operator<<(SPIRVOperandList &list, SPIRVOperand *elem) {
121 list.push_back(elem);
122 return list;
123}
124
125SPIRVOperand* MkNum(uint32_t num) {
126 return new SPIRVOperand(LITERAL_INTEGER, num);
127}
David Neto257c3892018-04-11 13:19:45 -0400128SPIRVOperand* MkInteger(ArrayRef<uint32_t> num_vec) {
129 return new SPIRVOperand(LITERAL_INTEGER, num_vec);
130}
131SPIRVOperand* MkFloat(ArrayRef<uint32_t> num_vec) {
132 return new SPIRVOperand(LITERAL_FLOAT, num_vec);
133}
David Netoc6f3ab22018-04-06 18:02:31 -0400134SPIRVOperand* MkId(uint32_t id) {
135 return new SPIRVOperand(NUMBERID, id);
136}
David Neto257c3892018-04-11 13:19:45 -0400137SPIRVOperand* MkString(StringRef str) {
138 return new SPIRVOperand(LITERAL_STRING, str);
139}
David Netoc6f3ab22018-04-06 18:02:31 -0400140
David Neto22f144c2017-06-12 14:26:21 -0400141struct SPIRVInstruction {
142 explicit SPIRVInstruction(uint16_t WCount, spv::Op Opc, uint32_t ResID,
143 ArrayRef<SPIRVOperand *> Ops)
144 : WordCount(WCount), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
145 Operands(Ops.begin(), Ops.end()) {}
146
147 uint16_t getWordCount() const { return WordCount; }
148 uint16_t getOpcode() const { return Opcode; }
149 uint32_t getResultID() const { return ResultID; }
150 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
151
152private:
153 uint16_t WordCount;
154 uint16_t Opcode;
155 uint32_t ResultID;
156 SmallVector<SPIRVOperand *, 4> Operands;
157};
158
159struct SPIRVProducerPass final : public ModulePass {
David Neto22f144c2017-06-12 14:26:21 -0400160 typedef DenseMap<Type *, uint32_t> TypeMapType;
161 typedef UniqueVector<Type *> TypeList;
162 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400163 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400164 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
165 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
166 typedef std::vector<
167 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
168 DeferredInstVecType;
169 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
170 GlobalConstFuncMapType;
171
David Neto44795152017-07-13 15:45:28 -0400172 explicit SPIRVProducerPass(
173 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
174 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
175 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400176 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400177 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400178 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400179 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400180 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
David Neto85082642018-03-24 06:55:20 -0700181 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0),
David Neto257c3892018-04-11 13:19:45 -0400182 NextDescriptorSetIndex(0), constant_i32_zero_id_(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400183
184 void getAnalysisUsage(AnalysisUsage &AU) const override {
185 AU.addRequired<DominatorTreeWrapperPass>();
186 AU.addRequired<LoopInfoWrapperPass>();
187 }
188
189 virtual bool runOnModule(Module &module) override;
190
191 // output the SPIR-V header block
192 void outputHeader();
193
194 // patch the SPIR-V header block
195 void patchHeader();
196
197 uint32_t lookupType(Type *Ty) {
198 if (Ty->isPointerTy() &&
199 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
200 auto PointeeTy = Ty->getPointerElementType();
201 if (PointeeTy->isStructTy() &&
202 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
203 Ty = PointeeTy;
204 }
205 }
206
207 if (0 == TypeMap.count(Ty)) {
208 Ty->print(errs());
David Netoe439d702018-03-23 13:14:08 -0700209 llvm_unreachable("\nUnhandled type!");
David Neto22f144c2017-06-12 14:26:21 -0400210 }
211
212 return TypeMap[Ty];
213 }
214 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
215 TypeList &getTypeList() { return Types; };
216 ValueList &getConstantList() { return Constants; };
217 ValueMapType &getValueMap() { return ValueMap; }
218 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
219 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
220 ValueToValueMapTy &getArgumentGVMap() { return ArgumentGVMap; };
221 ValueMapType &getArgumentGVIDMap() { return ArgumentGVIDMap; };
222 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
223 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
224 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
225 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
226 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
227 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
228 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400229 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400230 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
231 return GlobalConstFuncTypeMap;
232 }
233 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
234 return GlobalConstArgumentSet;
235 }
David Neto85082642018-03-24 06:55:20 -0700236 TypeList &getTypesNeedingArrayStride() {
237 return TypesNeedingArrayStride;
David Neto1a1a0582017-07-07 12:01:44 -0400238 }
David Neto22f144c2017-06-12 14:26:21 -0400239
David Netoc6f3ab22018-04-06 18:02:31 -0400240 void GenerateLLVMIRInfo(Module &M, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400241 bool FindExtInst(Module &M);
242 void FindTypePerGlobalVar(GlobalVariable &GV);
243 void FindTypePerFunc(Function &F);
David Neto19a1bad2017-08-25 15:01:41 -0400244 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
245 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400246 void FindType(Type *Ty);
247 void FindConstantPerGlobalVar(GlobalVariable &GV);
248 void FindConstantPerFunc(Function &F);
249 void FindConstant(Value *V);
250 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400251 // Generates instructions for SPIR-V types corresponding to the LLVM types
252 // saved in the |Types| member. A type follows its subtypes. IDs are
253 // allocated sequentially starting with the current value of nextID, and
254 // with a type following its subtypes. Also updates nextID to just beyond
255 // the last generated ID.
David Netoc6f3ab22018-04-06 18:02:31 -0400256 void GenerateSPIRVTypes(LLVMContext& context, const DataLayout &DL);
David Neto22f144c2017-06-12 14:26:21 -0400257 void GenerateSPIRVConstants();
David Neto5c22a252018-03-15 16:07:41 -0400258 void GenerateModuleInfo(Module &M);
David Neto22f144c2017-06-12 14:26:21 -0400259 void GenerateGlobalVar(GlobalVariable &GV);
David Netoc6f3ab22018-04-06 18:02:31 -0400260 void GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400261 void GenerateSamplers(Module &M);
262 void GenerateFuncPrologue(Function &F);
263 void GenerateFuncBody(Function &F);
264 void GenerateInstForArg(Function &F);
265 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
266 spv::Op GetSPIRVCastOpcode(Instruction &I);
267 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
268 void GenerateInstruction(Instruction &I);
269 void GenerateFuncEpilogue();
270 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400271 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400272 bool is4xi8vec(Type *Ty) const;
David Neto257c3892018-04-11 13:19:45 -0400273 // Return the SPIR-V Id for 32-bit constant zero. The constant must already
274 // have been created.
275 uint32_t GetI32Zero();
David Neto22f144c2017-06-12 14:26:21 -0400276 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
277 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400278 // Returns the GLSL extended instruction enum that the given function
279 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400280 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400281 // Returns the GLSL extended instruction enum indirectly used by the given
282 // function. That is, to implement the given function, we use an extended
283 // instruction plus one more instruction. If none, then returns the 0 value,
284 // i.e. GLSLstd4580Bad.
285 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
286 // Returns the single GLSL extended instruction used directly or
287 // indirectly by the given function call.
288 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400289 void PrintResID(SPIRVInstruction *Inst);
290 void PrintOpcode(SPIRVInstruction *Inst);
291 void PrintOperand(SPIRVOperand *Op);
292 void PrintCapability(SPIRVOperand *Op);
293 void PrintExtInst(SPIRVOperand *Op);
294 void PrintAddrModel(SPIRVOperand *Op);
295 void PrintMemModel(SPIRVOperand *Op);
296 void PrintExecModel(SPIRVOperand *Op);
297 void PrintExecMode(SPIRVOperand *Op);
298 void PrintSourceLanguage(SPIRVOperand *Op);
299 void PrintFuncCtrl(SPIRVOperand *Op);
300 void PrintStorageClass(SPIRVOperand *Op);
301 void PrintDecoration(SPIRVOperand *Op);
302 void PrintBuiltIn(SPIRVOperand *Op);
303 void PrintSelectionControl(SPIRVOperand *Op);
304 void PrintLoopControl(SPIRVOperand *Op);
305 void PrintDimensionality(SPIRVOperand *Op);
306 void PrintImageFormat(SPIRVOperand *Op);
307 void PrintMemoryAccess(SPIRVOperand *Op);
308 void PrintImageOperandsType(SPIRVOperand *Op);
309 void WriteSPIRVAssembly();
310 void WriteOneWord(uint32_t Word);
311 void WriteResultID(SPIRVInstruction *Inst);
312 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
313 void WriteOperand(SPIRVOperand *Op);
314 void WriteSPIRVBinary();
315
316private:
317 static char ID;
David Neto44795152017-07-13 15:45:28 -0400318 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400319 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400320
321 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
322 // convert to other formats on demand?
323
324 // When emitting a C initialization list, the WriteSPIRVBinary method
325 // will actually write its words to this vector via binaryTempOut.
326 SmallVector<char, 100> binaryTempUnderlyingVector;
327 raw_svector_ostream binaryTempOut;
328
329 // Binary output writes to this stream, which might be |out| or
330 // |binaryTempOut|. It's the latter when we really want to write a C
331 // initializer list.
332 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400333 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400334 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400335 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400336 uint64_t patchBoundOffset;
337 uint32_t nextID;
338
David Neto19a1bad2017-08-25 15:01:41 -0400339 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400340 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400341 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400342 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400343 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400344 TypeList Types;
345 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400346 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400347 ValueMapType ValueMap;
348 ValueMapType AllocatedValueMap;
349 SPIRVInstructionList SPIRVInsts;
David Netoe439d702018-03-23 13:14:08 -0700350 // Maps a kernel argument value to a global value. OpenCL kernel arguments
351 // have to map to resources: buffers, samplers, images, or sampled images.
David Neto22f144c2017-06-12 14:26:21 -0400352 ValueToValueMapTy ArgumentGVMap;
353 ValueMapType ArgumentGVIDMap;
354 EntryPointVecType EntryPointVec;
355 DeferredInstVecType DeferredInstVec;
356 ValueList EntryPointInterfacesVec;
357 uint32_t OpExtInstImportID;
358 std::vector<uint32_t> BuiltinDimensionVec;
359 bool HasVariablePointers;
360 Type *SamplerTy;
David Netoc77d9e22018-03-24 06:30:28 -0700361
362 // If a function F has a pointer-to-__constant parameter, then this variable
David Neto9ed8e2f2018-03-24 06:47:24 -0700363 // will map F's type to (G, index of the parameter), where in a first phase
364 // G is F's type. During FindTypePerFunc, G will be changed to F's type
365 // but replacing the pointer-to-constant parameter with
366 // pointer-to-ModuleScopePrivate.
David Netoc77d9e22018-03-24 06:30:28 -0700367 // TODO(dneto): This doesn't seem general enough? A function might have
368 // more than one such parameter.
David Neto22f144c2017-06-12 14:26:21 -0400369 GlobalConstFuncMapType GlobalConstFuncTypeMap;
370 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400371 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
David Neto85082642018-03-24 06:55:20 -0700372 // or array types, and which point into transparent memory (StorageBuffer
373 // storage class). These will require an ArrayStride decoration.
David Neto1a1a0582017-07-07 12:01:44 -0400374 // See SPV_KHR_variable_pointers rev 13.
David Neto85082642018-03-24 06:55:20 -0700375 TypeList TypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400376
377 // This is truly ugly, but works around what look like driver bugs.
378 // For get_local_size, an earlier part of the flow has created a module-scope
379 // variable in Private address space to hold the value for the workgroup
380 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
381 // When this is present, save the IDs of the initializer value and variable
382 // in these two variables. We only ever do a vector load from it, and
383 // when we see one of those, substitute just the value of the intializer.
384 // This mimics what Glslang does, and that's what drivers are used to.
David Neto66cfe642018-03-24 06:13:56 -0700385 // TODO(dneto): Remove this once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -0400386 uint32_t WorkgroupSizeValueID;
387 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400388
389 // What module-scope variables already have had their binding information
390 // emitted?
391 DenseSet<Value*> GVarWithEmittedBindingInfo;
David Neto85082642018-03-24 06:55:20 -0700392
David Netoc6f3ab22018-04-06 18:02:31 -0400393 // An ordered list of the kernel arguments of type pointer-to-local.
394 using LocalArgList = SmallVector<const Argument*, 8>;
395 LocalArgList LocalArgs;
396 // Information about a pointer-to-local argument.
397 struct LocalArgInfo {
398 // The SPIR-V ID of the array variable.
399 uint32_t variable_id;
400 // The element type of the
401 Type* elem_type;
402 // The ID of the array type.
403 uint32_t array_size_id;
404 // The ID of the array type.
405 uint32_t array_type_id;
406 // The ID of the pointer to the array type.
407 uint32_t ptr_array_type_id;
408 // The ID of the pointer to the first element of the array.
409 uint32_t first_elem_ptr_id;
410 // The specialization constant ID of the array size.
411 int spec_id;
412 };
413 // A mapping from a pointer-to-local argument value to a LocalArgInfo value.
414 DenseMap<const Argument*, LocalArgInfo> LocalArgMap;
415
David Neto85082642018-03-24 06:55:20 -0700416 // The next descriptor set index to use.
417 uint32_t NextDescriptorSetIndex;
David Netoc6f3ab22018-04-06 18:02:31 -0400418
419 // A mapping from pointer-to-local argument to a specialization constant ID
420 // for that argument's array size. This is generated from AllocatArgSpecIds.
421 ArgIdMapType ArgSpecIdMap;
David Neto257c3892018-04-11 13:19:45 -0400422
423 // The ID of 32-bit integer zero constant. This is only valid after
424 // GenerateSPIRVConstants has run.
425 uint32_t constant_i32_zero_id_;
David Neto22f144c2017-06-12 14:26:21 -0400426};
427
428char SPIRVProducerPass::ID;
David Netoc6f3ab22018-04-06 18:02:31 -0400429
David Neto22f144c2017-06-12 14:26:21 -0400430}
431
432namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400433ModulePass *
434createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
435 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
436 bool outputAsm, bool outputCInitList) {
437 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
438 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400439}
David Netoc2c368d2017-06-30 16:50:17 -0400440} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400441
442bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400443 binaryOut = outputCInitList ? &binaryTempOut : &out;
444
David Neto257c3892018-04-11 13:19:45 -0400445 constant_i32_zero_id_ = 0; // Reset, for the benefit of validity checks.
446
David Netoc6f3ab22018-04-06 18:02:31 -0400447 ArgSpecIdMap = AllocateArgSpecIds(module);
448
David Neto22f144c2017-06-12 14:26:21 -0400449 // SPIR-V always begins with its header information
450 outputHeader();
451
David Netoc6f3ab22018-04-06 18:02:31 -0400452 const DataLayout &DL = module.getDataLayout();
453
David Neto22f144c2017-06-12 14:26:21 -0400454 // Gather information from the LLVM IR that we require.
David Netoc6f3ab22018-04-06 18:02:31 -0400455 GenerateLLVMIRInfo(module, DL);
David Neto22f144c2017-06-12 14:26:21 -0400456
457 // If we are using a sampler map, find the type of the sampler.
458 if (0 < getSamplerMap().size()) {
459 auto SamplerStructTy = module.getTypeByName("opencl.sampler_t");
460 if (!SamplerStructTy) {
461 SamplerStructTy =
462 StructType::create(module.getContext(), "opencl.sampler_t");
463 }
464
465 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
466
467 FindType(SamplerTy);
468 }
469
470 // Collect information on global variables too.
471 for (GlobalVariable &GV : module.globals()) {
472 // If the GV is one of our special __spirv_* variables, remove the
473 // initializer as it was only placed there to force LLVM to not throw the
474 // value away.
475 if (GV.getName().startswith("__spirv_")) {
476 GV.setInitializer(nullptr);
477 }
478
479 // Collect types' information from global variable.
480 FindTypePerGlobalVar(GV);
481
482 // Collect constant information from global variable.
483 FindConstantPerGlobalVar(GV);
484
485 // If the variable is an input, entry points need to know about it.
486 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400487 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400488 }
489 }
490
David Netoc6f3ab22018-04-06 18:02:31 -0400491 // Find types related to pointer-to-local arguments.
492 for (auto& arg_spec_id_pair : ArgSpecIdMap) {
493 const Argument* arg = arg_spec_id_pair.first;
494 FindType(arg->getType());
495 FindType(arg->getType()->getPointerElementType());
496 }
497
David Neto22f144c2017-06-12 14:26:21 -0400498 // If there are extended instructions, generate OpExtInstImport.
499 if (FindExtInst(module)) {
500 GenerateExtInstImport();
501 }
502
503 // Generate SPIRV instructions for types.
David Netoc6f3ab22018-04-06 18:02:31 -0400504 GenerateSPIRVTypes(module.getContext(), DL);
David Neto22f144c2017-06-12 14:26:21 -0400505
506 // Generate SPIRV constants.
507 GenerateSPIRVConstants();
508
509 // If we have a sampler map, we might have literal samplers to generate.
510 if (0 < getSamplerMap().size()) {
511 GenerateSamplers(module);
512 }
513
514 // Generate SPIRV variables.
515 for (GlobalVariable &GV : module.globals()) {
516 GenerateGlobalVar(GV);
517 }
David Netoc6f3ab22018-04-06 18:02:31 -0400518 GenerateWorkgroupVars();
David Neto22f144c2017-06-12 14:26:21 -0400519
520 // Generate SPIRV instructions for each function.
521 for (Function &F : module) {
522 if (F.isDeclaration()) {
523 continue;
524 }
525
526 // Generate Function Prologue.
527 GenerateFuncPrologue(F);
528
529 // Generate SPIRV instructions for function body.
530 GenerateFuncBody(F);
531
532 // Generate Function Epilogue.
533 GenerateFuncEpilogue();
534 }
535
536 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400537 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400538
539 // Generate SPIRV module information.
David Neto5c22a252018-03-15 16:07:41 -0400540 GenerateModuleInfo(module);
David Neto22f144c2017-06-12 14:26:21 -0400541
542 if (outputAsm) {
543 WriteSPIRVAssembly();
544 } else {
545 WriteSPIRVBinary();
546 }
547
548 // We need to patch the SPIR-V header to set bound correctly.
549 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400550
551 if (outputCInitList) {
552 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400553 std::ostringstream os;
554
David Neto57fb0b92017-08-04 15:35:09 -0400555 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400556 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400557 os << ",\n";
558 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400559 first = false;
560 };
561
562 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400563 const std::string str(binaryTempOut.str());
564 for (unsigned i = 0; i < str.size(); i += 4) {
565 const uint32_t a = static_cast<unsigned char>(str[i]);
566 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
567 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
568 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
569 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400570 }
571 os << "}\n";
572 out << os.str();
573 }
574
David Neto22f144c2017-06-12 14:26:21 -0400575 return false;
576}
577
578void SPIRVProducerPass::outputHeader() {
579 if (outputAsm) {
580 // for ASM output the header goes into 5 comments at the beginning of the
581 // file
582 out << "; SPIR-V\n";
583
584 // the major version number is in the 2nd highest byte
585 const uint32_t major = (spv::Version >> 16) & 0xFF;
586
587 // the minor version number is in the 2nd lowest byte
588 const uint32_t minor = (spv::Version >> 8) & 0xFF;
589 out << "; Version: " << major << "." << minor << "\n";
590
591 // use Codeplay's vendor ID
592 out << "; Generator: Codeplay; 0\n";
593
594 out << "; Bound: ";
595
596 // we record where we need to come back to and patch in the bound value
597 patchBoundOffset = out.tell();
598
599 // output one space per digit for the max size of a 32 bit unsigned integer
600 // (which is the maximum ID we could possibly be using)
601 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
602 out << " ";
603 }
604
605 out << "\n";
606
607 out << "; Schema: 0\n";
608 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400609 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400610 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400611 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400612 sizeof(spv::Version));
613
614 // use Codeplay's vendor ID
615 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400616 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400617
618 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400619 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400620
621 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400622 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400623
624 // output the schema (reserved for use and must be 0)
625 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400626 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400627 }
628}
629
630void SPIRVProducerPass::patchHeader() {
631 if (outputAsm) {
632 // get the string representation of the max bound used (nextID will be the
633 // max ID used)
634 auto asString = std::to_string(nextID);
635 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
636 } else {
637 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400638 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
639 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400640 }
641}
642
David Netoc6f3ab22018-04-06 18:02:31 -0400643void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -0400644 // This function generates LLVM IR for function such as global variable for
645 // argument, constant and pointer type for argument access. These information
646 // is artificial one because we need Vulkan SPIR-V output. This function is
647 // executed ahead of FindType and FindConstant.
648 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
649 LLVMContext &Context = M.getContext();
650
651 // Map for avoiding to generate struct type with same fields.
652 DenseMap<Type *, Type *> ArgTyMap;
653
David Neto5c22a252018-03-15 16:07:41 -0400654 // These function calls need a <2 x i32> as an intermediate result but not
655 // the final result.
656 std::unordered_set<std::string> NeedsIVec2{
657 "_Z15get_image_width14ocl_image2d_ro",
658 "_Z15get_image_width14ocl_image2d_wo",
659 "_Z16get_image_height14ocl_image2d_ro",
660 "_Z16get_image_height14ocl_image2d_wo",
661 };
662
David Neto22f144c2017-06-12 14:26:21 -0400663 // Collect global constant variables.
David Netoc6f3ab22018-04-06 18:02:31 -0400664 {
665 SmallVector<GlobalVariable *, 8> GVList;
666 SmallVector<GlobalVariable *, 8> DeadGVList;
667 for (GlobalVariable &GV : M.globals()) {
668 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
669 if (GV.use_empty()) {
670 DeadGVList.push_back(&GV);
671 } else {
672 GVList.push_back(&GV);
673 }
David Netofba9d262018-03-24 06:14:18 -0700674 }
David Neto22f144c2017-06-12 14:26:21 -0400675 }
David Neto22f144c2017-06-12 14:26:21 -0400676
David Netoc6f3ab22018-04-06 18:02:31 -0400677 // Remove dead global __constant variables.
678 for (auto GV : DeadGVList) {
679 GV->eraseFromParent();
David Neto85082642018-03-24 06:55:20 -0700680 }
David Netoc6f3ab22018-04-06 18:02:31 -0400681 DeadGVList.clear();
David Neto22f144c2017-06-12 14:26:21 -0400682
David Netoc6f3ab22018-04-06 18:02:31 -0400683 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
684 // For now, we only support a single storage buffer.
685 if (GVList.size() > 0) {
686 assert(GVList.size() == 1);
687 const auto *GV = GVList[0];
688 const size_t constants_byte_size =
689 (DL.getTypeSizeInBits(GV->getInitializer()->getType())) / 8;
690 const size_t kConstantMaxSize = 65536;
691 if (constants_byte_size > kConstantMaxSize) {
692 outs() << "Max __constant capacity of " << kConstantMaxSize
693 << " bytes exceeded: " << constants_byte_size
694 << " bytes used\n";
695 llvm_unreachable("Max __constant capacity exceeded");
696 }
697 }
698 } else {
699 // Change global constant variable's address space to ModuleScopePrivate.
700 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
701 for (auto GV : GVList) {
702 // Create new gv with ModuleScopePrivate address space.
703 Type *NewGVTy = GV->getType()->getPointerElementType();
704 GlobalVariable *NewGV = new GlobalVariable(
705 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "",
706 nullptr, GV->getThreadLocalMode(),
707 AddressSpace::ModuleScopePrivate);
708 NewGV->takeName(GV);
David Neto22f144c2017-06-12 14:26:21 -0400709
David Netoc6f3ab22018-04-06 18:02:31 -0400710 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
711 SmallVector<User *, 8> CandidateUsers;
712
713 auto record_called_function_type_as_user =
714 [&GlobalConstFuncTyMap](Value *gv, CallInst *call) {
715 // Find argument index.
716 unsigned index = 0;
717 for (unsigned i = 0; i < call->getNumArgOperands(); i++) {
718 if (gv == call->getOperand(i)) {
719 // TODO(dneto): Should we break here?
720 index = i;
721 }
722 }
723
724 // Record function type with global constant.
725 GlobalConstFuncTyMap[call->getFunctionType()] =
726 std::make_pair(call->getFunctionType(), index);
727 };
728
729 for (User *GVU : GVUsers) {
730 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
731 record_called_function_type_as_user(GV, Call);
732 } else if (GetElementPtrInst *GEP =
733 dyn_cast<GetElementPtrInst>(GVU)) {
734 // Check GEP users.
735 for (User *GEPU : GEP->users()) {
736 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
737 record_called_function_type_as_user(GEP, GEPCall);
David Neto85082642018-03-24 06:55:20 -0700738 }
739 }
David Netoc77d9e22018-03-24 06:30:28 -0700740 }
David Netoc6f3ab22018-04-06 18:02:31 -0400741
742 CandidateUsers.push_back(GVU);
David Neto22f144c2017-06-12 14:26:21 -0400743 }
David Neto85082642018-03-24 06:55:20 -0700744
David Netoc6f3ab22018-04-06 18:02:31 -0400745 for (User *U : CandidateUsers) {
746 // Update users of gv with new gv.
747 U->replaceUsesOfWith(GV, NewGV);
748 }
David Neto22f144c2017-06-12 14:26:21 -0400749
David Netoc6f3ab22018-04-06 18:02:31 -0400750 // Delete original gv.
751 GV->eraseFromParent();
David Neto85082642018-03-24 06:55:20 -0700752 }
David Neto22f144c2017-06-12 14:26:21 -0400753 }
David Neto22f144c2017-06-12 14:26:21 -0400754 }
755
756 bool HasWorkGroupBuiltin = false;
757 for (GlobalVariable &GV : M.globals()) {
758 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
759 if (spv::BuiltInWorkgroupSize == BuiltinType) {
760 HasWorkGroupBuiltin = true;
761 }
762 }
763
764
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 Netoc6f3ab22018-04-06 18:02:31 -0400772 // For each kernel argument type, record the kernel arg global resource variables
David Neto26aaf622017-10-23 18:11:53 -0400773 // generated for that type, the function in which that variable was most
774 // recently used, and the binding number it took. For reproducibility,
775 // we track things by ordinal number (rather than pointer), and we use a
776 // std::set rather than DenseSet since std::set maintains an ordering.
777 // Each tuple is the ordinals of the kernel function, the binding number,
778 // and the ordinal of the kernal-arg-var.
779 //
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 Neto22f144c2017-06-12 14:26:21 -0400785 for (Function &F : M) {
786 // Handle kernel function first.
787 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
788 continue;
789 }
David Neto26aaf622017-10-23 18:11:53 -0400790 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400791
792 for (BasicBlock &BB : F) {
793 for (Instruction &I : BB) {
794 if (I.getOpcode() == Instruction::ZExt ||
795 I.getOpcode() == Instruction::SExt ||
796 I.getOpcode() == Instruction::UIToFP) {
797 // If there is zext with i1 type, it will be changed to OpSelect. The
798 // OpSelect needs constant 0 and 1 so the constants are added here.
799
800 auto OpTy = I.getOperand(0)->getType();
801
802 if (OpTy->isIntegerTy(1) ||
803 (OpTy->isVectorTy() &&
804 OpTy->getVectorElementType()->isIntegerTy(1))) {
805 if (I.getOpcode() == Instruction::ZExt) {
806 APInt One(32, 1);
807 FindConstant(Constant::getNullValue(I.getType()));
808 FindConstant(Constant::getIntegerValue(I.getType(), One));
809 } else if (I.getOpcode() == Instruction::SExt) {
810 APInt MinusOne(32, UINT64_MAX, true);
811 FindConstant(Constant::getNullValue(I.getType()));
812 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
813 } else {
814 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
815 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
816 }
817 }
818 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
819 Function *Callee = Call->getCalledFunction();
820
821 // Handle image type specially.
822 if (Callee->getName().equals(
823 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
824 Callee->getName().equals(
825 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
826 TypeMapType &OpImageTypeMap = getImageTypeMap();
827 Type *ImageTy =
828 Call->getArgOperand(0)->getType()->getPointerElementType();
829 OpImageTypeMap[ImageTy] = 0;
830
831 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
832 }
David Neto5c22a252018-03-15 16:07:41 -0400833
834 if (NeedsIVec2.find(Callee->getName()) != NeedsIVec2.end()) {
835 FindType(VectorType::get(Type::getInt32Ty(Context), 2));
836 }
David Neto22f144c2017-06-12 14:26:21 -0400837 }
838 }
839 }
840
841 if (M.getTypeByName("opencl.image2d_ro_t") ||
842 M.getTypeByName("opencl.image2d_wo_t") ||
843 M.getTypeByName("opencl.image3d_ro_t") ||
844 M.getTypeByName("opencl.image3d_wo_t")) {
845 // Assume Image type's sampled type is float type.
846 FindType(Type::getFloatTy(Context));
847 }
848
849 if (const MDNode *MD =
850 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
851 // We generate constants if the WorkgroupSize builtin is being used.
852 if (HasWorkGroupBuiltin) {
853 // Collect constant information for work group size.
854 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
855 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
856 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
857 }
858 }
859
860 // Wrap up all argument types with struct type and create global variables
861 // with them.
862 bool HasArgUser = false;
863 unsigned Idx = 0;
864
865 for (const Argument &Arg : F.args()) {
866 Type *ArgTy = Arg.getType();
David Neto22f144c2017-06-12 14:26:21 -0400867
David Netoe439d702018-03-23 13:14:08 -0700868 // The pointee type of the module scope variable we will make.
869 Type *GVTy = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400870
871 Type *TmpArgTy = ArgTy;
872
873 // sampler_t and image types have pointer type of struct type with
David Netoe439d702018-03-23 13:14:08 -0700874 // opaque type as field. Extract the struct type. It will be used by
875 // global variable for argument.
David Neto22f144c2017-06-12 14:26:21 -0400876 bool IsSamplerType = false;
877 bool IsImageType = false;
878 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
879 if (StructType *STy =
880 dyn_cast<StructType>(TmpArgPTy->getElementType())) {
881 if (STy->isOpaque()) {
882 if (STy->getName().equals("opencl.sampler_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400883 IsSamplerType = true;
884 TmpArgTy = STy;
885 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
886 STy->getName().equals("opencl.image2d_wo_t") ||
887 STy->getName().equals("opencl.image3d_ro_t") ||
888 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -0400889 IsImageType = true;
890 TmpArgTy = STy;
891 } else {
892 llvm_unreachable("Argument has opaque type unsupported???");
893 }
894 }
895 }
896 }
David Netoc6f3ab22018-04-06 18:02:31 -0400897 const bool IsPointerToLocal = IsLocalPtr(ArgTy);
898 // Can't both be pointer-to-local and (sampler or image).
899 assert(!((IsSamplerType || IsImageType) && IsPointerToLocal));
David Neto22f144c2017-06-12 14:26:21 -0400900
David Netoe439d702018-03-23 13:14:08 -0700901 // Determine the address space for the module-scope variable.
902 unsigned AddrSpace = AddressSpace::Global;
903 if (IsSamplerType || IsImageType) {
904 AddrSpace = AddressSpace::UniformConstant;
905 } else if (PointerType *ArgPTy = dyn_cast<PointerType>(ArgTy)) {
906 AddrSpace = ArgPTy->getAddressSpace();
David Neto482550a2018-03-24 05:21:07 -0700907 } else if (clspv::Option::PodArgsInUniformBuffer()) {
David Netoe439d702018-03-23 13:14:08 -0700908 // Use a uniform buffer for POD arguments.
909 AddrSpace = AddressSpace::Uniform;
910 }
911
David Neto22f144c2017-06-12 14:26:21 -0400912 // LLVM's pointer type is distinguished by address space but we need to
913 // regard constant and global address space as same here. If pointer
914 // type has constant address space, generate new pointer type
915 // temporarily to check previous struct type for argument.
916 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
David Netoe439d702018-03-23 13:14:08 -0700917 if (TmpArgPTy->getAddressSpace() == AddressSpace::Constant) {
David Neto22f144c2017-06-12 14:26:21 -0400918 TmpArgTy = PointerType::get(TmpArgPTy->getElementType(),
919 AddressSpace::Global);
920 }
921 }
922
923 if (IsSamplerType || IsImageType) {
924 GVTy = TmpArgTy;
David Netoc6f3ab22018-04-06 18:02:31 -0400925 } else if (IsPointerToLocal) {
926 assert(ArgTy == TmpArgTy);
927 auto spec_id = ArgSpecIdMap[&Arg];
928 assert(spec_id > 0);
929 LocalArgMap[&Arg] =
930 LocalArgInfo{nextID, ArgTy->getPointerElementType(),
931 nextID + 1, nextID + 2,
932 nextID + 3, nextID + 4,
933 spec_id};
934 LocalArgs.push_back(&Arg);
935 nextID += 5;
David Neto22f144c2017-06-12 14:26:21 -0400936 } else if (ArgTyMap.count(TmpArgTy)) {
937 // If there are arguments handled previously, use its type.
938 GVTy = ArgTyMap[TmpArgTy];
939 } else {
940 // Wrap up argument type with struct type.
David Neto83add0a2017-10-23 15:30:59 -0400941 // Reuse struct types where possible.
David Neto7b2abea2017-10-23 20:02:02 -0400942 SmallVector<Type*,1> members{ArgTy};
David Neto83add0a2017-10-23 15:30:59 -0400943 StructType *STy = StructType::get(Context, members);
David Neto22f144c2017-06-12 14:26:21 -0400944
945 GVTy = STy;
946 ArgTyMap[TmpArgTy] = STy;
947 }
948
David Netoc6f3ab22018-04-06 18:02:31 -0400949 if (!IsPointerToLocal) {
950 // In order to build type map between llvm type and spirv id, LLVM
951 // global variable is needed. It has llvm type and other instructions
952 // can access it with its type.
953 //
954 // Reuse a global variable if it was created for a different entry
955 // point.
David Neto26aaf622017-10-23 18:11:53 -0400956
David Netoc6f3ab22018-04-06 18:02:31 -0400957 // Returns a new global variable for this kernel argument, and remembers
958 // it in KernelArgVarOrdinal.
959 auto make_gvar = [&]() {
960 auto result = new GlobalVariable(
961 M, GVTy, false, GlobalValue::ExternalLinkage,
962 UndefValue::get(GVTy),
963 F.getName() + ".arg." + std::to_string(Idx), nullptr,
964 GlobalValue::ThreadLocalMode::NotThreadLocal, AddrSpace);
965 KernelArgVarOrdinal.insert(result);
966 return result;
967 };
David Neto26aaf622017-10-23 18:11:53 -0400968
David Netoc6f3ab22018-04-06 18:02:31 -0400969 // Make a new variable if there was none for this type, or if we can
970 // reuse one created for a different function but not yet reused for
971 // the current function, *and* the binding is the same.
972 // Always make a new variable if we're forcing distinct descriptor sets.
973 GlobalVariable *GV = nullptr;
974 auto which_set = GVarsForType.find(GVTy);
975 if (IsSamplerType || IsImageType || which_set == GVarsForType.end() ||
976 clspv::Option::DistinctKernelDescriptorSets()) {
977 GV = make_gvar();
978 } else {
979 auto &set = which_set->second;
980 // Reuse a variable if it was associated with a different function.
981 for (auto iter = set.begin(), end = set.end(); iter != end; ++iter) {
982 const unsigned fn_ordinal = std::get<0>(*iter);
983 const unsigned binding = std::get<1>(*iter);
984 if (fn_ordinal != KernelOrdinal.idFor(&F) && binding == Idx) {
985 GV = KernelArgVarOrdinal[std::get<2>(*iter)];
986 // Remove it from the set. We'll add it back later.
987 set.erase(iter);
988 break;
989 }
990 }
991 if (!GV) {
992 GV = make_gvar();
David Neto26aaf622017-10-23 18:11:53 -0400993 }
994 }
David Netoc6f3ab22018-04-06 18:02:31 -0400995 assert(GV);
996 GVarsForType[GVTy].insert(std::make_tuple(
997 KernelOrdinal.idFor(&F), Idx, KernelArgVarOrdinal.idFor(GV)));
998
999 // Generate type info for argument global variable.
1000 FindType(GV->getType());
1001
1002 ArgGVMap[&Arg] = GV;
1003
1004 Idx++;
David Neto26aaf622017-10-23 18:11:53 -04001005 }
David Neto22f144c2017-06-12 14:26:21 -04001006
1007 // Generate pointer type of argument type for OpAccessChain of argument.
1008 if (!Arg.use_empty()) {
1009 if (!isa<PointerType>(ArgTy)) {
David Netoe439d702018-03-23 13:14:08 -07001010 auto ty = PointerType::get(ArgTy, AddrSpace);
1011 FindType(ty);
David Neto22f144c2017-06-12 14:26:21 -04001012 }
1013 HasArgUser = true;
1014 }
1015 }
1016
1017 if (HasArgUser) {
1018 // Generate constant 0 for OpAccessChain of argument.
1019 Type *IdxTy = Type::getInt32Ty(Context);
1020 FindConstant(ConstantInt::get(IdxTy, 0));
1021 FindType(IdxTy);
1022 }
1023
1024 // Collect types' information from function.
1025 FindTypePerFunc(F);
1026
1027 // Collect constant information from function.
1028 FindConstantPerFunc(F);
1029 }
1030
1031 for (Function &F : M) {
1032 // Handle non-kernel functions.
1033 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
1034 continue;
1035 }
1036
1037 for (BasicBlock &BB : F) {
1038 for (Instruction &I : BB) {
1039 if (I.getOpcode() == Instruction::ZExt ||
1040 I.getOpcode() == Instruction::SExt ||
1041 I.getOpcode() == Instruction::UIToFP) {
1042 // If there is zext with i1 type, it will be changed to OpSelect. The
1043 // OpSelect needs constant 0 and 1 so the constants are added here.
1044
1045 auto OpTy = I.getOperand(0)->getType();
1046
1047 if (OpTy->isIntegerTy(1) ||
1048 (OpTy->isVectorTy() &&
1049 OpTy->getVectorElementType()->isIntegerTy(1))) {
1050 if (I.getOpcode() == Instruction::ZExt) {
1051 APInt One(32, 1);
1052 FindConstant(Constant::getNullValue(I.getType()));
1053 FindConstant(Constant::getIntegerValue(I.getType(), One));
1054 } else if (I.getOpcode() == Instruction::SExt) {
1055 APInt MinusOne(32, UINT64_MAX, true);
1056 FindConstant(Constant::getNullValue(I.getType()));
1057 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
1058 } else {
1059 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
1060 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
1061 }
1062 }
1063 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1064 Function *Callee = Call->getCalledFunction();
1065
1066 // Handle image type specially.
1067 if (Callee->getName().equals(
1068 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
1069 Callee->getName().equals(
1070 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
1071 TypeMapType &OpImageTypeMap = getImageTypeMap();
1072 Type *ImageTy =
1073 Call->getArgOperand(0)->getType()->getPointerElementType();
1074 OpImageTypeMap[ImageTy] = 0;
1075
1076 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
1077 }
1078 }
1079 }
1080 }
1081
1082 if (M.getTypeByName("opencl.image2d_ro_t") ||
1083 M.getTypeByName("opencl.image2d_wo_t") ||
1084 M.getTypeByName("opencl.image3d_ro_t") ||
1085 M.getTypeByName("opencl.image3d_wo_t")) {
1086 // Assume Image type's sampled type is float type.
1087 FindType(Type::getFloatTy(Context));
1088 }
1089
1090 // Collect types' information from function.
1091 FindTypePerFunc(F);
1092
1093 // Collect constant information from function.
1094 FindConstantPerFunc(F);
1095 }
1096}
1097
1098bool SPIRVProducerPass::FindExtInst(Module &M) {
1099 LLVMContext &Context = M.getContext();
1100 bool HasExtInst = false;
1101
1102 for (Function &F : M) {
1103 for (BasicBlock &BB : F) {
1104 for (Instruction &I : BB) {
1105 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1106 Function *Callee = Call->getCalledFunction();
1107 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -04001108 auto callee_name = Callee->getName();
1109 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
1110 const glsl::ExtInst IndirectEInst =
1111 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04001112
David Neto3fbb4072017-10-16 11:28:14 -04001113 HasExtInst |=
1114 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
1115
1116 if (IndirectEInst) {
1117 // Register extra constants if needed.
1118
1119 // Registers a type and constant for computing the result of the
1120 // given instruction. If the result of the instruction is a vector,
1121 // then make a splat vector constant with the same number of
1122 // elements.
1123 auto register_constant = [this, &I](Constant *constant) {
1124 FindType(constant->getType());
1125 FindConstant(constant);
1126 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
1127 // Register the splat vector of the value with the same
1128 // width as the result of the instruction.
1129 auto *vec_constant = ConstantVector::getSplat(
1130 static_cast<unsigned>(vectorTy->getNumElements()),
1131 constant);
1132 FindConstant(vec_constant);
1133 FindType(vec_constant->getType());
1134 }
1135 };
1136 switch (IndirectEInst) {
1137 case glsl::ExtInstFindUMsb:
1138 // clz needs OpExtInst and OpISub with constant 31, or splat
1139 // vector of 31. Add it to the constant list here.
1140 register_constant(
1141 ConstantInt::get(Type::getInt32Ty(Context), 31));
1142 break;
1143 case glsl::ExtInstAcos:
1144 case glsl::ExtInstAsin:
1145 case glsl::ExtInstAtan2:
1146 // We need 1/pi for acospi, asinpi, atan2pi.
1147 register_constant(
1148 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1149 break;
1150 default:
1151 assert(false && "internally inconsistent");
1152 }
David Neto22f144c2017-06-12 14:26:21 -04001153 }
1154 }
1155 }
1156 }
1157 }
1158
1159 return HasExtInst;
1160}
1161
1162void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1163 // Investigate global variable's type.
1164 FindType(GV.getType());
1165}
1166
1167void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1168 // Investigate function's type.
1169 FunctionType *FTy = F.getFunctionType();
1170
1171 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1172 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
David Neto9ed8e2f2018-03-24 06:47:24 -07001173 // Handle a regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04001174 if (GlobalConstFuncTyMap.count(FTy)) {
1175 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1176 SmallVector<Type *, 4> NewFuncParamTys;
1177 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1178 Type *ParamTy = FTy->getParamType(i);
1179 if (i == GVCstArgIdx) {
1180 Type *EleTy = ParamTy->getPointerElementType();
1181 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1182 }
1183
1184 NewFuncParamTys.push_back(ParamTy);
1185 }
1186
1187 FunctionType *NewFTy =
1188 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1189 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1190 FTy = NewFTy;
1191 }
1192
1193 FindType(FTy);
1194 } else {
1195 // As kernel functions do not have parameters, create new function type and
1196 // add it to type map.
1197 SmallVector<Type *, 4> NewFuncParamTys;
1198 FunctionType *NewFTy =
1199 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1200 FindType(NewFTy);
1201 }
1202
1203 // Investigate instructions' type in function body.
1204 for (BasicBlock &BB : F) {
1205 for (Instruction &I : BB) {
1206 if (isa<ShuffleVectorInst>(I)) {
1207 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1208 // Ignore type for mask of shuffle vector instruction.
1209 if (i == 2) {
1210 continue;
1211 }
1212
1213 Value *Op = I.getOperand(i);
1214 if (!isa<MetadataAsValue>(Op)) {
1215 FindType(Op->getType());
1216 }
1217 }
1218
1219 FindType(I.getType());
1220 continue;
1221 }
1222
1223 // Work through the operands of the instruction.
1224 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1225 Value *const Op = I.getOperand(i);
1226 // If any of the operands is a constant, find the type!
1227 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1228 FindType(Op->getType());
1229 }
1230 }
1231
1232 for (Use &Op : I.operands()) {
1233 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1234 // Avoid to check call instruction's type.
1235 break;
1236 }
1237 if (!isa<MetadataAsValue>(&Op)) {
1238 FindType(Op->getType());
1239 continue;
1240 }
1241 }
1242
1243 CallInst *Call = dyn_cast<CallInst>(&I);
1244
1245 // We don't want to track the type of this call as we are going to replace
1246 // it.
1247 if (Call && ("__translate_sampler_initializer" ==
1248 Call->getCalledFunction()->getName())) {
1249 continue;
1250 }
1251
1252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1253 // If gep's base operand has ModuleScopePrivate address space, make gep
1254 // return ModuleScopePrivate address space.
1255 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1256 // Add pointer type with private address space for global constant to
1257 // type list.
1258 Type *EleTy = I.getType()->getPointerElementType();
1259 Type *NewPTy =
1260 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1261
1262 FindType(NewPTy);
1263 continue;
1264 }
1265 }
1266
1267 FindType(I.getType());
1268 }
1269 }
1270}
1271
1272void SPIRVProducerPass::FindType(Type *Ty) {
1273 TypeList &TyList = getTypeList();
1274
1275 if (0 != TyList.idFor(Ty)) {
1276 return;
1277 }
1278
1279 if (Ty->isPointerTy()) {
1280 auto AddrSpace = Ty->getPointerAddressSpace();
1281 if ((AddressSpace::Constant == AddrSpace) ||
1282 (AddressSpace::Global == AddrSpace)) {
1283 auto PointeeTy = Ty->getPointerElementType();
1284
1285 if (PointeeTy->isStructTy() &&
1286 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1287 FindType(PointeeTy);
1288 auto ActualPointerTy =
1289 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1290 FindType(ActualPointerTy);
1291 return;
1292 }
1293 }
1294 }
1295
1296 // OpTypeArray has constant and we need to support type of the constant.
1297 if (isa<ArrayType>(Ty)) {
1298 LLVMContext &Context = Ty->getContext();
1299 FindType(Type::getInt32Ty(Context));
1300 }
1301
1302 for (Type *SubTy : Ty->subtypes()) {
1303 FindType(SubTy);
1304 }
1305
1306 TyList.insert(Ty);
1307}
1308
1309void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1310 // If the global variable has a (non undef) initializer.
1311 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1312 FindConstant(GV.getInitializer());
1313 }
1314}
1315
1316void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1317 // Investigate constants in function body.
1318 for (BasicBlock &BB : F) {
1319 for (Instruction &I : BB) {
1320 CallInst *Call = dyn_cast<CallInst>(&I);
1321
1322 if (Call && ("__translate_sampler_initializer" ==
1323 Call->getCalledFunction()->getName())) {
1324 // We've handled these constants elsewhere, so skip it.
1325 continue;
1326 }
1327
1328 if (isa<AllocaInst>(I)) {
1329 // Alloca instruction has constant for the number of element. Ignore it.
1330 continue;
1331 } else if (isa<ShuffleVectorInst>(I)) {
1332 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1333 // Ignore constant for mask of shuffle vector instruction.
1334 if (i == 2) {
1335 continue;
1336 }
1337
1338 if (isa<Constant>(I.getOperand(i)) &&
1339 !isa<GlobalValue>(I.getOperand(i))) {
1340 FindConstant(I.getOperand(i));
1341 }
1342 }
1343
1344 continue;
1345 } else if (isa<InsertElementInst>(I)) {
1346 // Handle InsertElement with <4 x i8> specially.
1347 Type *CompositeTy = I.getOperand(0)->getType();
1348 if (is4xi8vec(CompositeTy)) {
1349 LLVMContext &Context = CompositeTy->getContext();
1350 if (isa<Constant>(I.getOperand(0))) {
1351 FindConstant(I.getOperand(0));
1352 }
1353
1354 if (isa<Constant>(I.getOperand(1))) {
1355 FindConstant(I.getOperand(1));
1356 }
1357
1358 // Add mask constant 0xFF.
1359 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1360 FindConstant(CstFF);
1361
1362 // Add shift amount constant.
1363 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1364 uint64_t Idx = CI->getZExtValue();
1365 Constant *CstShiftAmount =
1366 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1367 FindConstant(CstShiftAmount);
1368 }
1369
1370 continue;
1371 }
1372
1373 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1374 // Ignore constant for index of InsertElement instruction.
1375 if (i == 2) {
1376 continue;
1377 }
1378
1379 if (isa<Constant>(I.getOperand(i)) &&
1380 !isa<GlobalValue>(I.getOperand(i))) {
1381 FindConstant(I.getOperand(i));
1382 }
1383 }
1384
1385 continue;
1386 } else if (isa<ExtractElementInst>(I)) {
1387 // Handle ExtractElement with <4 x i8> specially.
1388 Type *CompositeTy = I.getOperand(0)->getType();
1389 if (is4xi8vec(CompositeTy)) {
1390 LLVMContext &Context = CompositeTy->getContext();
1391 if (isa<Constant>(I.getOperand(0))) {
1392 FindConstant(I.getOperand(0));
1393 }
1394
1395 // Add mask constant 0xFF.
1396 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1397 FindConstant(CstFF);
1398
1399 // Add shift amount constant.
1400 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1401 uint64_t Idx = CI->getZExtValue();
1402 Constant *CstShiftAmount =
1403 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1404 FindConstant(CstShiftAmount);
1405 } else {
1406 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1407 FindConstant(Cst8);
1408 }
1409
1410 continue;
1411 }
1412
1413 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1414 // Ignore constant for index of ExtractElement instruction.
1415 if (i == 1) {
1416 continue;
1417 }
1418
1419 if (isa<Constant>(I.getOperand(i)) &&
1420 !isa<GlobalValue>(I.getOperand(i))) {
1421 FindConstant(I.getOperand(i));
1422 }
1423 }
1424
1425 continue;
1426 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1427 // 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
1428 bool foundConstantTrue = false;
1429 for (Use &Op : I.operands()) {
1430 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1431 auto CI = cast<ConstantInt>(Op);
1432
1433 if (CI->isZero() || foundConstantTrue) {
1434 // 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.
1435 FindConstant(Op);
1436 } else {
1437 foundConstantTrue = true;
1438 }
1439 }
1440 }
1441
1442 continue;
David Netod2de94a2017-08-28 17:27:47 -04001443 } else if (isa<TruncInst>(I)) {
1444 // For truncation to i8 we mask against 255.
1445 Type *ToTy = I.getType();
1446 if (8u == ToTy->getPrimitiveSizeInBits()) {
1447 LLVMContext &Context = ToTy->getContext();
1448 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1449 FindConstant(Cst255);
1450 }
1451 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001452 } else if (isa<AtomicRMWInst>(I)) {
1453 LLVMContext &Context = I.getContext();
1454
1455 FindConstant(
1456 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1457 FindConstant(ConstantInt::get(
1458 Type::getInt32Ty(Context),
1459 spv::MemorySemanticsUniformMemoryMask |
1460 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001461 }
1462
1463 for (Use &Op : I.operands()) {
1464 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1465 FindConstant(Op);
1466 }
1467 }
1468 }
1469 }
1470}
1471
1472void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001473 ValueList &CstList = getConstantList();
1474
David Netofb9a7972017-08-25 17:08:24 -04001475 // If V is already tracked, ignore it.
1476 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001477 return;
1478 }
1479
1480 Constant *Cst = cast<Constant>(V);
1481
1482 // Handle constant with <4 x i8> type specially.
1483 Type *CstTy = Cst->getType();
1484 if (is4xi8vec(CstTy)) {
1485 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001486 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001487 }
1488 }
1489
1490 if (Cst->getNumOperands()) {
1491 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1492 ++I) {
1493 FindConstant(*I);
1494 }
1495
David Netofb9a7972017-08-25 17:08:24 -04001496 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001497 return;
1498 } else if (const ConstantDataSequential *CDS =
1499 dyn_cast<ConstantDataSequential>(Cst)) {
1500 // Add constants for each element to constant list.
1501 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1502 Constant *EleCst = CDS->getElementAsConstant(i);
1503 FindConstant(EleCst);
1504 }
1505 }
1506
1507 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001508 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001509 }
1510}
1511
1512spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1513 switch (AddrSpace) {
1514 default:
1515 llvm_unreachable("Unsupported OpenCL address space");
1516 case AddressSpace::Private:
1517 return spv::StorageClassFunction;
1518 case AddressSpace::Global:
1519 case AddressSpace::Constant:
1520 return spv::StorageClassStorageBuffer;
1521 case AddressSpace::Input:
1522 return spv::StorageClassInput;
1523 case AddressSpace::Local:
1524 return spv::StorageClassWorkgroup;
1525 case AddressSpace::UniformConstant:
1526 return spv::StorageClassUniformConstant;
David Neto9ed8e2f2018-03-24 06:47:24 -07001527 case AddressSpace::Uniform:
David Netoe439d702018-03-23 13:14:08 -07001528 return spv::StorageClassUniform;
David Neto22f144c2017-06-12 14:26:21 -04001529 case AddressSpace::ModuleScopePrivate:
1530 return spv::StorageClassPrivate;
1531 }
1532}
1533
1534spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1535 return StringSwitch<spv::BuiltIn>(Name)
1536 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1537 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1538 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1539 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1540 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1541 .Default(spv::BuiltInMax);
1542}
1543
1544void SPIRVProducerPass::GenerateExtInstImport() {
1545 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1546 uint32_t &ExtInstImportID = getOpExtInstImportID();
1547
1548 //
1549 // Generate OpExtInstImport.
1550 //
1551 // Ops[0] ... Ops[n] = Name (Literal String)
1552 SPIRVOperandList Ops;
1553
David Neto257c3892018-04-11 13:19:45 -04001554 const char* name = "GLSL.std.450";
1555 Ops << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04001556
David Neto257c3892018-04-11 13:19:45 -04001557 const size_t NameWordSize = (std::strlen(name) + 4)/4;
David Neto22f144c2017-06-12 14:26:21 -04001558 assert(NameWordSize < (UINT16_MAX - 2));
David Neto22f144c2017-06-12 14:26:21 -04001559
1560 uint16_t WordCount = static_cast<uint16_t>(2 + NameWordSize);
1561 ExtInstImportID = nextID;
1562
1563 SPIRVInstruction *Inst =
1564 new SPIRVInstruction(WordCount, spv::OpExtInstImport, nextID++, Ops);
1565 SPIRVInstList.push_back(Inst);
1566}
1567
David Netoc6f3ab22018-04-06 18:02:31 -04001568void SPIRVProducerPass::GenerateSPIRVTypes(LLVMContext& Context, const DataLayout &DL) {
David Neto22f144c2017-06-12 14:26:21 -04001569 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1570 ValueMapType &VMap = getValueMap();
1571 ValueMapType &AllocatedVMap = getAllocatedValueMap();
1572 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
1573
1574 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1575 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1576 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1577
1578 for (Type *Ty : getTypeList()) {
1579 // Update TypeMap with nextID for reference later.
1580 TypeMap[Ty] = nextID;
1581
1582 switch (Ty->getTypeID()) {
1583 default: {
1584 Ty->print(errs());
1585 llvm_unreachable("Unsupported type???");
1586 break;
1587 }
1588 case Type::MetadataTyID:
1589 case Type::LabelTyID: {
1590 // Ignore these types.
1591 break;
1592 }
1593 case Type::PointerTyID: {
1594 PointerType *PTy = cast<PointerType>(Ty);
1595 unsigned AddrSpace = PTy->getAddressSpace();
1596
1597 // For the purposes of our Vulkan SPIR-V type system, constant and global
1598 // are conflated.
1599 bool UseExistingOpTypePointer = false;
1600 if (AddressSpace::Constant == AddrSpace) {
1601 AddrSpace = AddressSpace::Global;
1602
1603 // Check to see if we already created this type (for instance, if we had
1604 // a constant <type>* and a global <type>*, the type would be created by
1605 // one of these types, and shared by both).
1606 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1607 if (0 < TypeMap.count(GlobalTy)) {
1608 TypeMap[PTy] = TypeMap[GlobalTy];
David Netoe439d702018-03-23 13:14:08 -07001609 UseExistingOpTypePointer = true;
David Neto22f144c2017-06-12 14:26:21 -04001610 break;
1611 }
1612 } else if (AddressSpace::Global == AddrSpace) {
1613 AddrSpace = AddressSpace::Constant;
1614
1615 // Check to see if we already created this type (for instance, if we had
1616 // a constant <type>* and a global <type>*, the type would be created by
1617 // one of these types, and shared by both).
1618 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1619 if (0 < TypeMap.count(ConstantTy)) {
1620 TypeMap[PTy] = TypeMap[ConstantTy];
1621 UseExistingOpTypePointer = true;
1622 }
1623 }
1624
1625 bool IsOpTypeRuntimeArray = false;
1626 bool HasArgUser = false;
1627
1628 for (auto ArgGV : ArgGVMap) {
1629 auto Arg = ArgGV.first;
1630
1631 Type *ArgTy = Arg->getType();
1632 if (ArgTy == PTy) {
1633 if (AddrSpace != AddressSpace::UniformConstant) {
1634 IsOpTypeRuntimeArray = true;
1635 }
1636
1637 for (auto U : Arg->users()) {
1638 if (!isa<GetElementPtrInst>(U) || (U->getType() == PTy)) {
1639 HasArgUser = true;
1640 break;
1641 }
1642 }
1643 }
1644 }
1645
1646 if ((!IsOpTypeRuntimeArray || HasArgUser) && !UseExistingOpTypePointer) {
1647 //
1648 // Generate OpTypePointer.
1649 //
1650
1651 // OpTypePointer
1652 // Ops[0] = Storage Class
1653 // Ops[1] = Element Type ID
1654 SPIRVOperandList Ops;
1655
David Neto257c3892018-04-11 13:19:45 -04001656 Ops << MkNum(GetStorageClass(AddrSpace))
1657 << MkId(lookupType(PTy->getElementType()));
David Neto22f144c2017-06-12 14:26:21 -04001658
1659 spv::Op Opcode = spv::OpTypePointer;
1660 uint16_t WordCount = 4;
1661
1662 SPIRVInstruction *Inst =
1663 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1664 SPIRVInstList.push_back(Inst);
1665 }
1666
1667 if (IsOpTypeRuntimeArray) {
1668 //
1669 // Generate OpTypeRuntimeArray.
1670 //
1671
1672 // OpTypeRuntimeArray
1673 // Ops[0] = Element Type ID
1674 SPIRVOperandList Ops;
1675
David Neto257c3892018-04-11 13:19:45 -04001676 Type *EleTy = PTy->getElementType();
1677 Ops << MkId(lookupType(EleTy));
David Neto22f144c2017-06-12 14:26:21 -04001678
1679 spv::Op Opcode = spv::OpTypeRuntimeArray;
1680 uint16_t WordCount = 3;
1681
1682 uint32_t OpTypeRuntimeArrayID = nextID;
1683 assert(0 == OpRuntimeTyMap.count(Ty));
1684 OpRuntimeTyMap[Ty] = nextID;
1685
1686 SPIRVInstruction *Inst =
1687 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1688 SPIRVInstList.push_back(Inst);
1689
1690 // Generate OpDecorate.
1691 auto DecoInsertPoint =
1692 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1693 [](SPIRVInstruction *Inst) -> bool {
1694 return Inst->getOpcode() != spv::OpDecorate &&
1695 Inst->getOpcode() != spv::OpMemberDecorate &&
1696 Inst->getOpcode() != spv::OpExtInstImport;
1697 });
1698
1699 // Ops[0] = Target ID
1700 // Ops[1] = Decoration (ArrayStride)
1701 // Ops[2] = Stride Number(Literal Number)
1702 Ops.clear();
1703
David Neto257c3892018-04-11 13:19:45 -04001704 Ops << MkId(OpTypeRuntimeArrayID) << MkNum(spv::DecorationArrayStride)
1705 << MkNum(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04001706
1707 SPIRVInstruction *DecoInst =
1708 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
1709 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1710 }
1711 break;
1712 }
1713 case Type::StructTyID: {
1714 LLVMContext &Context = Ty->getContext();
1715
1716 StructType *STy = cast<StructType>(Ty);
1717
1718 // Handle sampler type.
1719 if (STy->isOpaque()) {
1720 if (STy->getName().equals("opencl.sampler_t")) {
1721 //
1722 // Generate OpTypeSampler
1723 //
1724 // Empty Ops.
1725 SPIRVOperandList Ops;
1726
1727 SPIRVInstruction *Inst =
1728 new SPIRVInstruction(2, spv::OpTypeSampler, nextID++, Ops);
1729 SPIRVInstList.push_back(Inst);
1730 break;
1731 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1732 STy->getName().equals("opencl.image2d_wo_t") ||
1733 STy->getName().equals("opencl.image3d_ro_t") ||
1734 STy->getName().equals("opencl.image3d_wo_t")) {
1735 //
1736 // Generate OpTypeImage
1737 //
1738 // Ops[0] = Sampled Type ID
1739 // Ops[1] = Dim ID
1740 // Ops[2] = Depth (Literal Number)
1741 // Ops[3] = Arrayed (Literal Number)
1742 // Ops[4] = MS (Literal Number)
1743 // Ops[5] = Sampled (Literal Number)
1744 // Ops[6] = Image Format ID
1745 //
1746 SPIRVOperandList Ops;
1747
1748 // TODO: Changed Sampled Type according to situations.
1749 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
David Neto257c3892018-04-11 13:19:45 -04001750 Ops << MkId(SampledTyID);
David Neto22f144c2017-06-12 14:26:21 -04001751
1752 spv::Dim DimID = spv::Dim2D;
1753 if (STy->getName().equals("opencl.image3d_ro_t") ||
1754 STy->getName().equals("opencl.image3d_wo_t")) {
1755 DimID = spv::Dim3D;
1756 }
David Neto257c3892018-04-11 13:19:45 -04001757 Ops << MkNum(DimID);
David Neto22f144c2017-06-12 14:26:21 -04001758
1759 // TODO: Set up Depth.
David Neto257c3892018-04-11 13:19:45 -04001760 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001761
1762 // TODO: Set up Arrayed.
David Neto257c3892018-04-11 13:19:45 -04001763 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001764
1765 // TODO: Set up MS.
David Neto257c3892018-04-11 13:19:45 -04001766 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04001767
1768 // TODO: Set up Sampled.
1769 //
1770 // From Spec
1771 //
1772 // 0 indicates this is only known at run time, not at compile time
1773 // 1 indicates will be used with sampler
1774 // 2 indicates will be used without a sampler (a storage image)
1775 uint32_t Sampled = 1;
1776 if (STy->getName().equals("opencl.image2d_wo_t") ||
1777 STy->getName().equals("opencl.image3d_wo_t")) {
1778 Sampled = 2;
1779 }
David Neto257c3892018-04-11 13:19:45 -04001780 Ops << MkNum(Sampled);
David Neto22f144c2017-06-12 14:26:21 -04001781
1782 // TODO: Set up Image Format.
David Neto257c3892018-04-11 13:19:45 -04001783 Ops << MkNum(spv::ImageFormatUnknown);
David Neto22f144c2017-06-12 14:26:21 -04001784
1785 SPIRVInstruction *Inst =
1786 new SPIRVInstruction(9, spv::OpTypeImage, nextID++, Ops);
1787 SPIRVInstList.push_back(Inst);
1788 break;
1789 }
1790 }
1791
1792 //
1793 // Generate OpTypeStruct
1794 //
1795 // Ops[0] ... Ops[n] = Member IDs
1796 SPIRVOperandList Ops;
1797
1798 for (auto *EleTy : STy->elements()) {
1799 uint32_t EleTyID = lookupType(EleTy);
1800
1801 // Check OpTypeRuntimeArray.
1802 if (isa<PointerType>(EleTy)) {
David Netoc6f3ab22018-04-06 18:02:31 -04001803 // TODO(dneto): Isn't this a straight lookup instead of a loop?
David Neto22f144c2017-06-12 14:26:21 -04001804 for (auto ArgGV : ArgGVMap) {
1805 Type *ArgTy = ArgGV.first->getType();
1806 if (ArgTy == EleTy) {
1807 assert(0 != OpRuntimeTyMap.count(EleTy));
1808 EleTyID = OpRuntimeTyMap[EleTy];
1809 }
1810 }
1811 }
1812
David Neto257c3892018-04-11 13:19:45 -04001813 Ops << MkId(EleTyID);
David Neto22f144c2017-06-12 14:26:21 -04001814 }
1815
1816 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1817 uint32_t STyID = nextID;
1818
1819 SPIRVInstruction *Inst =
1820 new SPIRVInstruction(WordCount, spv::OpTypeStruct, nextID++, Ops);
1821 SPIRVInstList.push_back(Inst);
1822
1823 // Generate OpMemberDecorate.
1824 auto DecoInsertPoint =
1825 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1826 [](SPIRVInstruction *Inst) -> bool {
1827 return Inst->getOpcode() != spv::OpDecorate &&
1828 Inst->getOpcode() != spv::OpMemberDecorate &&
1829 Inst->getOpcode() != spv::OpExtInstImport;
1830 });
1831
David Netoc463b372017-08-10 15:32:21 -04001832 const auto StructLayout = DL.getStructLayout(STy);
1833
David Neto22f144c2017-06-12 14:26:21 -04001834 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1835 MemberIdx++) {
1836 // Ops[0] = Structure Type ID
1837 // Ops[1] = Member Index(Literal Number)
1838 // Ops[2] = Decoration (Offset)
1839 // Ops[3] = Byte Offset (Literal Number)
1840 Ops.clear();
1841
David Neto257c3892018-04-11 13:19:45 -04001842 Ops << MkId(STyID) << MkNum(MemberIdx) << MkNum(spv::DecorationOffset);
David Neto22f144c2017-06-12 14:26:21 -04001843
David Netoc463b372017-08-10 15:32:21 -04001844 const auto ByteOffset =
1845 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto257c3892018-04-11 13:19:45 -04001846 Ops << MkNum(ByteOffset);
David Neto22f144c2017-06-12 14:26:21 -04001847
1848 SPIRVInstruction *DecoInst =
1849 new SPIRVInstruction(5, spv::OpMemberDecorate, 0 /* No id */, Ops);
1850 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001851 }
1852
1853 // Generate OpDecorate.
1854 for (auto ArgGV : ArgGVMap) {
1855 Type *ArgGVTy = ArgGV.second->getType();
1856 PointerType *PTy = cast<PointerType>(ArgGVTy);
1857 Type *ArgTy = PTy->getElementType();
1858
1859 // Struct type from argument is already distinguished with the other
1860 // struct types on llvm types. As a result, if current processing struct
1861 // type is same with argument type, we can generate OpDecorate with
1862 // Block or BufferBlock.
1863 if (ArgTy == STy) {
1864 // Ops[0] = Target ID
1865 // Ops[1] = Decoration (Block or BufferBlock)
1866 Ops.clear();
1867
David Neto6e392822017-08-04 14:06:10 -04001868 // Use Block decorations with StorageBuffer storage class.
David Neto257c3892018-04-11 13:19:45 -04001869 Ops << MkId(STyID) << MkNum(spv::DecorationBlock);
David Neto22f144c2017-06-12 14:26:21 -04001870
1871 SPIRVInstruction *DecoInst =
1872 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
1873 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1874 break;
1875 }
1876 }
1877 break;
1878 }
1879 case Type::IntegerTyID: {
1880 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1881
1882 if (BitWidth == 1) {
1883 SPIRVInstruction *Inst =
1884 new SPIRVInstruction(2, spv::OpTypeBool, nextID++, {});
1885 SPIRVInstList.push_back(Inst);
1886 } else {
1887 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001888 // No matter what LLVM type is requested first, always alias the
1889 // second one's SPIR-V type to be the same as the one we generated
1890 // first.
Neil Henning39672102017-09-29 14:33:13 +01001891 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001892 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001893 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001894 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001895 } else if (BitWidth == 32) {
1896 aliasToWidth = 8;
1897 }
1898 if (aliasToWidth) {
1899 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1900 auto where = TypeMap.find(otherType);
1901 if (where == TypeMap.end()) {
1902 // Go ahead and make it, but also map the other type to it.
1903 TypeMap[otherType] = nextID;
1904 } else {
1905 // Alias this SPIR-V type the existing type.
1906 TypeMap[Ty] = where->second;
1907 break;
1908 }
David Neto22f144c2017-06-12 14:26:21 -04001909 }
1910
David Neto257c3892018-04-11 13:19:45 -04001911 SPIRVOperandList Ops;
1912 Ops << MkNum(BitWidth) << MkNum(0 /* not signed */);
David Neto22f144c2017-06-12 14:26:21 -04001913
1914 SPIRVInstList.push_back(
1915 new SPIRVInstruction(4, spv::OpTypeInt, nextID++, Ops));
1916 }
1917 break;
1918 }
1919 case Type::HalfTyID:
1920 case Type::FloatTyID:
1921 case Type::DoubleTyID: {
1922 SPIRVOperand *WidthOp = new SPIRVOperand(
1923 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1924
1925 SPIRVInstList.push_back(
1926 new SPIRVInstruction(3, spv::OpTypeFloat, nextID++, WidthOp));
1927 break;
1928 }
1929 case Type::ArrayTyID: {
1930 LLVMContext &Context = Ty->getContext();
1931 ArrayType *ArrTy = cast<ArrayType>(Ty);
1932 //
1933 // Generate OpConstant and OpTypeArray.
1934 //
1935
1936 //
1937 // Generate OpConstant for array length.
1938 //
1939 // Ops[0] = Result Type ID
1940 // Ops[1] .. Ops[n] = Values LiteralNumber
1941 SPIRVOperandList Ops;
1942
1943 Type *LengthTy = Type::getInt32Ty(Context);
1944 uint32_t ResTyID = lookupType(LengthTy);
David Neto257c3892018-04-11 13:19:45 -04001945 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04001946
1947 uint64_t Length = ArrTy->getArrayNumElements();
1948 assert(Length < UINT32_MAX);
David Neto257c3892018-04-11 13:19:45 -04001949 Ops << MkNum(static_cast<uint32_t>(Length));
David Neto22f144c2017-06-12 14:26:21 -04001950
1951 // Add constant for length to constant list.
1952 Constant *CstLength = ConstantInt::get(LengthTy, Length);
1953 AllocatedVMap[CstLength] = nextID;
1954 VMap[CstLength] = nextID;
1955 uint32_t LengthID = nextID;
1956
1957 SPIRVInstruction *CstInst =
1958 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
1959 SPIRVInstList.push_back(CstInst);
1960
David Neto85082642018-03-24 06:55:20 -07001961 // Remember to generate ArrayStride later
1962 getTypesNeedingArrayStride().insert(Ty);
1963
David Neto22f144c2017-06-12 14:26:21 -04001964 //
1965 // Generate OpTypeArray.
1966 //
1967 // Ops[0] = Element Type ID
1968 // Ops[1] = Array Length Constant ID
1969 Ops.clear();
1970
1971 uint32_t EleTyID = lookupType(ArrTy->getElementType());
David Neto257c3892018-04-11 13:19:45 -04001972 Ops << MkId(EleTyID) << MkId(LengthID);
David Neto22f144c2017-06-12 14:26:21 -04001973
1974 // Update TypeMap with nextID.
1975 TypeMap[Ty] = nextID;
1976
1977 SPIRVInstruction *ArrayInst =
1978 new SPIRVInstruction(4, spv::OpTypeArray, nextID++, Ops);
1979 SPIRVInstList.push_back(ArrayInst);
1980 break;
1981 }
1982 case Type::VectorTyID: {
1983 // <4 x i8> is changed to i32.
1984 LLVMContext &Context = Ty->getContext();
1985 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
1986 if (Ty->getVectorNumElements() == 4) {
1987 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
1988 break;
1989 } else {
1990 Ty->print(errs());
1991 llvm_unreachable("Support above i8 vector type");
1992 }
1993 }
1994
1995 // Ops[0] = Component Type ID
1996 // Ops[1] = Component Count (Literal Number)
David Neto257c3892018-04-11 13:19:45 -04001997 SPIRVOperandList Ops;
1998 Ops << MkId(lookupType(Ty->getVectorElementType()))
1999 << MkNum(Ty->getVectorNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002000
David Netoc6f3ab22018-04-06 18:02:31 -04002001 SPIRVInstruction* inst = new SPIRVInstruction(4, spv::OpTypeVector, nextID++, Ops);
2002 SPIRVInstList.push_back(inst);
David Neto22f144c2017-06-12 14:26:21 -04002003 break;
2004 }
2005 case Type::VoidTyID: {
2006 SPIRVInstruction *Inst =
2007 new SPIRVInstruction(2, spv::OpTypeVoid, nextID++, {});
2008 SPIRVInstList.push_back(Inst);
2009 break;
2010 }
2011 case Type::FunctionTyID: {
2012 // Generate SPIRV instruction for function type.
2013 FunctionType *FTy = cast<FunctionType>(Ty);
2014
2015 // Ops[0] = Return Type ID
2016 // Ops[1] ... Ops[n] = Parameter Type IDs
2017 SPIRVOperandList Ops;
2018
2019 // Find SPIRV instruction for return type
David Netoc6f3ab22018-04-06 18:02:31 -04002020 Ops << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002021
2022 // Find SPIRV instructions for parameter types
2023 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
2024 // Find SPIRV instruction for parameter type.
2025 auto ParamTy = FTy->getParamType(k);
2026 if (ParamTy->isPointerTy()) {
2027 auto PointeeTy = ParamTy->getPointerElementType();
2028 if (PointeeTy->isStructTy() &&
2029 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
2030 ParamTy = PointeeTy;
2031 }
2032 }
2033
David Netoc6f3ab22018-04-06 18:02:31 -04002034 Ops << MkId(lookupType(ParamTy));
David Neto22f144c2017-06-12 14:26:21 -04002035 }
2036
2037 // Return type id is included in operand list.
2038 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
2039
2040 SPIRVInstruction *Inst =
2041 new SPIRVInstruction(WordCount, spv::OpTypeFunction, nextID++, Ops);
2042 SPIRVInstList.push_back(Inst);
2043 break;
2044 }
2045 }
2046 }
2047
2048 // Generate OpTypeSampledImage.
2049 TypeMapType &OpImageTypeMap = getImageTypeMap();
2050 for (auto &ImageType : OpImageTypeMap) {
2051 //
2052 // Generate OpTypeSampledImage.
2053 //
2054 // Ops[0] = Image Type ID
2055 //
2056 SPIRVOperandList Ops;
2057
2058 Type *ImgTy = ImageType.first;
David Netoc6f3ab22018-04-06 18:02:31 -04002059 Ops << MkId(TypeMap[ImgTy]);
David Neto22f144c2017-06-12 14:26:21 -04002060
2061 // Update OpImageTypeMap.
2062 ImageType.second = nextID;
2063
2064 SPIRVInstruction *Inst =
2065 new SPIRVInstruction(3, spv::OpTypeSampledImage, nextID++, Ops);
2066 SPIRVInstList.push_back(Inst);
2067 }
David Netoc6f3ab22018-04-06 18:02:31 -04002068
2069 // Generate types for pointer-to-local arguments.
2070 for (auto* arg : LocalArgs) {
2071
2072 LocalArgInfo& arg_info = LocalArgMap[arg];
2073
2074 // Generate the spec constant.
2075 SPIRVOperandList Ops;
2076 Ops << MkId(lookupType(Type::getInt32Ty(Context))) << MkNum(1);
2077 SPIRVInstList.push_back(new SPIRVInstruction(4, spv::OpSpecConstant,
2078 arg_info.array_size_id, Ops));
2079
2080
2081 // Generate the array type.
2082 Ops.clear();
2083 // The element type must have been created.
2084 uint32_t elem_ty_id = lookupType(arg_info.elem_type);
2085 assert(elem_ty_id);
2086 Ops << MkId(elem_ty_id) << MkId(arg_info.array_size_id);
2087
2088 SPIRVInstList.push_back(
2089 new SPIRVInstruction(4, spv::OpTypeArray, arg_info.array_type_id, Ops));
2090
2091 Ops.clear();
2092 Ops << MkNum(spv::StorageClassWorkgroup) << MkId(arg_info.array_type_id);
2093 SPIRVInstList.push_back(
2094 new SPIRVInstruction(4, spv::OpTypePointer, arg_info.ptr_array_type_id, Ops));
2095 }
David Neto22f144c2017-06-12 14:26:21 -04002096}
2097
2098void SPIRVProducerPass::GenerateSPIRVConstants() {
2099 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2100 ValueMapType &VMap = getValueMap();
2101 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2102 ValueList &CstList = getConstantList();
David Neto482550a2018-03-24 05:21:07 -07002103 const bool hack_undef = clspv::Option::HackUndef();
David Neto22f144c2017-06-12 14:26:21 -04002104
2105 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002106 // UniqueVector ids are 1-based.
2107 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002108
2109 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002110 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002111 continue;
2112 }
2113
David Netofb9a7972017-08-25 17:08:24 -04002114 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002115 VMap[Cst] = nextID;
2116
2117 //
2118 // Generate OpConstant.
2119 //
2120
2121 // Ops[0] = Result Type ID
2122 // Ops[1] .. Ops[n] = Values LiteralNumber
2123 SPIRVOperandList Ops;
2124
David Neto257c3892018-04-11 13:19:45 -04002125 Ops << MkId(lookupType(Cst->getType()));
David Neto22f144c2017-06-12 14:26:21 -04002126
2127 std::vector<uint32_t> LiteralNum;
2128 uint16_t WordCount = 0;
2129 spv::Op Opcode = spv::OpNop;
2130
2131 if (isa<UndefValue>(Cst)) {
2132 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002133 Opcode = spv::OpUndef;
2134 if (hack_undef) {
2135 Type *type = Cst->getType();
2136 if (type->isFPOrFPVectorTy() || type->isIntOrIntVectorTy()) {
2137 Opcode = spv::OpConstantNull;
2138 }
2139 }
David Neto22f144c2017-06-12 14:26:21 -04002140 WordCount = 3;
2141 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2142 unsigned BitWidth = CI->getBitWidth();
2143 if (BitWidth == 1) {
2144 // If the bitwidth of constant is 1, generate OpConstantTrue or
2145 // OpConstantFalse.
2146 if (CI->getZExtValue()) {
2147 // Ops[0] = Result Type ID
2148 Opcode = spv::OpConstantTrue;
2149 } else {
2150 // Ops[0] = Result Type ID
2151 Opcode = spv::OpConstantFalse;
2152 }
2153 WordCount = 3;
2154 } else {
2155 auto V = CI->getZExtValue();
2156 LiteralNum.push_back(V & 0xFFFFFFFF);
2157
2158 if (BitWidth > 32) {
2159 LiteralNum.push_back(V >> 32);
2160 }
2161
2162 Opcode = spv::OpConstant;
2163 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2164
David Neto257c3892018-04-11 13:19:45 -04002165 Ops << MkInteger(LiteralNum);
2166
2167 if (BitWidth == 32 && V == 0) {
2168 constant_i32_zero_id_ = nextID;
2169 }
David Neto22f144c2017-06-12 14:26:21 -04002170 }
2171 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2172 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2173 Type *CFPTy = CFP->getType();
2174 if (CFPTy->isFloatTy()) {
2175 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2176 } else {
2177 CFPTy->print(errs());
2178 llvm_unreachable("Implement this ConstantFP Type");
2179 }
2180
2181 Opcode = spv::OpConstant;
2182 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2183
David Neto257c3892018-04-11 13:19:45 -04002184 Ops << MkFloat(LiteralNum);
David Neto22f144c2017-06-12 14:26:21 -04002185 } else if (isa<ConstantDataSequential>(Cst) &&
2186 cast<ConstantDataSequential>(Cst)->isString()) {
2187 Cst->print(errs());
2188 llvm_unreachable("Implement this Constant");
2189
2190 } else if (const ConstantDataSequential *CDS =
2191 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002192 // Let's convert <4 x i8> constant to int constant specially.
2193 // This case occurs when all the values are specified as constant
2194 // ints.
2195 Type *CstTy = Cst->getType();
2196 if (is4xi8vec(CstTy)) {
2197 LLVMContext &Context = CstTy->getContext();
2198
2199 //
2200 // Generate OpConstant with OpTypeInt 32 0.
2201 //
Neil Henning39672102017-09-29 14:33:13 +01002202 uint32_t IntValue = 0;
2203 for (unsigned k = 0; k < 4; k++) {
2204 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002205 IntValue = (IntValue << 8) | (Val & 0xffu);
2206 }
2207
2208 Type *i32 = Type::getInt32Ty(Context);
2209 Constant *CstInt = ConstantInt::get(i32, IntValue);
2210 // If this constant is already registered on VMap, use it.
2211 if (VMap.count(CstInt)) {
2212 uint32_t CstID = VMap[CstInt];
2213 VMap[Cst] = CstID;
2214 continue;
2215 }
2216
David Neto257c3892018-04-11 13:19:45 -04002217 Ops << MkNum(IntValue);
David Neto49351ac2017-08-26 17:32:20 -04002218
2219 SPIRVInstruction *CstInst =
2220 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2221 SPIRVInstList.push_back(CstInst);
2222
2223 continue;
2224 }
2225
2226 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002227 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2228 Constant *EleCst = CDS->getElementAsConstant(k);
2229 uint32_t EleCstID = VMap[EleCst];
David Neto257c3892018-04-11 13:19:45 -04002230 Ops << MkId(EleCstID);
David Neto22f144c2017-06-12 14:26:21 -04002231 }
2232
2233 Opcode = spv::OpConstantComposite;
2234 WordCount = static_cast<uint16_t>(3 + CDS->getNumElements());
2235 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2236 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002237 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002238 Type *CstTy = Cst->getType();
2239 if (is4xi8vec(CstTy)) {
2240 LLVMContext &Context = CstTy->getContext();
2241
2242 //
2243 // Generate OpConstant with OpTypeInt 32 0.
2244 //
Neil Henning39672102017-09-29 14:33:13 +01002245 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002246 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2247 I != E; ++I) {
2248 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002249 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002250 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2251 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002252 }
David Neto49351ac2017-08-26 17:32:20 -04002253 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002254 }
2255
David Neto49351ac2017-08-26 17:32:20 -04002256 Type *i32 = Type::getInt32Ty(Context);
2257 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002258 // If this constant is already registered on VMap, use it.
2259 if (VMap.count(CstInt)) {
2260 uint32_t CstID = VMap[CstInt];
2261 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002262 continue;
David Neto22f144c2017-06-12 14:26:21 -04002263 }
2264
David Neto257c3892018-04-11 13:19:45 -04002265 Ops << MkNum(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002266
2267 SPIRVInstruction *CstInst =
2268 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2269 SPIRVInstList.push_back(CstInst);
2270
David Neto19a1bad2017-08-25 15:01:41 -04002271 continue;
David Neto22f144c2017-06-12 14:26:21 -04002272 }
2273
2274 // We use a constant composite in SPIR-V for our constant aggregate in
2275 // LLVM.
2276 Opcode = spv::OpConstantComposite;
2277 WordCount = static_cast<uint16_t>(3 + CA->getNumOperands());
2278
2279 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2280 // Look up the ID of the element of this aggregate (which we will
2281 // previously have created a constant for).
2282 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2283
2284 // And add an operand to the composite we are constructing
David Neto257c3892018-04-11 13:19:45 -04002285 Ops << MkId(ElementConstantID);
David Neto22f144c2017-06-12 14:26:21 -04002286 }
2287 } else if (Cst->isNullValue()) {
2288 Opcode = spv::OpConstantNull;
2289 WordCount = 3;
2290 } else {
2291 Cst->print(errs());
2292 llvm_unreachable("Unsupported Constant???");
2293 }
2294
2295 SPIRVInstruction *CstInst =
2296 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
2297 SPIRVInstList.push_back(CstInst);
2298 }
2299}
2300
2301void SPIRVProducerPass::GenerateSamplers(Module &M) {
2302 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2303 ValueMapType &VMap = getValueMap();
2304
2305 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
2306
2307 unsigned BindingIdx = 0;
2308
2309 // Generate the sampler map.
2310 for (auto SamplerLiteral : getSamplerMap()) {
2311 // Generate OpVariable.
2312 //
2313 // GIDOps[0] : Result Type ID
2314 // GIDOps[1] : Storage Class
2315 SPIRVOperandList Ops;
2316
David Neto257c3892018-04-11 13:19:45 -04002317 Ops << MkId(lookupType(SamplerTy))
2318 << MkNum(spv::StorageClassUniformConstant);
David Neto22f144c2017-06-12 14:26:21 -04002319
2320 SPIRVInstruction *Inst = new SPIRVInstruction(
2321 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID, Ops);
2322 SPIRVInstList.push_back(Inst);
2323
David Neto44795152017-07-13 15:45:28 -04002324 SamplerLiteralToIDMap[SamplerLiteral.first] = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002325
2326 // Find Insert Point for OpDecorate.
2327 auto DecoInsertPoint =
2328 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2329 [](SPIRVInstruction *Inst) -> bool {
2330 return Inst->getOpcode() != spv::OpDecorate &&
2331 Inst->getOpcode() != spv::OpMemberDecorate &&
2332 Inst->getOpcode() != spv::OpExtInstImport;
2333 });
2334
2335 // Ops[0] = Target ID
2336 // Ops[1] = Decoration (DescriptorSet)
2337 // Ops[2] = LiteralNumber according to Decoration
2338 Ops.clear();
2339
David Neto257c3892018-04-11 13:19:45 -04002340 uint32_t ArgID = SamplerLiteralToIDMap[SamplerLiteral.first];
2341 Ops << MkId(ArgID) << MkNum(spv::DecorationDescriptorSet)
2342 << MkNum(NextDescriptorSetIndex);
David Neto22f144c2017-06-12 14:26:21 -04002343
David Neto44795152017-07-13 15:45:28 -04002344 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
David Neto257c3892018-04-11 13:19:45 -04002345 << SamplerLiteral.second << "\",descriptorSet,"
2346 << NextDescriptorSetIndex << ",binding," << BindingIdx
2347 << "\n";
David Neto22f144c2017-06-12 14:26:21 -04002348
2349 SPIRVInstruction *DescDecoInst =
2350 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2351 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2352
2353 // Ops[0] = Target ID
2354 // Ops[1] = Decoration (Binding)
2355 // Ops[2] = LiteralNumber according to Decoration
2356 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002357 Ops << MkId(ArgID) << MkNum(spv::DecorationBinding) << MkNum(BindingIdx);
2358 BindingIdx++;
David Neto22f144c2017-06-12 14:26:21 -04002359
2360 SPIRVInstruction *BindDecoInst =
2361 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2362 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2363 }
David Neto85082642018-03-24 06:55:20 -07002364 if (BindingIdx > 0) {
2365 // We generated something.
2366 ++NextDescriptorSetIndex;
2367 }
David Neto22f144c2017-06-12 14:26:21 -04002368
2369 const char *TranslateSamplerFunctionName = "__translate_sampler_initializer";
2370
2371 auto SamplerFunction = M.getFunction(TranslateSamplerFunctionName);
2372
2373 // If there are no uses of the sampler function, no work to do!
2374 if (!SamplerFunction) {
2375 return;
2376 }
2377
2378 // Iterate through the users of the sampler function.
2379 for (auto User : SamplerFunction->users()) {
2380 if (auto CI = dyn_cast<CallInst>(User)) {
2381 // Get the literal used to initialize the sampler.
2382 auto Constant = dyn_cast<ConstantInt>(CI->getArgOperand(0));
2383
2384 if (!Constant) {
2385 CI->getArgOperand(0)->print(errs());
2386 llvm_unreachable("Argument of sampler initializer was non-constant!");
2387 }
2388
2389 auto SamplerLiteral = static_cast<unsigned>(Constant->getZExtValue());
2390
2391 if (0 == SamplerLiteralToIDMap.count(SamplerLiteral)) {
2392 Constant->print(errs());
2393 llvm_unreachable("Sampler literal was not found in sampler map!");
2394 }
2395
2396 // Calls to the sampler literal function to initialize a sampler are
2397 // re-routed to the global variables declared for the sampler.
2398 VMap[CI] = SamplerLiteralToIDMap[SamplerLiteral];
2399 }
2400 }
2401}
2402
2403void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
2404 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2405 ValueMapType &VMap = getValueMap();
2406 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
David Neto85082642018-03-24 06:55:20 -07002407 const DataLayout &DL = GV.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002408
2409 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2410 Type *Ty = GV.getType();
2411 PointerType *PTy = cast<PointerType>(Ty);
2412
2413 uint32_t InitializerID = 0;
2414
2415 // Workgroup size is handled differently (it goes into a constant)
2416 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2417 std::vector<bool> HasMDVec;
2418 uint32_t PrevXDimCst = 0xFFFFFFFF;
2419 uint32_t PrevYDimCst = 0xFFFFFFFF;
2420 uint32_t PrevZDimCst = 0xFFFFFFFF;
2421 for (Function &Func : *GV.getParent()) {
2422 if (Func.isDeclaration()) {
2423 continue;
2424 }
2425
2426 // We only need to check kernels.
2427 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2428 continue;
2429 }
2430
2431 if (const MDNode *MD =
2432 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2433 uint32_t CurXDimCst = static_cast<uint32_t>(
2434 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2435 uint32_t CurYDimCst = static_cast<uint32_t>(
2436 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2437 uint32_t CurZDimCst = static_cast<uint32_t>(
2438 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2439
2440 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2441 PrevZDimCst == 0xFFFFFFFF) {
2442 PrevXDimCst = CurXDimCst;
2443 PrevYDimCst = CurYDimCst;
2444 PrevZDimCst = CurZDimCst;
2445 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2446 CurZDimCst != PrevZDimCst) {
2447 llvm_unreachable(
2448 "reqd_work_group_size must be the same across all kernels");
2449 } else {
2450 continue;
2451 }
2452
2453 //
2454 // Generate OpConstantComposite.
2455 //
2456 // Ops[0] : Result Type ID
2457 // Ops[1] : Constant size for x dimension.
2458 // Ops[2] : Constant size for y dimension.
2459 // Ops[3] : Constant size for z dimension.
2460 SPIRVOperandList Ops;
2461
2462 uint32_t XDimCstID =
2463 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2464 uint32_t YDimCstID =
2465 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2466 uint32_t ZDimCstID =
2467 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2468
2469 InitializerID = nextID;
2470
David Neto257c3892018-04-11 13:19:45 -04002471 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2472 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002473
2474 SPIRVInstruction *Inst =
2475 new SPIRVInstruction(6, spv::OpConstantComposite, nextID++, Ops);
2476 SPIRVInstList.push_back(Inst);
2477
2478 HasMDVec.push_back(true);
2479 } else {
2480 HasMDVec.push_back(false);
2481 }
2482 }
2483
2484 // Check all kernels have same definitions for work_group_size.
2485 bool HasMD = false;
2486 if (!HasMDVec.empty()) {
2487 HasMD = HasMDVec[0];
2488 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2489 if (HasMD != HasMDVec[i]) {
2490 llvm_unreachable(
2491 "Kernels should have consistent work group size definition");
2492 }
2493 }
2494 }
2495
2496 // If all kernels do not have metadata for reqd_work_group_size, generate
2497 // OpSpecConstants for x/y/z dimension.
2498 if (!HasMD) {
2499 //
2500 // Generate OpSpecConstants for x/y/z dimension.
2501 //
2502 // Ops[0] : Result Type ID
2503 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2504 uint32_t XDimCstID = 0;
2505 uint32_t YDimCstID = 0;
2506 uint32_t ZDimCstID = 0;
2507
David Neto22f144c2017-06-12 14:26:21 -04002508 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04002509 uint32_t result_type_id =
2510 lookupType(Ty->getPointerElementType()->getSequentialElementType());
David Neto22f144c2017-06-12 14:26:21 -04002511
David Neto257c3892018-04-11 13:19:45 -04002512 // X Dimension
2513 Ops << MkId(result_type_id) << MkNum(1);
2514 XDimCstID = nextID++;
2515 SPIRVInstList.push_back(
2516 new SPIRVInstruction(4, spv::OpSpecConstant, XDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002517
2518 // Y Dimension
2519 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002520 Ops << MkId(result_type_id) << MkNum(1);
2521 YDimCstID = nextID++;
2522 SPIRVInstList.push_back(
2523 new SPIRVInstruction(4, spv::OpSpecConstant, YDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002524
2525 // Z Dimension
2526 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002527 Ops << MkId(result_type_id) << MkNum(1);
2528 ZDimCstID = nextID++;
2529 SPIRVInstList.push_back(
2530 new SPIRVInstruction(4, spv::OpSpecConstant, ZDimCstID, Ops));
David Neto22f144c2017-06-12 14:26:21 -04002531
David Neto22f144c2017-06-12 14:26:21 -04002532
David Neto257c3892018-04-11 13:19:45 -04002533 BuiltinDimVec.push_back(XDimCstID);
2534 BuiltinDimVec.push_back(YDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002535 BuiltinDimVec.push_back(ZDimCstID);
2536
David Neto22f144c2017-06-12 14:26:21 -04002537
2538 //
2539 // Generate OpSpecConstantComposite.
2540 //
2541 // Ops[0] : Result Type ID
2542 // Ops[1] : Constant size for x dimension.
2543 // Ops[2] : Constant size for y dimension.
2544 // Ops[3] : Constant size for z dimension.
2545 InitializerID = nextID;
2546
2547 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002548 Ops << MkId(lookupType(Ty->getPointerElementType())) << MkId(XDimCstID)
2549 << MkId(YDimCstID) << MkId(ZDimCstID);
David Neto22f144c2017-06-12 14:26:21 -04002550
2551 SPIRVInstruction *Inst =
2552 new SPIRVInstruction(6, spv::OpSpecConstantComposite, nextID++, Ops);
2553 SPIRVInstList.push_back(Inst);
2554 }
2555 }
2556
David Neto22f144c2017-06-12 14:26:21 -04002557 VMap[&GV] = nextID;
2558
2559 //
2560 // Generate OpVariable.
2561 //
2562 // GIDOps[0] : Result Type ID
2563 // GIDOps[1] : Storage Class
2564 SPIRVOperandList Ops;
2565
David Neto85082642018-03-24 06:55:20 -07002566 const auto AS = PTy->getAddressSpace();
David Netoc6f3ab22018-04-06 18:02:31 -04002567 Ops << MkId(lookupType(Ty)) << MkNum(GetStorageClass(AS));
David Neto22f144c2017-06-12 14:26:21 -04002568
David Neto85082642018-03-24 06:55:20 -07002569 if (GV.hasInitializer()) {
2570 InitializerID = VMap[GV.getInitializer()];
David Neto22f144c2017-06-12 14:26:21 -04002571 }
2572
David Neto85082642018-03-24 06:55:20 -07002573 const bool module_scope_constant_external_init =
2574 (0 != InitializerID) && (AS == AddressSpace::Constant) &&
2575 clspv::Option::ModuleConstantsInStorageBuffer();
2576
2577 if (0 != InitializerID) {
2578 if (!module_scope_constant_external_init) {
2579 // Emit the ID of the intiializer as part of the variable definition.
David Netoc6f3ab22018-04-06 18:02:31 -04002580 Ops << MkId(InitializerID);
David Neto85082642018-03-24 06:55:20 -07002581 }
2582 }
2583 const uint32_t var_id = nextID++;
2584
David Neto22f144c2017-06-12 14:26:21 -04002585 SPIRVInstruction *Inst = new SPIRVInstruction(
David Neto85082642018-03-24 06:55:20 -07002586 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, var_id, Ops);
David Neto22f144c2017-06-12 14:26:21 -04002587 SPIRVInstList.push_back(Inst);
2588
2589 // If we have a builtin.
2590 if (spv::BuiltInMax != BuiltinType) {
2591 // Find Insert Point for OpDecorate.
2592 auto DecoInsertPoint =
2593 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2594 [](SPIRVInstruction *Inst) -> bool {
2595 return Inst->getOpcode() != spv::OpDecorate &&
2596 Inst->getOpcode() != spv::OpMemberDecorate &&
2597 Inst->getOpcode() != spv::OpExtInstImport;
2598 });
2599 //
2600 // Generate OpDecorate.
2601 //
2602 // DOps[0] = Target ID
2603 // DOps[1] = Decoration (Builtin)
2604 // DOps[2] = BuiltIn ID
2605 uint32_t ResultID;
2606
2607 // WorkgroupSize is different, we decorate the constant composite that has
2608 // its value, rather than the variable that we use to access the value.
2609 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2610 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002611 // Save both the value and variable IDs for later.
2612 WorkgroupSizeValueID = InitializerID;
2613 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002614 } else {
2615 ResultID = VMap[&GV];
2616 }
2617
2618 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002619 DOps << MkId(ResultID) << MkNum(spv::DecorationBuiltIn)
2620 << MkNum(BuiltinType);
David Neto22f144c2017-06-12 14:26:21 -04002621
2622 SPIRVInstruction *DescDecoInst =
2623 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps);
2624 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto85082642018-03-24 06:55:20 -07002625 } else if (module_scope_constant_external_init) {
2626 // This module scope constant is initialized from a storage buffer with data
2627 // provided by the host at binding 0 of the next descriptor set.
2628 const uint32_t descriptor_set = NextDescriptorSetIndex++;
2629
2630 // Emit the intiialier to the descriptor map file.
2631 // Use "kind,buffer" to indicate storage buffer. We might want to expand
2632 // that later to other types, like uniform buffer.
2633 descriptorMapOut << "constant,descriptorSet," << descriptor_set
2634 << ",binding,0,kind,buffer,hexbytes,";
2635 clspv::ConstantEmitter(DL, descriptorMapOut).Emit(GV.getInitializer());
2636 descriptorMapOut << "\n";
2637
2638 // Find Insert Point for OpDecorate.
2639 auto DecoInsertPoint =
2640 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2641 [](SPIRVInstruction *Inst) -> bool {
2642 return Inst->getOpcode() != spv::OpDecorate &&
2643 Inst->getOpcode() != spv::OpMemberDecorate &&
2644 Inst->getOpcode() != spv::OpExtInstImport;
2645 });
2646
David Neto257c3892018-04-11 13:19:45 -04002647 // OpDecorate %var Binding <binding>
David Neto85082642018-03-24 06:55:20 -07002648 SPIRVOperandList DOps;
David Neto257c3892018-04-11 13:19:45 -04002649 DOps << MkId(var_id) << MkNum(spv::DecorationBinding) << MkNum(0);
2650 DecoInsertPoint = SPIRVInstList.insert(
2651 DecoInsertPoint,
David Neto85082642018-03-24 06:55:20 -07002652 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps));
2653
2654 // OpDecorate %var DescriptorSet <descriptor_set>
2655 DOps.clear();
David Neto257c3892018-04-11 13:19:45 -04002656 DOps << MkId(var_id) << MkNum(spv::DecorationDescriptorSet)
2657 << MkNum(descriptor_set);
David Netoc6f3ab22018-04-06 18:02:31 -04002658 SPIRVInstList.insert(DecoInsertPoint,
David Neto85082642018-03-24 06:55:20 -07002659 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps));
David Neto22f144c2017-06-12 14:26:21 -04002660 }
2661}
2662
David Netoc6f3ab22018-04-06 18:02:31 -04002663void SPIRVProducerPass::GenerateWorkgroupVars() {
2664 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2665 for (auto* arg : LocalArgs) {
2666 const auto& info = LocalArgMap[arg];
2667
2668 // Generate OpVariable.
2669 //
2670 // GIDOps[0] : Result Type ID
2671 // GIDOps[1] : Storage Class
2672 SPIRVOperandList Ops;
2673 Ops << MkId(info.ptr_array_type_id) << MkNum(spv::StorageClassWorkgroup);
2674
2675 SPIRVInstList.push_back(
2676 new SPIRVInstruction(4, spv::OpVariable, info.variable_id, Ops));
2677 }
2678}
2679
David Neto22f144c2017-06-12 14:26:21 -04002680void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
David Netoc6f3ab22018-04-06 18:02:31 -04002681 const DataLayout &DL = F.getParent()->getDataLayout();
David Neto22f144c2017-06-12 14:26:21 -04002682 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2683 ValueMapType &VMap = getValueMap();
2684 EntryPointVecType &EntryPoints = getEntryPointVec();
2685 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
2686 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
2687 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2688 auto &GlobalConstArgSet = getGlobalConstArgSet();
2689
2690 FunctionType *FTy = F.getFunctionType();
2691
2692 //
2693 // Generate OpVariable and OpDecorate for kernel function with arguments.
2694 //
2695 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2696
2697 // Find Insert Point for OpDecorate.
2698 auto DecoInsertPoint =
2699 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2700 [](SPIRVInstruction *Inst) -> bool {
2701 return Inst->getOpcode() != spv::OpDecorate &&
2702 Inst->getOpcode() != spv::OpMemberDecorate &&
2703 Inst->getOpcode() != spv::OpExtInstImport;
2704 });
2705
David Neto85082642018-03-24 06:55:20 -07002706 const uint32_t DescriptorSetIdx = NextDescriptorSetIndex;
David Neto482550a2018-03-24 05:21:07 -07002707 if (clspv::Option::DistinctKernelDescriptorSets()) {
David Neto85082642018-03-24 06:55:20 -07002708 ++NextDescriptorSetIndex;
David Neto22f144c2017-06-12 14:26:21 -04002709 }
2710
David Netoe439d702018-03-23 13:14:08 -07002711 auto remap_arg_kind = [](StringRef argKind) {
David Neto482550a2018-03-24 05:21:07 -07002712 return clspv::Option::PodArgsInUniformBuffer() && argKind.equals("pod")
2713 ? "pod_ubo"
2714 : argKind;
David Netoe439d702018-03-23 13:14:08 -07002715 };
2716
David Neto156783e2017-07-05 15:39:41 -04002717 const auto *ArgMap = F.getMetadata("kernel_arg_map");
2718 // Emit descriptor map entries, if there was explicit metadata
2719 // attached.
2720 if (ArgMap) {
David Netoc6f3ab22018-04-06 18:02:31 -04002721 // The binding number is the new argument index minus the number
2722 // pointer-to-local arguments. Do this adjustment here rather than
2723 // adding yet another data member to the metadata for each argument.
2724 int num_ptr_local = 0;
2725
David Neto156783e2017-07-05 15:39:41 -04002726 for (const auto &arg : ArgMap->operands()) {
2727 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
David Netoc6f3ab22018-04-06 18:02:31 -04002728 assert(arg_node->getNumOperands() == 6);
David Neto156783e2017-07-05 15:39:41 -04002729 const auto name =
2730 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2731 const auto old_index =
2732 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2733 const auto new_index =
2734 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2735 const auto offset =
2736 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
David Netoc6f3ab22018-04-06 18:02:31 -04002737 const auto argKind = remap_arg_kind(
2738 dyn_cast<MDString>(arg_node->getOperand(4))->getString());
2739 const auto spec_id =
2740 dyn_extract<ConstantInt>(arg_node->getOperand(5))->getSExtValue();
2741 if (spec_id > 0) {
2742 num_ptr_local++;
2743 FunctionType *fTy =
2744 cast<FunctionType>(F.getType()->getPointerElementType());
2745 descriptorMapOut
2746 << "kernel," << F.getName() << ",arg," << name << ",argOrdinal,"
2747 << old_index << ",argKind," << argKind << ",arrayElemSize,"
2748 << DL.getTypeAllocSize(
2749 fTy->getParamType(new_index)->getPointerElementType())
2750 << ",arrayNumElemSpecId," << spec_id << "\n";
2751 } else {
2752 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2753 << ",argOrdinal," << old_index << ",descriptorSet,"
2754 << DescriptorSetIdx << ",binding,"
2755 << (new_index - num_ptr_local) << ",offset,"
2756 << offset << ",argKind," << argKind << "\n";
2757 }
David Neto156783e2017-07-05 15:39:41 -04002758 }
2759 }
2760
David Neto22f144c2017-06-12 14:26:21 -04002761 uint32_t BindingIdx = 0;
David Netoc6f3ab22018-04-06 18:02:31 -04002762 uint32_t arg_index = 0;
David Neto22f144c2017-06-12 14:26:21 -04002763 for (auto &Arg : F.args()) {
David Netoc6f3ab22018-04-06 18:02:31 -04002764 // Always use a binding, unless it's pointer-to-local.
2765 const bool uses_binding = !IsLocalPtr(Arg.getType());
David Neto22f144c2017-06-12 14:26:21 -04002766
David Neto156783e2017-07-05 15:39:41 -04002767 // Emit a descriptor map entry for this arg, in case there was no explicit
2768 // kernel arg mapping metadata.
David Netoc6f3ab22018-04-06 18:02:31 -04002769 auto argKind = remap_arg_kind(clspv::GetArgKindForType(Arg.getType()));
David Neto156783e2017-07-05 15:39:41 -04002770 if (!ArgMap) {
David Netoc6f3ab22018-04-06 18:02:31 -04002771 if (uses_binding) {
2772 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2773 << Arg.getName() << ",argOrdinal," << arg_index
2774 << ",descriptorSet," << DescriptorSetIdx
2775 << ",binding," << BindingIdx << ",offset,0,argKind,"
2776 << argKind << "\n";
2777 } else {
2778 descriptorMapOut << "kernel," << F.getName() << ",arg,"
2779 << Arg.getName() << ",argOrdinal," << arg_index
2780 << ",argKind," << argKind << ",arrayElemSize,"
2781 << DL.getTypeAllocSize(
2782 Arg.getType()->getPointerElementType())
2783 << ",arrayNumElemSpecId," << ArgSpecIdMap[&Arg]
2784 << "\n";
2785 }
David Netoc2c368d2017-06-30 16:50:17 -04002786 }
2787
David Netoc6f3ab22018-04-06 18:02:31 -04002788 if (uses_binding) {
2789 Value *NewGV = ArgGVMap[&Arg];
2790 VMap[&Arg] = VMap[NewGV];
2791 ArgGVIDMap[&Arg] = VMap[&Arg];
David Neto26aaf622017-10-23 18:11:53 -04002792
David Netoc6f3ab22018-04-06 18:02:31 -04002793 if (0 == GVarWithEmittedBindingInfo.count(NewGV)) {
2794 // Generate a new global variable for this argument.
2795 GVarWithEmittedBindingInfo.insert(NewGV);
David Neto22f144c2017-06-12 14:26:21 -04002796
David Netoc6f3ab22018-04-06 18:02:31 -04002797 SPIRVOperandList Ops;
2798 SPIRVOperand *ArgIDOp = nullptr;
David Neto257c3892018-04-11 13:19:45 -04002799 uint32_t ArgID = 0;
David Neto22f144c2017-06-12 14:26:21 -04002800
David Netoc6f3ab22018-04-06 18:02:31 -04002801 if (uses_binding) {
2802 // Ops[0] = Target ID
2803 // Ops[1] = Decoration (DescriptorSet)
2804 // Ops[2] = LiteralNumber according to Decoration
David Neto22f144c2017-06-12 14:26:21 -04002805
David Neto257c3892018-04-11 13:19:45 -04002806 ArgID = VMap[&Arg];
2807 Ops << MkId(ArgID) << MkNum(spv::DecorationDescriptorSet)
2808 << MkNum(DescriptorSetIdx);
David Neto22f144c2017-06-12 14:26:21 -04002809
David Netoc6f3ab22018-04-06 18:02:31 -04002810 SPIRVInstruction *DescDecoInst =
2811 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2812 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
David Neto22f144c2017-06-12 14:26:21 -04002813
David Netoc6f3ab22018-04-06 18:02:31 -04002814 // Ops[0] = Target ID
2815 // Ops[1] = Decoration (Binding)
2816 // Ops[2] = LiteralNumber according to Decoration
2817 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002818 Ops << MkId(ArgID) << MkNum(spv::DecorationBinding)
2819 << MkNum(BindingIdx);
David Netoc6f3ab22018-04-06 18:02:31 -04002820
2821 SPIRVInstruction *BindDecoInst =
2822 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2823 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2824 }
2825
2826 // Handle image type argument.
2827 bool HasReadOnlyImageType = false;
2828 bool HasWriteOnlyImageType = false;
2829 if (PointerType *ArgPTy = dyn_cast<PointerType>(Arg.getType())) {
2830 if (StructType *STy =
2831 dyn_cast<StructType>(ArgPTy->getElementType())) {
2832 if (STy->isOpaque()) {
2833 if (STy->getName().equals("opencl.image2d_ro_t") ||
2834 STy->getName().equals("opencl.image3d_ro_t")) {
2835 HasReadOnlyImageType = true;
2836 } else if (STy->getName().equals("opencl.image2d_wo_t") ||
2837 STy->getName().equals("opencl.image3d_wo_t")) {
2838 HasWriteOnlyImageType = true;
2839 }
2840 }
David Neto22f144c2017-06-12 14:26:21 -04002841 }
2842 }
David Netoc6f3ab22018-04-06 18:02:31 -04002843
2844 if (HasReadOnlyImageType || HasWriteOnlyImageType) {
2845 // Ops[0] = Target ID
2846 // Ops[1] = Decoration (NonReadable or NonWritable)
2847 Ops.clear();
2848
David Neto257c3892018-04-11 13:19:45 -04002849 Ops << MkId(VMap[&Arg]);
David Netoc6f3ab22018-04-06 18:02:31 -04002850
David Neto257c3892018-04-11 13:19:45 -04002851 // In OpenCL 1.2 an image is either read-only or write-only, but
2852 // never both.
2853 Ops << MkNum(HasReadOnlyImageType ? spv::DecorationNonWritable
2854 : spv::DecorationNonReadable);
David Netoc6f3ab22018-04-06 18:02:31 -04002855
2856 auto *DescDecoInst =
2857 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2858 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2859 }
2860
2861 // Handle const address space.
2862 if (uses_binding && NewGV->getType()->getPointerAddressSpace() ==
2863 AddressSpace::Constant) {
2864 // Ops[0] = Target ID
2865 // Ops[1] = Decoration (NonWriteable)
2866 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04002867 assert(ArgID > 0);
2868 Ops << MkId(ArgID) << MkNum(spv::DecorationNonWritable);
David Netoc6f3ab22018-04-06 18:02:31 -04002869
2870 auto *BindDecoInst =
2871 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2872 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2873 }
David Neto22f144c2017-06-12 14:26:21 -04002874 }
David Netoc6f3ab22018-04-06 18:02:31 -04002875 BindingIdx++;
David Neto22f144c2017-06-12 14:26:21 -04002876 }
David Netoc6f3ab22018-04-06 18:02:31 -04002877 arg_index++;
David Neto22f144c2017-06-12 14:26:21 -04002878 }
2879 }
2880
2881 //
2882 // Generate OPFunction.
2883 //
2884
2885 // FOps[0] : Result Type ID
2886 // FOps[1] : Function Control
2887 // FOps[2] : Function Type ID
2888 SPIRVOperandList FOps;
2889
2890 // Find SPIRV instruction for return type.
David Neto257c3892018-04-11 13:19:45 -04002891 FOps << MkId(lookupType(FTy->getReturnType()));
David Neto22f144c2017-06-12 14:26:21 -04002892
2893 // Check function attributes for SPIRV Function Control.
2894 uint32_t FuncControl = spv::FunctionControlMaskNone;
2895 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2896 FuncControl |= spv::FunctionControlInlineMask;
2897 }
2898 if (F.hasFnAttribute(Attribute::NoInline)) {
2899 FuncControl |= spv::FunctionControlDontInlineMask;
2900 }
2901 // TODO: Check llvm attribute for Function Control Pure.
2902 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2903 FuncControl |= spv::FunctionControlPureMask;
2904 }
2905 // TODO: Check llvm attribute for Function Control Const.
2906 if (F.hasFnAttribute(Attribute::ReadNone)) {
2907 FuncControl |= spv::FunctionControlConstMask;
2908 }
2909
David Neto257c3892018-04-11 13:19:45 -04002910 FOps << MkNum(FuncControl);
David Neto22f144c2017-06-12 14:26:21 -04002911
2912 uint32_t FTyID;
2913 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2914 SmallVector<Type *, 4> NewFuncParamTys;
2915 FunctionType *NewFTy =
2916 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
2917 FTyID = lookupType(NewFTy);
2918 } else {
David Neto9ed8e2f2018-03-24 06:47:24 -07002919 // Handle regular function with global constant parameters.
David Neto22f144c2017-06-12 14:26:21 -04002920 if (GlobalConstFuncTyMap.count(FTy)) {
2921 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
2922 } else {
2923 FTyID = lookupType(FTy);
2924 }
2925 }
2926
David Neto257c3892018-04-11 13:19:45 -04002927 FOps << MkId(FTyID);
David Neto22f144c2017-06-12 14:26:21 -04002928
2929 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2930 EntryPoints.push_back(std::make_pair(&F, nextID));
2931 }
2932
2933 VMap[&F] = nextID;
2934
David Neto482550a2018-03-24 05:21:07 -07002935 if (clspv::Option::ShowIDs()) {
David Netob05675d2018-02-16 12:37:49 -05002936 errs() << "Function " << F.getName() << " is " << nextID << "\n";
2937 }
David Neto22f144c2017-06-12 14:26:21 -04002938 // Generate SPIRV instruction for function.
2939 SPIRVInstruction *FuncInst =
2940 new SPIRVInstruction(5, spv::OpFunction, nextID++, FOps);
2941 SPIRVInstList.push_back(FuncInst);
2942
2943 //
2944 // Generate OpFunctionParameter for Normal function.
2945 //
2946
2947 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2948 // Iterate Argument for name instead of param type from function type.
2949 unsigned ArgIdx = 0;
2950 for (Argument &Arg : F.args()) {
2951 VMap[&Arg] = nextID;
2952
2953 // ParamOps[0] : Result Type ID
2954 SPIRVOperandList ParamOps;
2955
2956 // Find SPIRV instruction for parameter type.
2957 uint32_t ParamTyID = lookupType(Arg.getType());
2958 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2959 if (GlobalConstFuncTyMap.count(FTy)) {
2960 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2961 Type *EleTy = PTy->getPointerElementType();
2962 Type *ArgTy =
2963 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
2964 ParamTyID = lookupType(ArgTy);
2965 GlobalConstArgSet.insert(&Arg);
2966 }
2967 }
2968 }
David Neto257c3892018-04-11 13:19:45 -04002969 ParamOps << MkId(ParamTyID);
David Neto22f144c2017-06-12 14:26:21 -04002970
2971 // Generate SPIRV instruction for parameter.
2972 SPIRVInstruction *ParamInst =
2973 new SPIRVInstruction(3, spv::OpFunctionParameter, nextID++, ParamOps);
2974 SPIRVInstList.push_back(ParamInst);
2975
2976 ArgIdx++;
2977 }
2978 }
2979}
2980
David Neto5c22a252018-03-15 16:07:41 -04002981void SPIRVProducerPass::GenerateModuleInfo(Module& module) {
David Neto22f144c2017-06-12 14:26:21 -04002982 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2983 EntryPointVecType &EntryPoints = getEntryPointVec();
2984 ValueMapType &VMap = getValueMap();
2985 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
2986 uint32_t &ExtInstImportID = getOpExtInstImportID();
2987 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2988
2989 // Set up insert point.
2990 auto InsertPoint = SPIRVInstList.begin();
2991
2992 //
2993 // Generate OpCapability
2994 //
2995 // TODO: Which llvm information is mapped to SPIRV Capapbility?
2996
2997 // Ops[0] = Capability
2998 SPIRVOperandList Ops;
2999
3000 SPIRVInstruction *CapInst = new SPIRVInstruction(
3001 2, spv::OpCapability, 0 /* No id */,
3002 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::CapabilityShader));
3003 SPIRVInstList.insert(InsertPoint, CapInst);
3004
3005 for (Type *Ty : getTypeList()) {
3006 // Find the i16 type.
3007 if (Ty->isIntegerTy(16)) {
3008 // Generate OpCapability for i16 type.
3009 SPIRVInstList.insert(
3010 InsertPoint,
3011 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3012 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3013 spv::CapabilityInt16)));
3014 } else if (Ty->isIntegerTy(64)) {
3015 // Generate OpCapability for i64 type.
3016 SPIRVInstList.insert(
3017 InsertPoint,
3018 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3019 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3020 spv::CapabilityInt64)));
3021 } else if (Ty->isHalfTy()) {
3022 // Generate OpCapability for half type.
3023 SPIRVInstList.insert(
3024 InsertPoint,
3025 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3026 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3027 spv::CapabilityFloat16)));
3028 } else if (Ty->isDoubleTy()) {
3029 // Generate OpCapability for double type.
3030 SPIRVInstList.insert(
3031 InsertPoint,
3032 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3033 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3034 spv::CapabilityFloat64)));
3035 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
3036 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04003037 if (STy->getName().equals("opencl.image2d_wo_t") ||
3038 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04003039 // Generate OpCapability for write only image type.
3040 SPIRVInstList.insert(
3041 InsertPoint,
3042 new SPIRVInstruction(
3043 2, spv::OpCapability, 0 /* No id */,
3044 new SPIRVOperand(
3045 SPIRVOperandType::NUMBERID,
3046 spv::CapabilityStorageImageWriteWithoutFormat)));
3047 }
3048 }
3049 }
3050 }
3051
David Neto5c22a252018-03-15 16:07:41 -04003052 { // OpCapability ImageQuery
3053 bool hasImageQuery = false;
3054 for (const char *imageQuery : {
3055 "_Z15get_image_width14ocl_image2d_ro",
3056 "_Z15get_image_width14ocl_image2d_wo",
3057 "_Z16get_image_height14ocl_image2d_ro",
3058 "_Z16get_image_height14ocl_image2d_wo",
3059 }) {
3060 if (module.getFunction(imageQuery)) {
3061 hasImageQuery = true;
3062 break;
3063 }
3064 }
3065 if (hasImageQuery) {
3066
3067 SPIRVInstruction *ImageQueryCapInst =
3068 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
3069 new SPIRVOperand(SPIRVOperandType::NUMBERID,
3070 spv::CapabilityImageQuery));
3071 SPIRVInstList.insert(InsertPoint, ImageQueryCapInst);
3072 }
3073 }
3074
David Neto22f144c2017-06-12 14:26:21 -04003075 if (hasVariablePointers()) {
3076 //
3077 // Generate OpCapability and OpExtension
3078 //
3079
3080 //
3081 // Generate OpCapability.
3082 //
3083 // Ops[0] = Capability
3084 //
3085 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003086 Ops << MkNum(spv::CapabilityVariablePointers);
David Neto22f144c2017-06-12 14:26:21 -04003087
3088 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(2, spv::OpCapability,
3089 0 /* No id */, Ops));
3090
3091 //
3092 // Generate OpExtension.
3093 //
3094 // Ops[0] = Name (Literal String)
3095 //
David Netoa772fd12017-08-04 14:17:33 -04003096 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3097 "SPV_KHR_variable_pointers"}) {
3098 Ops.clear();
David Neto22f144c2017-06-12 14:26:21 -04003099
David Neto257c3892018-04-11 13:19:45 -04003100 Ops << MkString(extension);
David Neto22f144c2017-06-12 14:26:21 -04003101
David Neto257c3892018-04-11 13:19:45 -04003102 const size_t NameWordSize = (std::strlen(extension) + 4)/4;
David Netoa772fd12017-08-04 14:17:33 -04003103 assert((NameWordSize + 1) < UINT16_MAX);
David Neto257c3892018-04-11 13:19:45 -04003104
David Netoa772fd12017-08-04 14:17:33 -04003105 uint16_t WordCount = static_cast<uint16_t>(1 + NameWordSize);
3106
3107 SPIRVInstruction *ExtensionInst =
3108 new SPIRVInstruction(WordCount, spv::OpExtension, 0 /* No id */, Ops);
3109 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003110 }
David Neto22f144c2017-06-12 14:26:21 -04003111 }
3112
3113 if (ExtInstImportID) {
3114 ++InsertPoint;
3115 }
3116
3117 //
3118 // Generate OpMemoryModel
3119 //
3120 // Memory model for Vulkan will always be GLSL450.
3121
3122 // Ops[0] = Addressing Model
3123 // Ops[1] = Memory Model
3124 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003125 Ops << MkNum(spv::AddressingModelLogical) << MkNum(spv::MemoryModelGLSL450);
David Neto22f144c2017-06-12 14:26:21 -04003126
3127 SPIRVInstruction *MemModelInst =
3128 new SPIRVInstruction(3, spv::OpMemoryModel, 0 /* No id */, Ops);
3129 SPIRVInstList.insert(InsertPoint, MemModelInst);
3130
3131 //
3132 // Generate OpEntryPoint
3133 //
3134 for (auto EntryPoint : EntryPoints) {
3135 // Ops[0] = Execution Model
3136 // Ops[1] = EntryPoint ID
3137 // Ops[2] = Name (Literal String)
3138 // ...
3139 //
3140 // TODO: Do we need to consider Interface ID for forward references???
3141 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003142 const StringRef& name = EntryPoint.first->getName();
3143 Ops << MkNum(spv::ExecutionModelGLCompute) << MkId(EntryPoint.second)
3144 << MkString(name);
David Neto22f144c2017-06-12 14:26:21 -04003145
David Neto257c3892018-04-11 13:19:45 -04003146 const size_t NameWordSize = (name.size() + 4) / 4;
David Neto22f144c2017-06-12 14:26:21 -04003147
3148 assert((3 + NameWordSize) < UINT16_MAX);
3149 uint16_t WordCount = static_cast<uint16_t>(3 + NameWordSize);
3150
3151 for (Value *Interface : EntryPointInterfaces) {
David Neto257c3892018-04-11 13:19:45 -04003152 Ops << MkId(VMap[Interface]);
David Neto22f144c2017-06-12 14:26:21 -04003153 WordCount++;
3154 }
3155
3156 SPIRVInstruction *EntryPointInst =
3157 new SPIRVInstruction(WordCount, spv::OpEntryPoint, 0 /* No id */, Ops);
3158 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3159 }
3160
3161 for (auto EntryPoint : EntryPoints) {
3162 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3163 ->getMetadata("reqd_work_group_size")) {
3164
3165 if (!BuiltinDimVec.empty()) {
3166 llvm_unreachable(
3167 "Kernels should have consistent work group size definition");
3168 }
3169
3170 //
3171 // Generate OpExecutionMode
3172 //
3173
3174 // Ops[0] = Entry Point ID
3175 // Ops[1] = Execution Mode
3176 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3177 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003178 Ops << MkId(EntryPoint.second)
3179 << MkNum(spv::ExecutionModeLocalSize);
David Neto22f144c2017-06-12 14:26:21 -04003180
3181 uint32_t XDim = static_cast<uint32_t>(
3182 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3183 uint32_t YDim = static_cast<uint32_t>(
3184 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3185 uint32_t ZDim = static_cast<uint32_t>(
3186 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3187
David Neto257c3892018-04-11 13:19:45 -04003188 Ops << MkNum(XDim) << MkNum(YDim) << MkNum(ZDim);
David Neto22f144c2017-06-12 14:26:21 -04003189
3190 SPIRVInstruction *ExecModeInst =
3191 new SPIRVInstruction(static_cast<uint16_t>(1 + Ops.size()),
3192 spv::OpExecutionMode, 0 /* No id */, Ops);
3193 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3194 }
3195 }
3196
3197 //
3198 // Generate OpSource.
3199 //
3200 // Ops[0] = SourceLanguage ID
3201 // Ops[1] = Version (LiteralNum)
3202 //
3203 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003204 Ops << MkNum(spv::SourceLanguageOpenCL_C) << MkNum(120);
David Neto22f144c2017-06-12 14:26:21 -04003205
3206 SPIRVInstruction *OpenSourceInst =
3207 new SPIRVInstruction(3, spv::OpSource, 0 /* No id */, Ops);
3208 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3209
3210 if (!BuiltinDimVec.empty()) {
3211 //
3212 // Generate OpDecorates for x/y/z dimension.
3213 //
3214 // Ops[0] = Target ID
3215 // Ops[1] = Decoration (SpecId)
David Neto257c3892018-04-11 13:19:45 -04003216 // Ops[2] = Specialization Constant ID (Literal Number)
David Neto22f144c2017-06-12 14:26:21 -04003217
3218 // X Dimension
3219 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003220 Ops << MkId(BuiltinDimVec[0]) << MkNum(spv::DecorationSpecId) << MkNum(0);
3221 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(4, spv::OpDecorate,
3222 0 /* No id */, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003223
3224 // Y Dimension
3225 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003226 Ops << MkId(BuiltinDimVec[1]) << MkNum(spv::DecorationSpecId) << MkNum(1);
3227 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(4, spv::OpDecorate,
3228 0 /* No id */, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003229
3230 // Z Dimension
3231 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003232 Ops << MkId(BuiltinDimVec[2]) << MkNum(spv::DecorationSpecId) << MkNum(2);
3233 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(4, spv::OpDecorate,
3234 0 /* No id */, Ops));
David Neto22f144c2017-06-12 14:26:21 -04003235 }
3236}
3237
3238void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3239 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3240 ValueMapType &VMap = getValueMap();
3241 Module *Module = F.getParent();
3242 LLVMContext &Context = Module->getContext();
3243 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3244
3245 for (Argument &Arg : F.args()) {
3246 if (Arg.use_empty()) {
3247 continue;
3248 }
3249
David Netoc6f3ab22018-04-06 18:02:31 -04003250 Type *ArgTy = Arg.getType();
3251 if (IsLocalPtr(ArgTy)) {
3252 // Generate OpAccessChain to point to the first element of the array.
3253 const LocalArgInfo &info = LocalArgMap[&Arg];
3254 VMap[&Arg] = info.first_elem_ptr_id;
3255
3256 SPIRVOperandList Ops;
3257 uint32_t zeroId = VMap[ConstantInt::get(Type::getInt32Ty(Context), 0)];
3258 Ops << MkId(lookupType(ArgTy)) << MkId(info.variable_id) << MkId(zeroId);
3259 SPIRVInstList.push_back(new SPIRVInstruction(
3260 5, spv::OpAccessChain, info.first_elem_ptr_id, Ops));
3261
3262 continue;
3263 }
3264
David Neto22f144c2017-06-12 14:26:21 -04003265 // Check the type of users of arguments.
3266 bool HasOnlyGEPUse = true;
3267 for (auto *U : Arg.users()) {
3268 if (!isa<GetElementPtrInst>(U) && isa<Instruction>(U)) {
3269 HasOnlyGEPUse = false;
3270 break;
3271 }
3272 }
3273
David Neto22f144c2017-06-12 14:26:21 -04003274 if (PointerType *PTy = dyn_cast<PointerType>(ArgTy)) {
3275 if (StructType *STy = dyn_cast<StructType>(PTy->getElementType())) {
3276 if (STy->isOpaque()) {
3277 // Generate OpLoad for sampler and image types.
3278 if (STy->getName().equals("opencl.sampler_t") ||
3279 STy->getName().equals("opencl.image2d_ro_t") ||
3280 STy->getName().equals("opencl.image2d_wo_t") ||
3281 STy->getName().equals("opencl.image3d_ro_t") ||
3282 STy->getName().equals("opencl.image3d_wo_t")) {
3283 //
3284 // Generate OpLoad.
3285 //
3286 // Ops[0] = Result Type ID
3287 // Ops[1] = Pointer ID
3288 // Ops[2] ... Ops[n] = Optional Memory Access
3289 //
3290 // TODO: Do we need to implement Optional Memory Access???
3291 SPIRVOperandList Ops;
3292
3293 // Use type with address space modified.
3294 ArgTy = ArgGVMap[&Arg]->getType()->getPointerElementType();
3295
David Neto257c3892018-04-11 13:19:45 -04003296 Ops << MkId(lookupType(ArgTy));
David Neto22f144c2017-06-12 14:26:21 -04003297
3298 uint32_t PointerID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003299 Ops << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04003300
3301 VMap[&Arg] = nextID;
3302 SPIRVInstruction *Inst =
3303 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3304 SPIRVInstList.push_back(Inst);
3305 continue;
3306 }
3307 }
3308 }
3309
3310 if (!HasOnlyGEPUse) {
3311 //
3312 // Generate OpAccessChain.
3313 //
3314 // Ops[0] = Result Type ID
3315 // Ops[1] = Base ID
3316 // Ops[2] ... Ops[n] = Indexes ID
3317 SPIRVOperandList Ops;
3318
3319 uint32_t ResTyID = lookupType(ArgTy);
3320 if (!isa<PointerType>(ArgTy)) {
3321 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3322 }
David Neto257c3892018-04-11 13:19:45 -04003323 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003324
3325 uint32_t BaseID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003326 Ops << MkId(BaseID) << MkId(GetI32Zero())
3327 << MkId(GetI32Zero());
David Neto22f144c2017-06-12 14:26:21 -04003328
3329 // Generate SPIRV instruction for argument.
3330 VMap[&Arg] = nextID;
3331 SPIRVInstruction *ArgInst =
3332 new SPIRVInstruction(6, spv::OpAccessChain, nextID++, Ops);
3333 SPIRVInstList.push_back(ArgInst);
3334 } else {
3335 // For GEP uses, generate OpAccessChain with folding GEP ahead of GEP.
3336 // Nothing to do here.
3337 }
3338 } else {
3339 //
3340 // Generate OpAccessChain and OpLoad for non-pointer type argument.
3341 //
3342
3343 //
3344 // Generate OpAccessChain.
3345 //
3346 // Ops[0] = Result Type ID
3347 // Ops[1] = Base ID
3348 // Ops[2] ... Ops[n] = Indexes ID
3349 SPIRVOperandList Ops;
3350
3351 uint32_t ResTyID = lookupType(ArgTy);
3352 if (!isa<PointerType>(ArgTy)) {
David Neto482550a2018-03-24 05:21:07 -07003353 auto AS = clspv::Option::PodArgsInUniformBuffer()
3354 ? AddressSpace::Uniform
3355 : AddressSpace::Global;
David Netoe439d702018-03-23 13:14:08 -07003356 ResTyID = lookupType(PointerType::get(ArgTy, AS));
David Neto22f144c2017-06-12 14:26:21 -04003357 }
David Neto257c3892018-04-11 13:19:45 -04003358 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003359
3360 uint32_t BaseID = VMap[&Arg];
David Neto257c3892018-04-11 13:19:45 -04003361 Ops << MkId(BaseID) << MkId(GetI32Zero());
David Neto22f144c2017-06-12 14:26:21 -04003362
3363 // Generate SPIRV instruction for argument.
3364 uint32_t PointerID = nextID;
3365 VMap[&Arg] = nextID;
3366 SPIRVInstruction *ArgInst =
3367 new SPIRVInstruction(5, spv::OpAccessChain, nextID++, Ops);
3368 SPIRVInstList.push_back(ArgInst);
3369
3370 //
3371 // Generate OpLoad.
3372 //
3373
3374 // Ops[0] = Result Type ID
3375 // Ops[1] = Pointer ID
3376 // Ops[2] ... Ops[n] = Optional Memory Access
3377 //
3378 // TODO: Do we need to implement Optional Memory Access???
3379 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003380 Ops << MkId(lookupType(ArgTy)) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04003381
3382 VMap[&Arg] = nextID;
3383 SPIRVInstruction *Inst =
3384 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3385 SPIRVInstList.push_back(Inst);
3386 }
3387 }
3388}
3389
3390void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3391 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3392 ValueMapType &VMap = getValueMap();
3393
3394 bool IsKernel = false;
3395 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3396 IsKernel = true;
3397 }
3398
3399 for (BasicBlock &BB : F) {
3400 // Register BasicBlock to ValueMap.
3401 VMap[&BB] = nextID;
3402
3403 //
3404 // Generate OpLabel for Basic Block.
3405 //
3406 SPIRVOperandList Ops;
3407 SPIRVInstruction *Inst =
3408 new SPIRVInstruction(2, spv::OpLabel, nextID++, Ops);
3409 SPIRVInstList.push_back(Inst);
3410
David Neto6dcd4712017-06-23 11:06:47 -04003411 // OpVariable instructions must come first.
3412 for (Instruction &I : BB) {
3413 if (isa<AllocaInst>(I)) {
3414 GenerateInstruction(I);
3415 }
3416 }
3417
David Neto22f144c2017-06-12 14:26:21 -04003418 if (&BB == &F.getEntryBlock() && IsKernel) {
3419 GenerateInstForArg(F);
3420 }
3421
3422 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003423 if (!isa<AllocaInst>(I)) {
3424 GenerateInstruction(I);
3425 }
David Neto22f144c2017-06-12 14:26:21 -04003426 }
3427 }
3428}
3429
3430spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3431 const std::map<CmpInst::Predicate, spv::Op> Map = {
3432 {CmpInst::ICMP_EQ, spv::OpIEqual},
3433 {CmpInst::ICMP_NE, spv::OpINotEqual},
3434 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3435 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3436 {CmpInst::ICMP_ULT, spv::OpULessThan},
3437 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3438 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3439 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3440 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3441 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3442 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3443 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3444 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3445 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3446 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3447 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3448 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3449 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3450 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3451 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3452 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3453 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3454
3455 assert(0 != Map.count(I->getPredicate()));
3456
3457 return Map.at(I->getPredicate());
3458}
3459
3460spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3461 const std::map<unsigned, spv::Op> Map{
3462 {Instruction::Trunc, spv::OpUConvert},
3463 {Instruction::ZExt, spv::OpUConvert},
3464 {Instruction::SExt, spv::OpSConvert},
3465 {Instruction::FPToUI, spv::OpConvertFToU},
3466 {Instruction::FPToSI, spv::OpConvertFToS},
3467 {Instruction::UIToFP, spv::OpConvertUToF},
3468 {Instruction::SIToFP, spv::OpConvertSToF},
3469 {Instruction::FPTrunc, spv::OpFConvert},
3470 {Instruction::FPExt, spv::OpFConvert},
3471 {Instruction::BitCast, spv::OpBitcast}};
3472
3473 assert(0 != Map.count(I.getOpcode()));
3474
3475 return Map.at(I.getOpcode());
3476}
3477
3478spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3479 if (I.getType()->isIntegerTy(1)) {
3480 switch (I.getOpcode()) {
3481 default:
3482 break;
3483 case Instruction::Or:
3484 return spv::OpLogicalOr;
3485 case Instruction::And:
3486 return spv::OpLogicalAnd;
3487 case Instruction::Xor:
3488 return spv::OpLogicalNotEqual;
3489 }
3490 }
3491
3492 const std::map<unsigned, spv::Op> Map {
3493 {Instruction::Add, spv::OpIAdd},
3494 {Instruction::FAdd, spv::OpFAdd},
3495 {Instruction::Sub, spv::OpISub},
3496 {Instruction::FSub, spv::OpFSub},
3497 {Instruction::Mul, spv::OpIMul},
3498 {Instruction::FMul, spv::OpFMul},
3499 {Instruction::UDiv, spv::OpUDiv},
3500 {Instruction::SDiv, spv::OpSDiv},
3501 {Instruction::FDiv, spv::OpFDiv},
3502 {Instruction::URem, spv::OpUMod},
3503 {Instruction::SRem, spv::OpSRem},
3504 {Instruction::FRem, spv::OpFRem},
3505 {Instruction::Or, spv::OpBitwiseOr},
3506 {Instruction::Xor, spv::OpBitwiseXor},
3507 {Instruction::And, spv::OpBitwiseAnd},
3508 {Instruction::Shl, spv::OpShiftLeftLogical},
3509 {Instruction::LShr, spv::OpShiftRightLogical},
3510 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3511
3512 assert(0 != Map.count(I.getOpcode()));
3513
3514 return Map.at(I.getOpcode());
3515}
3516
3517void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3518 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3519 ValueMapType &VMap = getValueMap();
3520 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3521 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
3522 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3523 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3524
3525 // Register Instruction to ValueMap.
3526 if (0 == VMap[&I]) {
3527 VMap[&I] = nextID;
3528 }
3529
3530 switch (I.getOpcode()) {
3531 default: {
3532 if (Instruction::isCast(I.getOpcode())) {
3533 //
3534 // Generate SPIRV instructions for cast operators.
3535 //
3536
David Netod2de94a2017-08-28 17:27:47 -04003537
3538 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003539 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003540 auto toI8 = Ty == Type::getInt8Ty(Context);
3541 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003542 // Handle zext, sext and uitofp with i1 type specially.
3543 if ((I.getOpcode() == Instruction::ZExt ||
3544 I.getOpcode() == Instruction::SExt ||
3545 I.getOpcode() == Instruction::UIToFP) &&
3546 (OpTy->isIntegerTy(1) ||
3547 (OpTy->isVectorTy() &&
3548 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3549 //
3550 // Generate OpSelect.
3551 //
3552
3553 // Ops[0] = Result Type ID
3554 // Ops[1] = Condition ID
3555 // Ops[2] = True Constant ID
3556 // Ops[3] = False Constant ID
3557 SPIRVOperandList Ops;
3558
David Neto257c3892018-04-11 13:19:45 -04003559 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003560
David Neto22f144c2017-06-12 14:26:21 -04003561 uint32_t CondID = VMap[I.getOperand(0)];
David Neto257c3892018-04-11 13:19:45 -04003562 Ops << MkId(CondID);
David Neto22f144c2017-06-12 14:26:21 -04003563
3564 uint32_t TrueID = 0;
3565 if (I.getOpcode() == Instruction::ZExt) {
3566 APInt One(32, 1);
3567 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3568 } else if (I.getOpcode() == Instruction::SExt) {
3569 APInt MinusOne(32, UINT64_MAX, true);
3570 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3571 } else {
3572 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3573 }
David Neto257c3892018-04-11 13:19:45 -04003574 Ops << MkId(TrueID);
David Neto22f144c2017-06-12 14:26:21 -04003575
3576 uint32_t FalseID = 0;
3577 if (I.getOpcode() == Instruction::ZExt) {
3578 FalseID = VMap[Constant::getNullValue(I.getType())];
3579 } else if (I.getOpcode() == Instruction::SExt) {
3580 FalseID = VMap[Constant::getNullValue(I.getType())];
3581 } else {
3582 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3583 }
David Neto257c3892018-04-11 13:19:45 -04003584 Ops << MkId(FalseID);
David Neto22f144c2017-06-12 14:26:21 -04003585
3586 SPIRVInstruction *Inst =
3587 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3588 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003589 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3590 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3591 // 8 bits.
3592 // Before:
3593 // %result = trunc i32 %a to i8
3594 // After
3595 // %result = OpBitwiseAnd %uint %a %uint_255
3596
3597 SPIRVOperandList Ops;
3598
David Neto257c3892018-04-11 13:19:45 -04003599 Ops << MkId(lookupType(OpTy)) << MkId(VMap[I.getOperand(0)]);
David Netod2de94a2017-08-28 17:27:47 -04003600
3601 Type *UintTy = Type::getInt32Ty(Context);
3602 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
David Neto257c3892018-04-11 13:19:45 -04003603 Ops << MkId(MaskID);
David Netod2de94a2017-08-28 17:27:47 -04003604
3605 SPIRVInstruction *Inst =
3606 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3607 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003608 } else {
3609 // Ops[0] = Result Type ID
3610 // Ops[1] = Source Value ID
3611 SPIRVOperandList Ops;
3612
David Neto257c3892018-04-11 13:19:45 -04003613 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003614
3615 SPIRVInstruction *Inst =
3616 new SPIRVInstruction(4, GetSPIRVCastOpcode(I), nextID++, Ops);
3617 SPIRVInstList.push_back(Inst);
3618 }
3619 } else if (isa<BinaryOperator>(I)) {
3620 //
3621 // Generate SPIRV instructions for binary operators.
3622 //
3623
3624 // Handle xor with i1 type specially.
3625 if (I.getOpcode() == Instruction::Xor &&
3626 I.getType() == Type::getInt1Ty(Context) &&
3627 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3628 //
3629 // Generate OpLogicalNot.
3630 //
3631 // Ops[0] = Result Type ID
3632 // Ops[1] = Operand
3633 SPIRVOperandList Ops;
3634
David Neto257c3892018-04-11 13:19:45 -04003635 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003636
3637 Value *CondV = I.getOperand(0);
3638 if (isa<Constant>(I.getOperand(0))) {
3639 CondV = I.getOperand(1);
3640 }
David Neto257c3892018-04-11 13:19:45 -04003641 Ops << MkId(VMap[CondV]);
David Neto22f144c2017-06-12 14:26:21 -04003642
3643 SPIRVInstruction *Inst =
3644 new SPIRVInstruction(4, spv::OpLogicalNot, nextID++, Ops);
3645 SPIRVInstList.push_back(Inst);
3646 } else {
3647 // Ops[0] = Result Type ID
3648 // Ops[1] = Operand 0
3649 // Ops[2] = Operand 1
3650 SPIRVOperandList Ops;
3651
David Neto257c3892018-04-11 13:19:45 -04003652 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
3653 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003654
3655 SPIRVInstruction *Inst =
3656 new SPIRVInstruction(5, GetSPIRVBinaryOpcode(I), nextID++, Ops);
3657 SPIRVInstList.push_back(Inst);
3658 }
3659 } else {
3660 I.print(errs());
3661 llvm_unreachable("Unsupported instruction???");
3662 }
3663 break;
3664 }
3665 case Instruction::GetElementPtr: {
3666 auto &GlobalConstArgSet = getGlobalConstArgSet();
3667
3668 //
3669 // Generate OpAccessChain.
3670 //
3671 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3672
3673 //
3674 // Generate OpAccessChain.
3675 //
3676
3677 // Ops[0] = Result Type ID
3678 // Ops[1] = Base ID
3679 // Ops[2] ... Ops[n] = Indexes ID
3680 SPIRVOperandList Ops;
3681
David Neto1a1a0582017-07-07 12:01:44 -04003682 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003683 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3684 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3685 // Use pointer type with private address space for global constant.
3686 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003687 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003688 }
David Neto257c3892018-04-11 13:19:45 -04003689
3690 Ops << MkId(lookupType(ResultType));
David Neto22f144c2017-06-12 14:26:21 -04003691
3692 // Check whether GEP's pointer operand is pointer argument.
3693 bool HasArgBasePointer = false;
3694 for (auto ArgGV : ArgGVMap) {
3695 if (ArgGV.first == GEP->getPointerOperand()) {
3696 if (isa<PointerType>(ArgGV.first->getType())) {
3697 HasArgBasePointer = true;
3698 } else {
3699 llvm_unreachable(
3700 "GEP's pointer operand is argument of non-poninter type???");
3701 }
3702 }
3703 }
3704
3705 uint32_t BaseID;
3706 if (HasArgBasePointer) {
3707 // Point to global variable for argument directly.
3708 BaseID = ArgGVIDMap[GEP->getPointerOperand()];
3709 } else {
3710 BaseID = VMap[GEP->getPointerOperand()];
3711 }
3712
David Neto257c3892018-04-11 13:19:45 -04003713 Ops << MkId(BaseID);
David Neto22f144c2017-06-12 14:26:21 -04003714
3715 uint16_t WordCount = 4;
3716
3717 if (HasArgBasePointer) {
3718 // If GEP's pointer operand is argument, add one more index for struct
3719 // type to wrap up argument type.
3720 Type *IdxTy = Type::getInt32Ty(Context);
David Neto257c3892018-04-11 13:19:45 -04003721 Ops << MkId(VMap[ConstantInt::get(IdxTy, 0)]);
David Neto22f144c2017-06-12 14:26:21 -04003722
3723 WordCount++;
3724 }
3725
3726 //
3727 // Follows below rules for gep.
3728 //
3729 // 1. If gep's first index is 0 and gep's base is not kernel function's
3730 // argument, generate OpAccessChain and ignore gep's first index.
3731 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3732 // first index.
3733 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3734 // use gep's first index.
3735 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3736 // gep's first index.
3737 //
3738 spv::Op Opcode = spv::OpAccessChain;
3739 unsigned offset = 0;
3740 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
3741 if (CstInt->getZExtValue() == 0 && !HasArgBasePointer) {
3742 offset = 1;
3743 } else if (CstInt->getZExtValue() != 0 && !HasArgBasePointer) {
3744 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003745 }
3746 } else if (!HasArgBasePointer) {
3747 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003748 }
3749
3750 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003751 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003752 // Do we need to generate ArrayStride? Check against the GEP result type
3753 // rather than the pointer type of the base because when indexing into
3754 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3755 // for something else in the SPIR-V.
3756 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3757 if (GetStorageClass(ResultType->getAddressSpace()) ==
3758 spv::StorageClassStorageBuffer) {
3759 // Save the need to generate an ArrayStride decoration. But defer
3760 // generation until later, so we only make one decoration.
David Neto85082642018-03-24 06:55:20 -07003761 getTypesNeedingArrayStride().insert(ResultType);
David Neto1a1a0582017-07-07 12:01:44 -04003762 }
David Neto22f144c2017-06-12 14:26:21 -04003763 }
3764
3765 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
David Neto257c3892018-04-11 13:19:45 -04003766 Ops << MkId(VMap[*II]);
David Neto22f144c2017-06-12 14:26:21 -04003767 WordCount++;
3768 }
3769
3770 SPIRVInstruction *Inst =
3771 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3772 SPIRVInstList.push_back(Inst);
3773 break;
3774 }
3775 case Instruction::ExtractValue: {
3776 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3777 // Ops[0] = Result Type ID
3778 // Ops[1] = Composite ID
3779 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3780 SPIRVOperandList Ops;
3781
David Neto257c3892018-04-11 13:19:45 -04003782 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04003783
3784 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003785 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003786
3787 for (auto &Index : EVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003788 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003789 }
3790
3791 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3792 SPIRVInstruction *Inst =
3793 new SPIRVInstruction(WordCount, spv::OpCompositeExtract, nextID++, Ops);
3794 SPIRVInstList.push_back(Inst);
3795 break;
3796 }
3797 case Instruction::InsertValue: {
3798 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3799 // Ops[0] = Result Type ID
3800 // Ops[1] = Object ID
3801 // Ops[2] = Composite ID
3802 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3803 SPIRVOperandList Ops;
3804
3805 uint32_t ResTyID = lookupType(I.getType());
David Neto257c3892018-04-11 13:19:45 -04003806 Ops << MkId(ResTyID);
David Neto22f144c2017-06-12 14:26:21 -04003807
3808 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
David Neto257c3892018-04-11 13:19:45 -04003809 Ops << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04003810
3811 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
David Neto257c3892018-04-11 13:19:45 -04003812 Ops << MkId(CompositeID);
David Neto22f144c2017-06-12 14:26:21 -04003813
3814 for (auto &Index : IVI->indices()) {
David Neto257c3892018-04-11 13:19:45 -04003815 Ops << MkNum(Index);
David Neto22f144c2017-06-12 14:26:21 -04003816 }
3817
3818 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3819 SPIRVInstruction *Inst =
3820 new SPIRVInstruction(WordCount, spv::OpCompositeInsert, nextID++, Ops);
3821 SPIRVInstList.push_back(Inst);
3822 break;
3823 }
3824 case Instruction::Select: {
3825 //
3826 // Generate OpSelect.
3827 //
3828
3829 // Ops[0] = Result Type ID
3830 // Ops[1] = Condition ID
3831 // Ops[2] = True Constant ID
3832 // Ops[3] = False Constant ID
3833 SPIRVOperandList Ops;
3834
3835 // Find SPIRV instruction for parameter type.
3836 auto Ty = I.getType();
3837 if (Ty->isPointerTy()) {
3838 auto PointeeTy = Ty->getPointerElementType();
3839 if (PointeeTy->isStructTy() &&
3840 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3841 Ty = PointeeTy;
3842 }
3843 }
3844
David Neto257c3892018-04-11 13:19:45 -04003845 Ops << MkId(lookupType(Ty)) << MkId(VMap[I.getOperand(0)])
3846 << MkId(VMap[I.getOperand(1)]) << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003847
3848 SPIRVInstruction *Inst =
3849 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3850 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
3895 SPIRVInstruction *TmpInst =
3896 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
3897 SPIRVInstList.push_back(TmpInst);
3898 }
David Neto257c3892018-04-11 13:19:45 -04003899 Ops << MkId(Op1ID);
David Neto22f144c2017-06-12 14:26:21 -04003900
3901 uint32_t ShiftID = nextID;
3902
3903 SPIRVInstruction *Inst =
3904 new SPIRVInstruction(5, spv::OpShiftRightLogical, nextID++, Ops);
3905 SPIRVInstList.push_back(Inst);
3906
3907 //
3908 // Generate OpBitwiseAnd
3909 //
3910 // Ops[0] = Result Type ID
3911 // Ops[1] = Operand 0
3912 // Ops[2] = Operand 1
3913 //
3914 Ops.clear();
3915
David Neto257c3892018-04-11 13:19:45 -04003916 Ops << MkId(lookupType(CompositeTy)) << MkId(ShiftID);
David Neto22f144c2017-06-12 14:26:21 -04003917
3918 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
David Neto257c3892018-04-11 13:19:45 -04003919 Ops << MkId(VMap[CstFF]);
David Neto22f144c2017-06-12 14:26:21 -04003920
David Neto9b2d6252017-09-06 15:47:37 -04003921 // Reset mapping for this value to the result of the bitwise and.
3922 VMap[&I] = nextID;
3923
David Neto22f144c2017-06-12 14:26:21 -04003924 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3925 SPIRVInstList.push_back(Inst);
3926 break;
3927 }
3928
3929 // Ops[0] = Result Type ID
3930 // Ops[1] = Composite ID
3931 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3932 SPIRVOperandList Ops;
3933
David Neto257c3892018-04-11 13:19:45 -04003934 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04003935
3936 spv::Op Opcode = spv::OpCompositeExtract;
3937 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
David Neto257c3892018-04-11 13:19:45 -04003938 Ops << MkNum(static_cast<uint32_t>(CI->getZExtValue()));
David Neto22f144c2017-06-12 14:26:21 -04003939 } else {
David Neto257c3892018-04-11 13:19:45 -04003940 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04003941 Opcode = spv::OpVectorExtractDynamic;
3942 }
3943
3944 uint16_t WordCount = 5;
3945 SPIRVInstruction *Inst =
3946 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3947 SPIRVInstList.push_back(Inst);
3948 break;
3949 }
3950 case Instruction::InsertElement: {
3951 // Handle <4 x i8> type manually.
3952 Type *CompositeTy = I.getOperand(0)->getType();
3953 if (is4xi8vec(CompositeTy)) {
3954 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3955 uint32_t CstFFID = VMap[CstFF];
3956
3957 uint32_t ShiftAmountID = 0;
3958 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3959 // Handle constant index.
3960 uint64_t Idx = CI->getZExtValue();
3961 Value *ShiftAmount =
3962 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3963 ShiftAmountID = VMap[ShiftAmount];
3964 } else {
3965 // Handle variable index.
3966 SPIRVOperandList TmpOps;
3967
David Neto257c3892018-04-11 13:19:45 -04003968 TmpOps << MkId(lookupType(Type::getInt32Ty(Context)))
3969 << MkId(VMap[I.getOperand(2)]);
David Neto22f144c2017-06-12 14:26:21 -04003970
3971 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
David Neto257c3892018-04-11 13:19:45 -04003972 TmpOps << MkId(VMap[Cst8]);
David Neto22f144c2017-06-12 14:26:21 -04003973
3974 ShiftAmountID = nextID;
3975
3976 SPIRVInstruction *TmpInst =
3977 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
3978 SPIRVInstList.push_back(TmpInst);
3979 }
3980
3981 //
3982 // Generate mask operations.
3983 //
3984
3985 // ShiftLeft mask according to index of insertelement.
3986 SPIRVOperandList Ops;
3987
David Neto257c3892018-04-11 13:19:45 -04003988 const uint32_t ResTyID = lookupType(CompositeTy);
3989 Ops << MkId(ResTyID) << MkId(CstFFID) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04003990
3991 uint32_t MaskID = nextID;
3992
3993 SPIRVInstruction *Inst =
3994 new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
3995 SPIRVInstList.push_back(Inst);
3996
3997 // Inverse mask.
3998 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04003999 Ops << MkId(ResTyID) << MkId(MaskID);
David Neto22f144c2017-06-12 14:26:21 -04004000
4001 uint32_t InvMaskID = nextID;
4002
David Netoa394f392017-08-26 20:45:29 -04004003 Inst = new SPIRVInstruction(4, spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004004 SPIRVInstList.push_back(Inst);
4005
4006 // Apply mask.
4007 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004008 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(0)]) << MkId(InvMaskID);
David Neto22f144c2017-06-12 14:26:21 -04004009
4010 uint32_t OrgValID = nextID;
4011
4012 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4013 SPIRVInstList.push_back(Inst);
4014
4015 // Create correct value according to index of insertelement.
4016 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004017 Ops << MkId(ResTyID) << MkId(VMap[I.getOperand(1)]) << MkId(ShiftAmountID);
David Neto22f144c2017-06-12 14:26:21 -04004018
4019 uint32_t InsertValID = nextID;
4020
4021 Inst = new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
4022 SPIRVInstList.push_back(Inst);
4023
4024 // Insert value to original value.
4025 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004026 Ops << MkId(ResTyID) << MkId(OrgValID) << MkId(InsertValID);
David Neto22f144c2017-06-12 14:26:21 -04004027
David Netoa394f392017-08-26 20:45:29 -04004028 VMap[&I] = nextID;
4029
David Neto22f144c2017-06-12 14:26:21 -04004030 Inst = new SPIRVInstruction(5, spv::OpBitwiseOr, nextID++, Ops);
4031 SPIRVInstList.push_back(Inst);
4032
4033 break;
4034 }
4035
4036 // Ops[0] = Result Type ID
4037 // Ops[1] = Object ID
4038 // Ops[2] = Composite ID
4039 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4040 SPIRVOperandList Ops;
4041
David Neto257c3892018-04-11 13:19:45 -04004042 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(1)])
4043 << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004044
4045 spv::Op Opcode = spv::OpCompositeInsert;
4046 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
David Neto257c3892018-04-11 13:19:45 -04004047 const auto value = CI->getZExtValue();
4048 assert(value <= UINT32_MAX);
4049 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004050 } else {
David Neto257c3892018-04-11 13:19:45 -04004051 Ops << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004052 Opcode = spv::OpVectorInsertDynamic;
4053 }
4054
4055 uint16_t WordCount = 6;
4056 SPIRVInstruction *Inst =
4057 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4058 SPIRVInstList.push_back(Inst);
4059 break;
4060 }
4061 case Instruction::ShuffleVector: {
4062 // Ops[0] = Result Type ID
4063 // Ops[1] = Vector 1 ID
4064 // Ops[2] = Vector 2 ID
4065 // Ops[3] ... Ops[n] = Components (Literal Number)
4066 SPIRVOperandList Ops;
4067
David Neto257c3892018-04-11 13:19:45 -04004068 Ops << MkId(lookupType(I.getType())) << MkId(VMap[I.getOperand(0)])
4069 << MkId(VMap[I.getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004070
4071 uint64_t NumElements = 0;
4072 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4073 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4074
4075 if (Cst->isNullValue()) {
4076 for (unsigned i = 0; i < NumElements; i++) {
David Neto257c3892018-04-11 13:19:45 -04004077 Ops << MkNum(0);
David Neto22f144c2017-06-12 14:26:21 -04004078 }
4079 } else if (const ConstantDataSequential *CDS =
4080 dyn_cast<ConstantDataSequential>(Cst)) {
4081 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4082 std::vector<uint32_t> LiteralNum;
David Neto257c3892018-04-11 13:19:45 -04004083 const auto value = CDS->getElementAsInteger(i);
4084 assert(value <= UINT32_MAX);
4085 Ops << MkNum(static_cast<uint32_t>(value));
David Neto22f144c2017-06-12 14:26:21 -04004086 }
4087 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4088 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4089 auto Op = CV->getOperand(i);
4090
4091 uint32_t literal = 0;
4092
4093 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4094 literal = static_cast<uint32_t>(CI->getZExtValue());
4095 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4096 literal = 0xFFFFFFFFu;
4097 } else {
4098 Op->print(errs());
4099 llvm_unreachable("Unsupported element in ConstantVector!");
4100 }
4101
David Neto257c3892018-04-11 13:19:45 -04004102 Ops << MkNum(literal);
David Neto22f144c2017-06-12 14:26:21 -04004103 }
4104 } else {
4105 Cst->print(errs());
4106 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4107 }
4108 }
4109
4110 uint16_t WordCount = static_cast<uint16_t>(5 + NumElements);
4111 SPIRVInstruction *Inst =
4112 new SPIRVInstruction(WordCount, spv::OpVectorShuffle, nextID++, Ops);
4113 SPIRVInstList.push_back(Inst);
4114 break;
4115 }
4116 case Instruction::ICmp:
4117 case Instruction::FCmp: {
4118 CmpInst *CmpI = cast<CmpInst>(&I);
4119
David Netod4ca2e62017-07-06 18:47:35 -04004120 // Pointer equality is invalid.
4121 Type* ArgTy = CmpI->getOperand(0)->getType();
4122 if (isa<PointerType>(ArgTy)) {
4123 CmpI->print(errs());
4124 std::string name = I.getParent()->getParent()->getName();
4125 errs()
4126 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4127 << "in function " << name << "\n";
4128 llvm_unreachable("Pointer equality check is invalid");
4129 break;
4130 }
4131
David Neto257c3892018-04-11 13:19:45 -04004132 // Ops[0] = Result Type ID
4133 // Ops[1] = Operand 1 ID
4134 // Ops[2] = Operand 2 ID
4135 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04004136
David Neto257c3892018-04-11 13:19:45 -04004137 Ops << MkId(lookupType(CmpI->getType())) << MkId(VMap[CmpI->getOperand(0)])
4138 << MkId(VMap[CmpI->getOperand(1)]);
David Neto22f144c2017-06-12 14:26:21 -04004139
4140 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4141 SPIRVInstruction *Inst = new SPIRVInstruction(5, Opcode, nextID++, Ops);
4142 SPIRVInstList.push_back(Inst);
4143 break;
4144 }
4145 case Instruction::Br: {
4146 // Branch instrucion is deferred because it needs label's ID. Record slot's
4147 // location on SPIRVInstructionList.
4148 DeferredInsts.push_back(
4149 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4150 break;
4151 }
4152 case Instruction::Switch: {
4153 I.print(errs());
4154 llvm_unreachable("Unsupported instruction???");
4155 break;
4156 }
4157 case Instruction::IndirectBr: {
4158 I.print(errs());
4159 llvm_unreachable("Unsupported instruction???");
4160 break;
4161 }
4162 case Instruction::PHI: {
4163 // Branch instrucion is deferred because it needs label's ID. Record slot's
4164 // location on SPIRVInstructionList.
4165 DeferredInsts.push_back(
4166 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4167 break;
4168 }
4169 case Instruction::Alloca: {
4170 //
4171 // Generate OpVariable.
4172 //
4173 // Ops[0] : Result Type ID
4174 // Ops[1] : Storage Class
4175 SPIRVOperandList Ops;
4176
David Neto257c3892018-04-11 13:19:45 -04004177 Ops << MkId(lookupType(I.getType())) << MkNum(spv::StorageClassFunction);
David Neto22f144c2017-06-12 14:26:21 -04004178
4179 SPIRVInstruction *Inst =
4180 new SPIRVInstruction(4, spv::OpVariable, nextID++, Ops);
4181 SPIRVInstList.push_back(Inst);
4182 break;
4183 }
4184 case Instruction::Load: {
4185 LoadInst *LD = cast<LoadInst>(&I);
4186 //
4187 // Generate OpLoad.
4188 //
4189
David Neto0a2f98d2017-09-15 19:38:40 -04004190 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004191 uint32_t PointerID = VMap[LD->getPointerOperand()];
4192
4193 // This is a hack to work around what looks like a driver bug.
4194 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004195 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4196 // generating a load.
David Neto66cfe642018-03-24 06:13:56 -07004197 // TODO(dneto): Remove this awful hack once drivers are fixed.
David Netoa60b00b2017-09-15 16:34:09 -04004198 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004199 // Generate a bitwise-and of the original value with itself.
4200 // We should have been able to get away with just an OpCopyObject,
4201 // but we need something more complex to get past certain driver bugs.
4202 // This is ridiculous, but necessary.
4203 // TODO(dneto): Revisit this once drivers fix their bugs.
4204
4205 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004206 Ops << MkId(ResTyID) << MkId(WorkgroupSizeValueID)
4207 << MkId(WorkgroupSizeValueID);
David Neto0a2f98d2017-09-15 19:38:40 -04004208
4209 SPIRVInstruction *Inst =
4210 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4211 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004212 break;
4213 }
4214
4215 // This is the normal path. Generate a load.
4216
David Neto22f144c2017-06-12 14:26:21 -04004217 // Ops[0] = Result Type ID
4218 // Ops[1] = Pointer ID
4219 // Ops[2] ... Ops[n] = Optional Memory Access
4220 //
4221 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004222
David Neto22f144c2017-06-12 14:26:21 -04004223 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004224 Ops << MkId(ResTyID) << MkId(PointerID);
David Neto22f144c2017-06-12 14:26:21 -04004225
4226 SPIRVInstruction *Inst =
4227 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4228 SPIRVInstList.push_back(Inst);
4229 break;
4230 }
4231 case Instruction::Store: {
4232 StoreInst *ST = cast<StoreInst>(&I);
4233 //
4234 // Generate OpStore.
4235 //
4236
4237 // Ops[0] = Pointer ID
4238 // Ops[1] = Object ID
4239 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4240 //
4241 // TODO: Do we need to implement Optional Memory Access???
David Neto257c3892018-04-11 13:19:45 -04004242 SPIRVOperandList Ops;
4243 Ops << MkId(VMap[ST->getPointerOperand()])
4244 << MkId(VMap[ST->getValueOperand()]);
David Neto22f144c2017-06-12 14:26:21 -04004245
4246 SPIRVInstruction *Inst =
4247 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4248 SPIRVInstList.push_back(Inst);
4249 break;
4250 }
4251 case Instruction::AtomicCmpXchg: {
4252 I.print(errs());
4253 llvm_unreachable("Unsupported instruction???");
4254 break;
4255 }
4256 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004257 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4258
4259 spv::Op opcode;
4260
4261 switch (AtomicRMW->getOperation()) {
4262 default:
4263 I.print(errs());
4264 llvm_unreachable("Unsupported instruction???");
4265 case llvm::AtomicRMWInst::Add:
4266 opcode = spv::OpAtomicIAdd;
4267 break;
4268 case llvm::AtomicRMWInst::Sub:
4269 opcode = spv::OpAtomicISub;
4270 break;
4271 case llvm::AtomicRMWInst::Xchg:
4272 opcode = spv::OpAtomicExchange;
4273 break;
4274 case llvm::AtomicRMWInst::Min:
4275 opcode = spv::OpAtomicSMin;
4276 break;
4277 case llvm::AtomicRMWInst::Max:
4278 opcode = spv::OpAtomicSMax;
4279 break;
4280 case llvm::AtomicRMWInst::UMin:
4281 opcode = spv::OpAtomicUMin;
4282 break;
4283 case llvm::AtomicRMWInst::UMax:
4284 opcode = spv::OpAtomicUMax;
4285 break;
4286 case llvm::AtomicRMWInst::And:
4287 opcode = spv::OpAtomicAnd;
4288 break;
4289 case llvm::AtomicRMWInst::Or:
4290 opcode = spv::OpAtomicOr;
4291 break;
4292 case llvm::AtomicRMWInst::Xor:
4293 opcode = spv::OpAtomicXor;
4294 break;
4295 }
4296
4297 //
4298 // Generate OpAtomic*.
4299 //
4300 SPIRVOperandList Ops;
4301
David Neto257c3892018-04-11 13:19:45 -04004302 Ops << MkId(lookupType(I.getType()))
4303 << MkId(VMap[AtomicRMW->getPointerOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004304
4305 auto IntTy = Type::getInt32Ty(I.getContext());
Neil Henning39672102017-09-29 14:33:13 +01004306 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
David Neto257c3892018-04-11 13:19:45 -04004307 Ops << MkId(VMap[ConstantScopeDevice]);
Neil Henning39672102017-09-29 14:33:13 +01004308
4309 const auto ConstantMemorySemantics = ConstantInt::get(
4310 IntTy, spv::MemorySemanticsUniformMemoryMask |
4311 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto257c3892018-04-11 13:19:45 -04004312 Ops << MkId(VMap[ConstantMemorySemantics]);
Neil Henning39672102017-09-29 14:33:13 +01004313
David Neto257c3892018-04-11 13:19:45 -04004314 Ops << MkId(VMap[AtomicRMW->getValOperand()]);
Neil Henning39672102017-09-29 14:33:13 +01004315
4316 VMap[&I] = nextID;
4317
4318 SPIRVInstruction *Inst = new SPIRVInstruction(
4319 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4320 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004321 break;
4322 }
4323 case Instruction::Fence: {
4324 I.print(errs());
4325 llvm_unreachable("Unsupported instruction???");
4326 break;
4327 }
4328 case Instruction::Call: {
4329 CallInst *Call = dyn_cast<CallInst>(&I);
4330 Function *Callee = Call->getCalledFunction();
4331
4332 // Sampler initializers become a load of the corresponding sampler.
4333 if (Callee->getName().equals("__translate_sampler_initializer")) {
4334 // Check that the sampler map was definitely used though.
4335 if (0 == getSamplerMap().size()) {
4336 llvm_unreachable("Sampler literal in source without sampler map!");
4337 }
4338
4339 SPIRVOperandList Ops;
4340
David Neto257c3892018-04-11 13:19:45 -04004341 Ops << MkId(lookupType(SamplerTy->getPointerElementType()))
4342 << MkId(VMap[Call]);
David Neto22f144c2017-06-12 14:26:21 -04004343
4344 VMap[Call] = nextID;
4345 SPIRVInstruction *Inst =
4346 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4347 SPIRVInstList.push_back(Inst);
4348
4349 break;
4350 }
4351
4352 if (Callee->getName().startswith("spirv.atomic")) {
4353 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4354 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4355 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4356 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4357 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4358 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4359 .Case("spirv.atomic_compare_exchange",
4360 spv::OpAtomicCompareExchange)
4361 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4362 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4363 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4364 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4365 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4366 .Case("spirv.atomic_or", spv::OpAtomicOr)
4367 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4368 .Default(spv::OpNop);
4369
4370 //
4371 // Generate OpAtomic*.
4372 //
4373 SPIRVOperandList Ops;
4374
David Neto257c3892018-04-11 13:19:45 -04004375 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004376
4377 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004378 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004379 }
4380
4381 VMap[&I] = nextID;
4382
4383 SPIRVInstruction *Inst = new SPIRVInstruction(
4384 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4385 SPIRVInstList.push_back(Inst);
4386 break;
4387 }
4388
4389 if (Callee->getName().startswith("_Z3dot")) {
4390 // If the argument is a vector type, generate OpDot
4391 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4392 //
4393 // Generate OpDot.
4394 //
4395 SPIRVOperandList Ops;
4396
David Neto257c3892018-04-11 13:19:45 -04004397 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004398
4399 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004400 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004401 }
4402
4403 VMap[&I] = nextID;
4404
4405 SPIRVInstruction *Inst = new SPIRVInstruction(
4406 static_cast<uint16_t>(2 + Ops.size()), spv::OpDot, nextID++, Ops);
4407 SPIRVInstList.push_back(Inst);
4408 } else {
4409 //
4410 // Generate OpFMul.
4411 //
4412 SPIRVOperandList Ops;
4413
David Neto257c3892018-04-11 13:19:45 -04004414 Ops << MkId(lookupType(I.getType()));
David Neto22f144c2017-06-12 14:26:21 -04004415
4416 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004417 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04004418 }
4419
4420 VMap[&I] = nextID;
4421
4422 SPIRVInstruction *Inst = new SPIRVInstruction(
4423 static_cast<uint16_t>(2 + Ops.size()), spv::OpFMul, nextID++, Ops);
4424 SPIRVInstList.push_back(Inst);
4425 }
4426 break;
4427 }
4428
David Neto8505ebf2017-10-13 18:50:50 -04004429 if (Callee->getName().startswith("_Z4fmod")) {
4430 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4431 // The sign for a non-zero result is taken from x.
4432 // (Try an example.)
4433 // So translate to OpFRem
4434
4435 SPIRVOperandList Ops;
4436
David Neto257c3892018-04-11 13:19:45 -04004437 Ops << MkId(lookupType(I.getType()));
David Neto8505ebf2017-10-13 18:50:50 -04004438
4439 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
David Neto257c3892018-04-11 13:19:45 -04004440 Ops << MkId(VMap[Call->getArgOperand(i)]);
David Neto8505ebf2017-10-13 18:50:50 -04004441 }
4442
4443 VMap[&I] = nextID;
4444
4445 SPIRVInstruction *Inst = new SPIRVInstruction(
4446 static_cast<uint16_t>(2 + Ops.size()), spv::OpFRem, nextID++, Ops);
4447 SPIRVInstList.push_back(Inst);
4448 break;
4449 }
4450
David Neto22f144c2017-06-12 14:26:21 -04004451 // spirv.store_null.* intrinsics become OpStore's.
4452 if (Callee->getName().startswith("spirv.store_null")) {
4453 //
4454 // Generate OpStore.
4455 //
4456
4457 // Ops[0] = Pointer ID
4458 // Ops[1] = Object ID
4459 // Ops[2] ... Ops[n]
4460 SPIRVOperandList Ops;
4461
4462 uint32_t PointerID = VMap[Call->getArgOperand(0)];
David Neto22f144c2017-06-12 14:26:21 -04004463 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
David Neto257c3892018-04-11 13:19:45 -04004464 Ops << MkId(PointerID) << MkId(ObjectID);
David Neto22f144c2017-06-12 14:26:21 -04004465
4466 SPIRVInstruction *Inst =
4467 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4468 SPIRVInstList.push_back(Inst);
4469
4470 break;
4471 }
4472
4473 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4474 if (Callee->getName().startswith("spirv.copy_memory")) {
4475 //
4476 // Generate OpCopyMemory.
4477 //
4478
4479 // Ops[0] = Dst ID
4480 // Ops[1] = Src ID
4481 // Ops[2] = Memory Access
4482 // Ops[3] = Alignment
4483
4484 auto IsVolatile =
4485 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4486
4487 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4488 : spv::MemoryAccessMaskNone;
4489
4490 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4491
4492 auto Alignment =
4493 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4494
David Neto257c3892018-04-11 13:19:45 -04004495 SPIRVOperandList Ops;
4496 Ops << MkId(VMap[Call->getArgOperand(0)])
4497 << MkId(VMap[Call->getArgOperand(1)]) << MkNum(MemoryAccess)
4498 << MkNum(static_cast<uint32_t>(Alignment));
David Neto22f144c2017-06-12 14:26:21 -04004499
4500 SPIRVInstruction *Inst =
4501 new SPIRVInstruction(5, spv::OpCopyMemory, 0 /* No id */, Ops);
4502
4503 SPIRVInstList.push_back(Inst);
4504
4505 break;
4506 }
4507
4508 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4509 // with unit.
4510 if (Callee->getName().equals("_Z3absj") ||
4511 Callee->getName().equals("_Z3absDv2_j") ||
4512 Callee->getName().equals("_Z3absDv3_j") ||
4513 Callee->getName().equals("_Z3absDv4_j")) {
4514 VMap[&I] = VMap[Call->getOperand(0)];
4515 break;
4516 }
4517
4518 // barrier is converted to OpControlBarrier
4519 if (Callee->getName().equals("__spirv_control_barrier")) {
4520 //
4521 // Generate OpControlBarrier.
4522 //
4523 // Ops[0] = Execution Scope ID
4524 // Ops[1] = Memory Scope ID
4525 // Ops[2] = Memory Semantics ID
4526 //
4527 Value *ExecutionScope = Call->getArgOperand(0);
4528 Value *MemoryScope = Call->getArgOperand(1);
4529 Value *MemorySemantics = Call->getArgOperand(2);
4530
David Neto257c3892018-04-11 13:19:45 -04004531 SPIRVOperandList Ops;
4532 Ops << MkId(VMap[ExecutionScope]) << MkId(VMap[MemoryScope])
4533 << MkId(VMap[MemorySemantics]);
David Neto22f144c2017-06-12 14:26:21 -04004534
4535 SPIRVInstList.push_back(
4536 new SPIRVInstruction(4, spv::OpControlBarrier, 0 /* No id */, Ops));
4537 break;
4538 }
4539
4540 // memory barrier is converted to OpMemoryBarrier
4541 if (Callee->getName().equals("__spirv_memory_barrier")) {
4542 //
4543 // Generate OpMemoryBarrier.
4544 //
4545 // Ops[0] = Memory Scope ID
4546 // Ops[1] = Memory Semantics ID
4547 //
4548 SPIRVOperandList Ops;
4549
David Neto257c3892018-04-11 13:19:45 -04004550 uint32_t MemoryScopeID = VMap[Call->getArgOperand(0)];
4551 uint32_t MemorySemanticsID = VMap[Call->getArgOperand(1)];
David Neto22f144c2017-06-12 14:26:21 -04004552
David Neto257c3892018-04-11 13:19:45 -04004553 Ops << MkId(MemoryScopeID) << MkId(MemorySemanticsID);
David Neto22f144c2017-06-12 14:26:21 -04004554
4555 SPIRVInstruction *Inst =
4556 new SPIRVInstruction(3, spv::OpMemoryBarrier, 0 /* No id */, Ops);
4557 SPIRVInstList.push_back(Inst);
4558 break;
4559 }
4560
4561 // isinf is converted to OpIsInf
4562 if (Callee->getName().equals("__spirv_isinff") ||
4563 Callee->getName().equals("__spirv_isinfDv2_f") ||
4564 Callee->getName().equals("__spirv_isinfDv3_f") ||
4565 Callee->getName().equals("__spirv_isinfDv4_f")) {
4566 //
4567 // Generate OpIsInf.
4568 //
4569 // Ops[0] = Result Type ID
4570 // Ops[1] = X ID
4571 //
4572 SPIRVOperandList Ops;
4573
David Neto257c3892018-04-11 13:19:45 -04004574 Ops << MkId(lookupType(I.getType()))
4575 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004576
4577 VMap[&I] = nextID;
4578
4579 SPIRVInstruction *Inst =
4580 new SPIRVInstruction(4, spv::OpIsInf, nextID++, Ops);
4581 SPIRVInstList.push_back(Inst);
4582 break;
4583 }
4584
4585 // isnan is converted to OpIsNan
4586 if (Callee->getName().equals("__spirv_isnanf") ||
4587 Callee->getName().equals("__spirv_isnanDv2_f") ||
4588 Callee->getName().equals("__spirv_isnanDv3_f") ||
4589 Callee->getName().equals("__spirv_isnanDv4_f")) {
4590 //
4591 // Generate OpIsInf.
4592 //
4593 // Ops[0] = Result Type ID
4594 // Ops[1] = X ID
4595 //
4596 SPIRVOperandList Ops;
4597
David Neto257c3892018-04-11 13:19:45 -04004598 Ops << MkId(lookupType(I.getType()))
4599 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004600
4601 VMap[&I] = nextID;
4602
4603 SPIRVInstruction *Inst =
4604 new SPIRVInstruction(4, spv::OpIsNan, nextID++, Ops);
4605 SPIRVInstList.push_back(Inst);
4606 break;
4607 }
4608
4609 // all is converted to OpAll
4610 if (Callee->getName().equals("__spirv_allDv2_i") ||
4611 Callee->getName().equals("__spirv_allDv3_i") ||
4612 Callee->getName().equals("__spirv_allDv4_i")) {
4613 //
4614 // Generate OpAll.
4615 //
4616 // Ops[0] = Result Type ID
4617 // Ops[1] = Vector ID
4618 //
4619 SPIRVOperandList Ops;
4620
David Neto257c3892018-04-11 13:19:45 -04004621 Ops << MkId(lookupType(I.getType()))
4622 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004623
4624 VMap[&I] = nextID;
4625
4626 SPIRVInstruction *Inst =
4627 new SPIRVInstruction(4, spv::OpAll, nextID++, Ops);
4628 SPIRVInstList.push_back(Inst);
4629 break;
4630 }
4631
4632 // any is converted to OpAny
4633 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4634 Callee->getName().equals("__spirv_anyDv3_i") ||
4635 Callee->getName().equals("__spirv_anyDv4_i")) {
4636 //
4637 // Generate OpAny.
4638 //
4639 // Ops[0] = Result Type ID
4640 // Ops[1] = Vector ID
4641 //
4642 SPIRVOperandList Ops;
4643
David Neto257c3892018-04-11 13:19:45 -04004644 Ops << MkId(lookupType(I.getType()))
4645 << MkId(VMap[Call->getArgOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004646
4647 VMap[&I] = nextID;
4648
4649 SPIRVInstruction *Inst =
4650 new SPIRVInstruction(4, spv::OpAny, nextID++, Ops);
4651 SPIRVInstList.push_back(Inst);
4652 break;
4653 }
4654
4655 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4656 // Additionally, OpTypeSampledImage is generated.
4657 if (Callee->getName().equals(
4658 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4659 Callee->getName().equals(
4660 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4661 //
4662 // Generate OpSampledImage.
4663 //
4664 // Ops[0] = Result Type ID
4665 // Ops[1] = Image ID
4666 // Ops[2] = Sampler ID
4667 //
4668 SPIRVOperandList Ops;
4669
4670 Value *Image = Call->getArgOperand(0);
4671 Value *Sampler = Call->getArgOperand(1);
4672 Value *Coordinate = Call->getArgOperand(2);
4673
4674 TypeMapType &OpImageTypeMap = getImageTypeMap();
4675 Type *ImageTy = Image->getType()->getPointerElementType();
4676 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
David Neto22f144c2017-06-12 14:26:21 -04004677 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004678 uint32_t SamplerID = VMap[Sampler];
David Neto257c3892018-04-11 13:19:45 -04004679
4680 Ops << MkId(ImageTyID) << MkId(ImageID) << MkId(SamplerID);
David Neto22f144c2017-06-12 14:26:21 -04004681
4682 uint32_t SampledImageID = nextID;
4683
4684 SPIRVInstruction *Inst =
4685 new SPIRVInstruction(5, spv::OpSampledImage, nextID++, Ops);
4686 SPIRVInstList.push_back(Inst);
4687
4688 //
4689 // Generate OpImageSampleExplicitLod.
4690 //
4691 // Ops[0] = Result Type ID
4692 // Ops[1] = Sampled Image ID
4693 // Ops[2] = Coordinate ID
4694 // Ops[3] = Image Operands Type ID
4695 // Ops[4] ... Ops[n] = Operands ID
4696 //
4697 Ops.clear();
4698
David Neto257c3892018-04-11 13:19:45 -04004699 Ops << MkId(lookupType(Call->getType())) << MkId(SampledImageID)
4700 << MkId(VMap[Coordinate]) << MkNum(spv::ImageOperandsLodMask);
David Neto22f144c2017-06-12 14:26:21 -04004701
4702 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
David Neto257c3892018-04-11 13:19:45 -04004703 Ops << MkId(VMap[CstFP0]);
David Neto22f144c2017-06-12 14:26:21 -04004704
4705 VMap[&I] = nextID;
4706
4707 Inst =
4708 new SPIRVInstruction(7, spv::OpImageSampleExplicitLod, nextID++, Ops);
4709 SPIRVInstList.push_back(Inst);
4710 break;
4711 }
4712
4713 // write_imagef is mapped to OpImageWrite.
4714 if (Callee->getName().equals(
4715 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4716 Callee->getName().equals(
4717 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4718 //
4719 // Generate OpImageWrite.
4720 //
4721 // Ops[0] = Image ID
4722 // Ops[1] = Coordinate ID
4723 // Ops[2] = Texel ID
4724 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4725 // Ops[4] ... Ops[n] = (Optional) Operands ID
4726 //
4727 SPIRVOperandList Ops;
4728
4729 Value *Image = Call->getArgOperand(0);
4730 Value *Coordinate = Call->getArgOperand(1);
4731 Value *Texel = Call->getArgOperand(2);
4732
4733 uint32_t ImageID = VMap[Image];
David Neto22f144c2017-06-12 14:26:21 -04004734 uint32_t CoordinateID = VMap[Coordinate];
David Neto22f144c2017-06-12 14:26:21 -04004735 uint32_t TexelID = VMap[Texel];
David Neto257c3892018-04-11 13:19:45 -04004736 Ops << MkId(ImageID) << MkId(CoordinateID) << MkId(TexelID);
David Neto22f144c2017-06-12 14:26:21 -04004737
4738 SPIRVInstruction *Inst =
4739 new SPIRVInstruction(4, spv::OpImageWrite, 0 /* No id */, Ops);
4740 SPIRVInstList.push_back(Inst);
4741 break;
4742 }
4743
David Neto5c22a252018-03-15 16:07:41 -04004744 // get_image_width is mapped to OpImageQuerySize
4745 if (Callee->getName().equals("_Z15get_image_width14ocl_image2d_ro") ||
4746 Callee->getName().equals("_Z15get_image_width14ocl_image2d_wo") ||
4747 Callee->getName().equals("_Z16get_image_height14ocl_image2d_ro") ||
4748 Callee->getName().equals("_Z16get_image_height14ocl_image2d_wo")) {
4749 //
4750 // Generate OpImageQuerySize, then pull out the right component.
4751 // Assume 2D image for now.
4752 //
4753 // Ops[0] = Image ID
4754 //
4755 // %sizes = OpImageQuerySizes %uint2 %im
4756 // %result = OpCompositeExtract %uint %sizes 0-or-1
4757 SPIRVOperandList Ops;
4758
4759 // Implement:
4760 // %sizes = OpImageQuerySizes %uint2 %im
4761 uint32_t SizesTypeID =
4762 TypeMap[VectorType::get(Type::getInt32Ty(Context), 2)];
David Neto5c22a252018-03-15 16:07:41 -04004763 Value *Image = Call->getArgOperand(0);
4764 uint32_t ImageID = VMap[Image];
David Neto257c3892018-04-11 13:19:45 -04004765 Ops << MkId(SizesTypeID) << MkId(ImageID);
David Neto5c22a252018-03-15 16:07:41 -04004766
4767 uint32_t SizesID = nextID++;
4768 SPIRVInstruction *QueryInst =
4769 new SPIRVInstruction(4, spv::OpImageQuerySize, SizesID, Ops);
4770 SPIRVInstList.push_back(QueryInst);
4771
4772 // Reset value map entry since we generated an intermediate instruction.
4773 VMap[&I] = nextID;
4774
4775 // Implement:
4776 // %result = OpCompositeExtract %uint %sizes 0-or-1
4777 Ops.clear();
David Neto257c3892018-04-11 13:19:45 -04004778 Ops << MkId(TypeMap[I.getType()]) << MkId(SizesID);
David Neto5c22a252018-03-15 16:07:41 -04004779
4780 uint32_t component = Callee->getName().contains("height") ? 1 : 0;
David Neto257c3892018-04-11 13:19:45 -04004781 Ops << MkNum(component);
David Neto5c22a252018-03-15 16:07:41 -04004782
4783 SPIRVInstruction *Inst =
4784 new SPIRVInstruction(5, spv::OpCompositeExtract, nextID++, Ops);
4785 SPIRVInstList.push_back(Inst);
4786 break;
4787 }
4788
David Neto22f144c2017-06-12 14:26:21 -04004789 // Call instrucion is deferred because it needs function's ID. Record
4790 // slot's location on SPIRVInstructionList.
4791 DeferredInsts.push_back(
4792 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4793
David Neto3fbb4072017-10-16 11:28:14 -04004794 // Check whether the implementation of this call uses an extended
4795 // instruction plus one more value-producing instruction. If so, then
4796 // reserve the id for the extra value-producing slot.
4797 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
4798 if (EInst != kGlslExtInstBad) {
4799 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04004800 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04004801 VMap[&I] = nextID;
4802 nextID++;
4803 }
4804 break;
4805 }
4806 case Instruction::Ret: {
4807 unsigned NumOps = I.getNumOperands();
4808 if (NumOps == 0) {
4809 //
4810 // Generate OpReturn.
4811 //
4812
4813 // Empty Ops
4814 SPIRVOperandList Ops;
4815 SPIRVInstruction *Inst =
4816 new SPIRVInstruction(1, spv::OpReturn, 0 /* No id */, Ops);
4817 SPIRVInstList.push_back(Inst);
4818 } else {
4819 //
4820 // Generate OpReturnValue.
4821 //
4822
4823 // Ops[0] = Return Value ID
4824 SPIRVOperandList Ops;
David Neto257c3892018-04-11 13:19:45 -04004825
4826 Ops << MkId(VMap[I.getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04004827
4828 SPIRVInstruction *Inst =
4829 new SPIRVInstruction(2, spv::OpReturnValue, 0 /* No id */, Ops);
4830 SPIRVInstList.push_back(Inst);
4831 break;
4832 }
4833 break;
4834 }
4835 }
4836}
4837
4838void SPIRVProducerPass::GenerateFuncEpilogue() {
4839 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4840
4841 //
4842 // Generate OpFunctionEnd
4843 //
4844
4845 // Empty Ops
4846 SPIRVOperandList Ops;
4847 SPIRVInstruction *Inst =
4848 new SPIRVInstruction(1, spv::OpFunctionEnd, 0 /* No id */, Ops);
4849 SPIRVInstList.push_back(Inst);
4850}
4851
4852bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4853 LLVMContext &Context = Ty->getContext();
4854 if (Ty->isVectorTy()) {
4855 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4856 Ty->getVectorNumElements() == 4) {
4857 return true;
4858 }
4859 }
4860
4861 return false;
4862}
4863
David Neto257c3892018-04-11 13:19:45 -04004864uint32_t SPIRVProducerPass::GetI32Zero() {
4865 if (0 == constant_i32_zero_id_) {
4866 llvm_unreachable("Requesting a 32-bit integer constant but it is not "
4867 "defined in the SPIR-V module");
4868 }
4869 return constant_i32_zero_id_;
4870}
4871
David Neto22f144c2017-06-12 14:26:21 -04004872void SPIRVProducerPass::HandleDeferredInstruction() {
4873 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4874 ValueMapType &VMap = getValueMap();
4875 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4876
4877 for (auto DeferredInst = DeferredInsts.rbegin();
4878 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4879 Value *Inst = std::get<0>(*DeferredInst);
4880 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4881 if (InsertPoint != SPIRVInstList.end()) {
4882 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4883 ++InsertPoint;
4884 }
4885 }
4886
4887 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4888 // Check whether basic block, which has this branch instruction, is loop
4889 // header or not. If it is loop header, generate OpLoopMerge and
4890 // OpBranchConditional.
4891 Function *Func = Br->getParent()->getParent();
4892 DominatorTree &DT =
4893 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4894 const LoopInfo &LI =
4895 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4896
4897 BasicBlock *BrBB = Br->getParent();
4898 if (LI.isLoopHeader(BrBB)) {
4899 Value *ContinueBB = nullptr;
4900 Value *MergeBB = nullptr;
4901
4902 Loop *L = LI.getLoopFor(BrBB);
4903 MergeBB = L->getExitBlock();
4904 if (!MergeBB) {
4905 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4906 // has regions with single entry/exit. As a result, loop should not
4907 // have multiple exits.
4908 llvm_unreachable("Loop has multiple exits???");
4909 }
4910
4911 if (L->isLoopLatch(BrBB)) {
4912 ContinueBB = BrBB;
4913 } else {
4914 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4915 // block.
4916 BasicBlock *Header = L->getHeader();
4917 BasicBlock *Latch = L->getLoopLatch();
4918 for (BasicBlock *BB : L->blocks()) {
4919 if (BB == Header) {
4920 continue;
4921 }
4922
4923 // Check whether block dominates block with back-edge.
4924 if (DT.dominates(BB, Latch)) {
4925 ContinueBB = BB;
4926 }
4927 }
4928
4929 if (!ContinueBB) {
4930 llvm_unreachable("Wrong continue block from loop");
4931 }
4932 }
4933
4934 //
4935 // Generate OpLoopMerge.
4936 //
4937 // Ops[0] = Merge Block ID
4938 // Ops[1] = Continue Target ID
4939 // Ops[2] = Selection Control
4940 SPIRVOperandList Ops;
4941
4942 // StructurizeCFG pass already manipulated CFG. Just use false block of
4943 // branch instruction as merge block.
4944 uint32_t MergeBBID = VMap[MergeBB];
David Neto22f144c2017-06-12 14:26:21 -04004945 uint32_t ContinueBBID = VMap[ContinueBB];
David Neto257c3892018-04-11 13:19:45 -04004946 Ops << MkId(MergeBBID) << MkId(ContinueBBID)
4947 << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004948
4949 SPIRVInstruction *MergeInst =
4950 new SPIRVInstruction(4, spv::OpLoopMerge, 0 /* No id */, Ops);
4951 SPIRVInstList.insert(InsertPoint, MergeInst);
4952
4953 } else if (Br->isConditional()) {
4954 bool HasBackEdge = false;
4955
4956 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4957 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4958 HasBackEdge = true;
4959 }
4960 }
4961 if (!HasBackEdge) {
4962 //
4963 // Generate OpSelectionMerge.
4964 //
4965 // Ops[0] = Merge Block ID
4966 // Ops[1] = Selection Control
4967 SPIRVOperandList Ops;
4968
4969 // StructurizeCFG pass already manipulated CFG. Just use false block
4970 // of branch instruction as merge block.
4971 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004972 Ops << MkId(MergeBBID) << MkNum(spv::SelectionControlMaskNone);
David Neto22f144c2017-06-12 14:26:21 -04004973
4974 SPIRVInstruction *MergeInst = new SPIRVInstruction(
4975 3, spv::OpSelectionMerge, 0 /* No id */, Ops);
4976 SPIRVInstList.insert(InsertPoint, MergeInst);
4977 }
4978 }
4979
4980 if (Br->isConditional()) {
4981 //
4982 // Generate OpBranchConditional.
4983 //
4984 // Ops[0] = Condition ID
4985 // Ops[1] = True Label ID
4986 // Ops[2] = False Label ID
4987 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4988 SPIRVOperandList Ops;
4989
4990 uint32_t CondID = VMap[Br->getCondition()];
David Neto22f144c2017-06-12 14:26:21 -04004991 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
David Neto22f144c2017-06-12 14:26:21 -04004992 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
David Neto257c3892018-04-11 13:19:45 -04004993
4994 Ops << MkId(CondID) << MkId(TrueBBID) << MkId(FalseBBID);
David Neto22f144c2017-06-12 14:26:21 -04004995
4996 SPIRVInstruction *BrInst = new SPIRVInstruction(
4997 4, spv::OpBranchConditional, 0 /* No id */, Ops);
4998 SPIRVInstList.insert(InsertPoint, BrInst);
4999 } else {
5000 //
5001 // Generate OpBranch.
5002 //
5003 // Ops[0] = Target Label ID
5004 SPIRVOperandList Ops;
5005
5006 uint32_t TargetID = VMap[Br->getSuccessor(0)];
David Neto257c3892018-04-11 13:19:45 -04005007 Ops << MkId(TargetID);
David Neto22f144c2017-06-12 14:26:21 -04005008
5009 SPIRVInstList.insert(
5010 InsertPoint,
5011 new SPIRVInstruction(2, spv::OpBranch, 0 /* No id */, Ops));
5012 }
5013 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5014 //
5015 // Generate OpPhi.
5016 //
5017 // Ops[0] = Result Type ID
5018 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5019 SPIRVOperandList Ops;
5020
David Neto257c3892018-04-11 13:19:45 -04005021 Ops << MkId(lookupType(PHI->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005022
5023 uint16_t WordCount = 3;
5024 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5025 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
David Neto22f144c2017-06-12 14:26:21 -04005026 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
David Neto257c3892018-04-11 13:19:45 -04005027 Ops << MkId(VarID) << MkId(ParentID);
David Neto22f144c2017-06-12 14:26:21 -04005028 WordCount += 2;
5029 }
5030
5031 SPIRVInstList.insert(
5032 InsertPoint, new SPIRVInstruction(WordCount, spv::OpPhi,
5033 std::get<2>(*DeferredInst), Ops));
5034 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5035 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005036 auto callee_name = Callee->getName();
5037 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005038
5039 if (EInst) {
5040 uint32_t &ExtInstImportID = getOpExtInstImportID();
5041
5042 //
5043 // Generate OpExtInst.
5044 //
5045
5046 // Ops[0] = Result Type ID
5047 // Ops[1] = Set ID (OpExtInstImport ID)
5048 // Ops[2] = Instruction Number (Literal Number)
5049 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5050 SPIRVOperandList Ops;
5051
David Neto257c3892018-04-11 13:19:45 -04005052 Ops << MkId(lookupType(Call->getType())) << MkId(ExtInstImportID) << MkNum(EInst);
David Neto22f144c2017-06-12 14:26:21 -04005053
5054 uint16_t WordCount = 5;
5055
5056 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5057 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005058 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005059 WordCount++;
5060 }
5061
5062 SPIRVInstruction *ExtInst = new SPIRVInstruction(
5063 WordCount, spv::OpExtInst, std::get<2>(*DeferredInst), Ops);
5064 SPIRVInstList.insert(InsertPoint, ExtInst);
5065
David Neto3fbb4072017-10-16 11:28:14 -04005066 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5067 if (IndirectExtInst != kGlslExtInstBad) {
5068 // Generate one more instruction that uses the result of the extended
5069 // instruction. Its result id is one more than the id of the
5070 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005071 LLVMContext &Context =
5072 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005073
David Neto3fbb4072017-10-16 11:28:14 -04005074 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5075 &VMap, &SPIRVInstList, &InsertPoint](
5076 spv::Op opcode, Constant *constant) {
5077 //
5078 // Generate instruction like:
5079 // result = opcode constant <extinst-result>
5080 //
5081 // Ops[0] = Result Type ID
5082 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5083 // Ops[2] = Operand 1 ;; the result of the extended instruction
5084 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005085
David Neto3fbb4072017-10-16 11:28:14 -04005086 Type *resultTy = Call->getType();
David Neto257c3892018-04-11 13:19:45 -04005087 Ops << MkId(lookupType(resultTy));
David Neto3fbb4072017-10-16 11:28:14 -04005088
5089 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5090 constant = ConstantVector::getSplat(
5091 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5092 }
David Neto257c3892018-04-11 13:19:45 -04005093 Ops << MkId(VMap[constant]) << MkId(std::get<2>(*DeferredInst));
David Neto3fbb4072017-10-16 11:28:14 -04005094
5095 SPIRVInstList.insert(
5096 InsertPoint,
5097 new SPIRVInstruction(5, opcode, std::get<2>(*DeferredInst) + 1,
5098 Ops));
5099 };
5100
5101 switch (IndirectExtInst) {
5102 case glsl::ExtInstFindUMsb: // Implementing clz
5103 generate_extra_inst(
5104 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5105 break;
5106 case glsl::ExtInstAcos: // Implementing acospi
5107 case glsl::ExtInstAsin: // Implementing asinpi
5108 case glsl::ExtInstAtan2: // Implementing atan2pi
5109 generate_extra_inst(
5110 spv::OpFMul,
5111 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5112 break;
5113
5114 default:
5115 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005116 }
David Neto22f144c2017-06-12 14:26:21 -04005117 }
David Neto3fbb4072017-10-16 11:28:14 -04005118
David Neto22f144c2017-06-12 14:26:21 -04005119 } else if (Callee->getName().equals("_Z8popcounti") ||
5120 Callee->getName().equals("_Z8popcountj") ||
5121 Callee->getName().equals("_Z8popcountDv2_i") ||
5122 Callee->getName().equals("_Z8popcountDv3_i") ||
5123 Callee->getName().equals("_Z8popcountDv4_i") ||
5124 Callee->getName().equals("_Z8popcountDv2_j") ||
5125 Callee->getName().equals("_Z8popcountDv3_j") ||
5126 Callee->getName().equals("_Z8popcountDv4_j")) {
5127 //
5128 // Generate OpBitCount
5129 //
5130 // Ops[0] = Result Type ID
5131 // Ops[1] = Base ID
David Neto257c3892018-04-11 13:19:45 -04005132 SPIRVOperandList Ops;
5133 Ops << MkId(lookupType(Call->getType()))
5134 << MkId(VMap[Call->getOperand(0)]);
David Neto22f144c2017-06-12 14:26:21 -04005135
5136 SPIRVInstList.insert(
5137 InsertPoint, new SPIRVInstruction(4, spv::OpBitCount,
5138 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005139
5140 } else if (Callee->getName().startswith(kCompositeConstructFunctionPrefix)) {
5141
5142 // Generate an OpCompositeConstruct
5143 SPIRVOperandList Ops;
5144
5145 // The result type.
David Neto257c3892018-04-11 13:19:45 -04005146 Ops << MkId(lookupType(Call->getType()));
David Netoab03f432017-11-03 17:00:44 -04005147
5148 for (Use &use : Call->arg_operands()) {
David Neto257c3892018-04-11 13:19:45 -04005149 Value *val = use.get();
5150 Ops << MkId(VMap[use.get()]);
David Netoab03f432017-11-03 17:00:44 -04005151 }
5152
5153 SPIRVInstList.insert(
5154 InsertPoint,
5155 new SPIRVInstruction(2 + Ops.size(), spv::OpCompositeConstruct,
5156 std::get<2>(*DeferredInst), Ops));
5157
David Neto22f144c2017-06-12 14:26:21 -04005158 } else {
5159 //
5160 // Generate OpFunctionCall.
5161 //
5162
5163 // Ops[0] = Result Type ID
5164 // Ops[1] = Callee Function ID
5165 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5166 SPIRVOperandList Ops;
5167
David Neto257c3892018-04-11 13:19:45 -04005168 Ops << MkId( lookupType(Call->getType()));
David Neto22f144c2017-06-12 14:26:21 -04005169
5170 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005171 if (CalleeID == 0) {
5172 errs() << "Can't translate function call. Missing builtin? "
5173 << Callee->getName() << " in: " << *Call << "\n";
5174 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5175 // causes an infinite loop. Instead, go ahead and generate
5176 // the bad function call. A validator will catch the 0-Id.
5177 // llvm_unreachable("Can't translate function call");
5178 }
David Neto22f144c2017-06-12 14:26:21 -04005179
David Neto257c3892018-04-11 13:19:45 -04005180 Ops << MkId(CalleeID);
David Neto22f144c2017-06-12 14:26:21 -04005181
5182 uint16_t WordCount = 4;
5183
5184 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5185 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
David Neto257c3892018-04-11 13:19:45 -04005186 Ops << MkId(VMap[Call->getOperand(i)]);
David Neto22f144c2017-06-12 14:26:21 -04005187 WordCount++;
5188 }
5189
5190 SPIRVInstruction *CallInst = new SPIRVInstruction(
5191 WordCount, spv::OpFunctionCall, std::get<2>(*DeferredInst), Ops);
5192 SPIRVInstList.insert(InsertPoint, CallInst);
5193 }
5194 }
5195 }
5196}
5197
David Neto1a1a0582017-07-07 12:01:44 -04005198void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
David Netoc6f3ab22018-04-06 18:02:31 -04005199 if (getTypesNeedingArrayStride().empty() && LocalArgs.empty()) {
David Neto1a1a0582017-07-07 12:01:44 -04005200 return;
David Netoc6f3ab22018-04-06 18:02:31 -04005201 }
David Neto1a1a0582017-07-07 12:01:44 -04005202
5203 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005204
5205 // Find an iterator pointing just past the last decoration.
5206 bool seen_decorations = false;
5207 auto DecoInsertPoint =
5208 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5209 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5210 const bool is_decoration =
5211 Inst->getOpcode() == spv::OpDecorate ||
5212 Inst->getOpcode() == spv::OpMemberDecorate;
5213 if (is_decoration) {
5214 seen_decorations = true;
5215 return false;
5216 } else {
5217 return seen_decorations;
5218 }
5219 });
5220
David Netoc6f3ab22018-04-06 18:02:31 -04005221 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5222 // instructions we generated earlier.
David Neto85082642018-03-24 06:55:20 -07005223 for (auto *type : getTypesNeedingArrayStride()) {
5224 Type *elemTy = nullptr;
5225 if (auto *ptrTy = dyn_cast<PointerType>(type)) {
5226 elemTy = ptrTy->getElementType();
5227 } else if (auto* arrayTy = dyn_cast<ArrayType>(type)) {
5228 elemTy = arrayTy->getArrayElementType();
5229 } else if (auto* seqTy = dyn_cast<SequentialType>(type)) {
5230 elemTy = seqTy->getSequentialElementType();
5231 } else {
5232 errs() << "Unhandled strided type " << *type << "\n";
5233 llvm_unreachable("Unhandled strided type");
5234 }
David Neto1a1a0582017-07-07 12:01:44 -04005235
5236 // Ops[0] = Target ID
5237 // Ops[1] = Decoration (ArrayStride)
5238 // Ops[2] = Stride number (Literal Number)
5239 SPIRVOperandList Ops;
5240
David Neto85082642018-03-24 06:55:20 -07005241 // Same as DL.getIndexedOffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005242 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto257c3892018-04-11 13:19:45 -04005243
5244 Ops << MkId(lookupType(type)) << MkNum(spv::DecorationArrayStride)
5245 << MkNum(stride);
David Neto1a1a0582017-07-07 12:01:44 -04005246
5247 SPIRVInstruction *DecoInst =
5248 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
5249 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5250 }
David Netoc6f3ab22018-04-06 18:02:31 -04005251
5252 // Emit SpecId decorations targeting the array size value.
5253 for (const Argument *arg : LocalArgs) {
5254 const LocalArgInfo &arg_info = LocalArgMap[arg];
5255 SPIRVOperandList Ops;
5256 Ops << MkId(arg_info.array_size_id) << MkNum(spv::DecorationSpecId)
5257 << MkNum(arg_info.spec_id);
5258 SPIRVInstList.insert(DecoInsertPoint,
5259 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops));
5260 }
David Neto1a1a0582017-07-07 12:01:44 -04005261}
5262
David Neto22f144c2017-06-12 14:26:21 -04005263glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5264 return StringSwitch<glsl::ExtInst>(Name)
5265 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5266 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5267 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5268 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5269 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5270 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5271 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5272 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5273 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5274 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5275 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5276 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5277 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5278 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5279 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5280 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005281 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5282 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5283 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5284 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5285 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5286 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5287 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5288 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5289 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5290 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5291 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5292 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5293 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5294 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5295 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5296 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5297 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5298 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5299 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5300 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5301 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5302 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5303 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5304 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5305 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5306 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5307 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5308 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5309 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5310 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5311 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5312 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5313 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5314 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5315 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5316 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5317 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5318 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5319 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5320 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5321 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5322 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5323 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5324 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5325 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5326 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5327 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5328 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5329 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5330 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5331 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5332 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5333 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5334 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5335 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5336 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5337 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5338 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5339 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5340 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5341 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5342 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5343 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5344 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5345 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5346 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5347 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5348 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5349 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5350 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5351 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5352 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5353 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5354 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5355 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5356 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5357 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5358 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5359 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5360 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005361 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005362 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5363 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5364 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5365 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5366 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005367 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5368 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5369 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5370 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005371 .Default(kGlslExtInstBad);
5372}
5373
5374glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5375 // Check indirect cases.
5376 return StringSwitch<glsl::ExtInst>(Name)
5377 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5378 // Use exact match on float arg because these need a multiply
5379 // of a constant of the right floating point type.
5380 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5381 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5382 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5383 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5384 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5385 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5386 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5387 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5388 .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();
5966 Word |= Inst->getWordCount() << 16;
5967 WriteOneWord(Word);
5968}
5969
5970void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5971 SPIRVOperandType OpTy = Op->getType();
5972 switch (OpTy) {
5973 default: {
5974 llvm_unreachable("Unsupported SPIRV Operand Type???");
5975 break;
5976 }
5977 case SPIRVOperandType::NUMBERID: {
5978 WriteOneWord(Op->getNumID());
5979 break;
5980 }
5981 case SPIRVOperandType::LITERAL_STRING: {
5982 std::string Str = Op->getLiteralStr();
5983 const char *Data = Str.c_str();
5984 size_t WordSize = Str.size() / 4;
5985 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5986 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5987 }
5988
5989 uint32_t Remainder = Str.size() % 4;
5990 uint32_t LastWord = 0;
5991 if (Remainder) {
5992 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5993 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5994 }
5995 }
5996
5997 WriteOneWord(LastWord);
5998 break;
5999 }
6000 case SPIRVOperandType::LITERAL_INTEGER:
6001 case SPIRVOperandType::LITERAL_FLOAT: {
6002 auto LiteralNum = Op->getLiteralNum();
6003 // TODO: Handle LiteranNum carefully.
6004 for (auto Word : LiteralNum) {
6005 WriteOneWord(Word);
6006 }
6007 break;
6008 }
6009 }
6010}
6011
6012void SPIRVProducerPass::WriteSPIRVBinary() {
6013 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6014
6015 for (auto Inst : SPIRVInstList) {
David Netoc6f3ab22018-04-06 18:02:31 -04006016 SPIRVOperandList Ops{Inst->getOperands()};
David Neto22f144c2017-06-12 14:26:21 -04006017 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6018
6019 switch (Opcode) {
6020 default: {
David Neto5c22a252018-03-15 16:07:41 -04006021 errs() << "Unsupported SPIR-V instruction opcode " << int(Opcode) << "\n";
David Neto22f144c2017-06-12 14:26:21 -04006022 llvm_unreachable("Unsupported SPIRV instruction");
6023 break;
6024 }
6025 case spv::OpCapability:
6026 case spv::OpExtension:
6027 case spv::OpMemoryModel:
6028 case spv::OpEntryPoint:
6029 case spv::OpExecutionMode:
6030 case spv::OpSource:
6031 case spv::OpDecorate:
6032 case spv::OpMemberDecorate:
6033 case spv::OpBranch:
6034 case spv::OpBranchConditional:
6035 case spv::OpSelectionMerge:
6036 case spv::OpLoopMerge:
6037 case spv::OpStore:
6038 case spv::OpImageWrite:
6039 case spv::OpReturnValue:
6040 case spv::OpControlBarrier:
6041 case spv::OpMemoryBarrier:
6042 case spv::OpReturn:
6043 case spv::OpFunctionEnd:
6044 case spv::OpCopyMemory: {
6045 WriteWordCountAndOpcode(Inst);
6046 for (uint32_t i = 0; i < Ops.size(); i++) {
6047 WriteOperand(Ops[i]);
6048 }
6049 break;
6050 }
6051 case spv::OpTypeBool:
6052 case spv::OpTypeVoid:
6053 case spv::OpTypeSampler:
6054 case spv::OpLabel:
6055 case spv::OpExtInstImport:
6056 case spv::OpTypePointer:
6057 case spv::OpTypeRuntimeArray:
6058 case spv::OpTypeStruct:
6059 case spv::OpTypeImage:
6060 case spv::OpTypeSampledImage:
6061 case spv::OpTypeInt:
6062 case spv::OpTypeFloat:
6063 case spv::OpTypeArray:
6064 case spv::OpTypeVector:
6065 case spv::OpTypeFunction: {
6066 WriteWordCountAndOpcode(Inst);
6067 WriteResultID(Inst);
6068 for (uint32_t i = 0; i < Ops.size(); i++) {
6069 WriteOperand(Ops[i]);
6070 }
6071 break;
6072 }
6073 case spv::OpFunction:
6074 case spv::OpFunctionParameter:
6075 case spv::OpAccessChain:
6076 case spv::OpPtrAccessChain:
6077 case spv::OpInBoundsAccessChain:
6078 case spv::OpUConvert:
6079 case spv::OpSConvert:
6080 case spv::OpConvertFToU:
6081 case spv::OpConvertFToS:
6082 case spv::OpConvertUToF:
6083 case spv::OpConvertSToF:
6084 case spv::OpFConvert:
6085 case spv::OpConvertPtrToU:
6086 case spv::OpConvertUToPtr:
6087 case spv::OpBitcast:
6088 case spv::OpIAdd:
6089 case spv::OpFAdd:
6090 case spv::OpISub:
6091 case spv::OpFSub:
6092 case spv::OpIMul:
6093 case spv::OpFMul:
6094 case spv::OpUDiv:
6095 case spv::OpSDiv:
6096 case spv::OpFDiv:
6097 case spv::OpUMod:
6098 case spv::OpSRem:
6099 case spv::OpFRem:
6100 case spv::OpBitwiseOr:
6101 case spv::OpBitwiseXor:
6102 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006103 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006104 case spv::OpShiftLeftLogical:
6105 case spv::OpShiftRightLogical:
6106 case spv::OpShiftRightArithmetic:
6107 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006108 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006109 case spv::OpCompositeExtract:
6110 case spv::OpVectorExtractDynamic:
6111 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006112 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006113 case spv::OpVectorInsertDynamic:
6114 case spv::OpVectorShuffle:
6115 case spv::OpIEqual:
6116 case spv::OpINotEqual:
6117 case spv::OpUGreaterThan:
6118 case spv::OpUGreaterThanEqual:
6119 case spv::OpULessThan:
6120 case spv::OpULessThanEqual:
6121 case spv::OpSGreaterThan:
6122 case spv::OpSGreaterThanEqual:
6123 case spv::OpSLessThan:
6124 case spv::OpSLessThanEqual:
6125 case spv::OpFOrdEqual:
6126 case spv::OpFOrdGreaterThan:
6127 case spv::OpFOrdGreaterThanEqual:
6128 case spv::OpFOrdLessThan:
6129 case spv::OpFOrdLessThanEqual:
6130 case spv::OpFOrdNotEqual:
6131 case spv::OpFUnordEqual:
6132 case spv::OpFUnordGreaterThan:
6133 case spv::OpFUnordGreaterThanEqual:
6134 case spv::OpFUnordLessThan:
6135 case spv::OpFUnordLessThanEqual:
6136 case spv::OpFUnordNotEqual:
6137 case spv::OpExtInst:
6138 case spv::OpIsInf:
6139 case spv::OpIsNan:
6140 case spv::OpAny:
6141 case spv::OpAll:
6142 case spv::OpUndef:
6143 case spv::OpConstantNull:
6144 case spv::OpLogicalOr:
6145 case spv::OpLogicalAnd:
6146 case spv::OpLogicalNot:
6147 case spv::OpLogicalNotEqual:
6148 case spv::OpConstantComposite:
6149 case spv::OpSpecConstantComposite:
6150 case spv::OpConstantTrue:
6151 case spv::OpConstantFalse:
6152 case spv::OpConstant:
6153 case spv::OpSpecConstant:
6154 case spv::OpVariable:
6155 case spv::OpFunctionCall:
6156 case spv::OpSampledImage:
6157 case spv::OpImageSampleExplicitLod:
David Neto5c22a252018-03-15 16:07:41 -04006158 case spv::OpImageQuerySize:
David Neto22f144c2017-06-12 14:26:21 -04006159 case spv::OpSelect:
6160 case spv::OpPhi:
6161 case spv::OpLoad:
6162 case spv::OpAtomicIAdd:
6163 case spv::OpAtomicISub:
6164 case spv::OpAtomicExchange:
6165 case spv::OpAtomicIIncrement:
6166 case spv::OpAtomicIDecrement:
6167 case spv::OpAtomicCompareExchange:
6168 case spv::OpAtomicUMin:
6169 case spv::OpAtomicSMin:
6170 case spv::OpAtomicUMax:
6171 case spv::OpAtomicSMax:
6172 case spv::OpAtomicAnd:
6173 case spv::OpAtomicOr:
6174 case spv::OpAtomicXor:
6175 case spv::OpDot: {
6176 WriteWordCountAndOpcode(Inst);
6177 WriteOperand(Ops[0]);
6178 WriteResultID(Inst);
6179 for (uint32_t i = 1; i < Ops.size(); i++) {
6180 WriteOperand(Ops[i]);
6181 }
6182 break;
6183 }
6184 }
6185 }
6186}