blob: 983e2f8375dc6d5cf157e3c0f8fa4e765a8d846f [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 Neto22f144c2017-06-12 14:26:21 -040020#include <clspv/Passes.h>
21
22#include <llvm/ADT/StringSwitch.h>
23#include <llvm/ADT/UniqueVector.h>
24#include <llvm/Analysis/LoopInfo.h>
25#include <llvm/IR/Constants.h>
26#include <llvm/IR/Dominators.h>
27#include <llvm/IR/Instructions.h>
28#include <llvm/IR/Metadata.h>
29#include <llvm/IR/Module.h>
30#include <llvm/Pass.h>
David Netocd8ca5f2017-10-02 23:34:11 -040031#include <llvm/Support/CommandLine.h>
David Neto22f144c2017-06-12 14:26:21 -040032#include <llvm/Support/raw_ostream.h>
33#include <llvm/Transforms/Utils/Cloning.h>
34
35#include <spirv/1.0/spirv.hpp>
36#include <clspv/AddressSpace.h>
37#include <clspv/spirv_c_strings.hpp>
38#include <clspv/spirv_glsl.hpp>
39
David Neto4feb7a42017-10-06 17:29:42 -040040#include "ArgKind.h"
David Neto48f56a42017-10-06 16:44:25 -040041
David Neto22f144c2017-06-12 14:26:21 -040042#include <list>
David Neto0676e6f2017-07-11 18:47:44 -040043#include <iomanip>
David Neto26aaf622017-10-23 18:11:53 -040044#include <set>
David Neto0676e6f2017-07-11 18:47:44 -040045#include <sstream>
David Neto26aaf622017-10-23 18:11:53 -040046#include <tuple>
David Neto44795152017-07-13 15:45:28 -040047#include <utility>
David Neto22f144c2017-06-12 14:26:21 -040048
49#if defined(_MSC_VER)
50#pragma warning(pop)
51#endif
52
53using namespace llvm;
54using namespace clspv;
David Neto156783e2017-07-05 15:39:41 -040055using namespace mdconst;
David Neto22f144c2017-06-12 14:26:21 -040056
57namespace {
David Netocd8ca5f2017-10-02 23:34:11 -040058
David Neto3fbb4072017-10-16 11:28:14 -040059// The value of 1/pi. This value is from MSDN
60// https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx
61const double kOneOverPi = 0.318309886183790671538;
62const glsl::ExtInst kGlslExtInstBad = static_cast<glsl::ExtInst>(0);
63
David Netoab03f432017-11-03 17:00:44 -040064const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
65
David Netocd8ca5f2017-10-02 23:34:11 -040066// By default, reuse the same descriptor set number for all arguments.
67// To turn that off, use -distinct-kernel-descriptor-sets
68llvm::cl::opt<bool> distinct_kernel_descriptor_sets(
69 "distinct-kernel-descriptor-sets", llvm::cl::init(false),
70 llvm::cl::desc(
71 "Each kernel uses its own descriptor set for its arguments"));
72
David Netoc66b3352017-10-20 14:28:46 -040073// Some drivers don't like to see constant composite values constructed
74// from scalar Undef values. Replace numeric scalar and vector Undef with
75// corresponding OpConstantNull. We need to keep Undef for image values,
76// for example. In the LLVM domain, image values are passed as pointer to
77// struct.
78// See https://github.com/google/clspv/issues/95
David Neto75d54be2017-10-18 15:37:17 -040079llvm::cl::opt<bool> hack_undef(
80 "hack-undef", llvm::cl::init(false),
David Netoc66b3352017-10-20 14:28:46 -040081 llvm::cl::desc("Use OpConstantNull instead of OpUndef for floating point, "
82 "integer, or vectors of them"));
David Neto75d54be2017-10-18 15:37:17 -040083
David Neto22f144c2017-06-12 14:26:21 -040084enum SPIRVOperandType {
85 NUMBERID,
86 LITERAL_INTEGER,
87 LITERAL_STRING,
88 LITERAL_FLOAT
89};
90
91struct SPIRVOperand {
92 explicit SPIRVOperand(SPIRVOperandType Ty, uint32_t Num)
93 : Type(Ty), LiteralNum(1, Num) {}
94 explicit SPIRVOperand(SPIRVOperandType Ty, const char *Str)
95 : Type(Ty), LiteralStr(Str) {}
96 explicit SPIRVOperand(SPIRVOperandType Ty, StringRef Str)
97 : Type(Ty), LiteralStr(Str) {}
98 explicit SPIRVOperand(SPIRVOperandType Ty, ArrayRef<uint32_t> NumVec)
99 : Type(Ty), LiteralNum(NumVec.begin(), NumVec.end()) {}
100
101 SPIRVOperandType getType() { return Type; };
102 uint32_t getNumID() { return LiteralNum[0]; };
103 std::string getLiteralStr() { return LiteralStr; };
104 ArrayRef<uint32_t> getLiteralNum() { return LiteralNum; };
105
106private:
107 SPIRVOperandType Type;
108 std::string LiteralStr;
109 SmallVector<uint32_t, 4> LiteralNum;
110};
111
112struct SPIRVInstruction {
113 explicit SPIRVInstruction(uint16_t WCount, spv::Op Opc, uint32_t ResID,
114 ArrayRef<SPIRVOperand *> Ops)
115 : WordCount(WCount), Opcode(static_cast<uint16_t>(Opc)), ResultID(ResID),
116 Operands(Ops.begin(), Ops.end()) {}
117
118 uint16_t getWordCount() const { return WordCount; }
119 uint16_t getOpcode() const { return Opcode; }
120 uint32_t getResultID() const { return ResultID; }
121 ArrayRef<SPIRVOperand *> getOperands() const { return Operands; }
122
123private:
124 uint16_t WordCount;
125 uint16_t Opcode;
126 uint32_t ResultID;
127 SmallVector<SPIRVOperand *, 4> Operands;
128};
129
130struct SPIRVProducerPass final : public ModulePass {
131 typedef std::vector<SPIRVOperand *> SPIRVOperandList;
132 typedef DenseMap<Type *, uint32_t> TypeMapType;
133 typedef UniqueVector<Type *> TypeList;
134 typedef DenseMap<Value *, uint32_t> ValueMapType;
David Netofb9a7972017-08-25 17:08:24 -0400135 typedef UniqueVector<Value *> ValueList;
David Neto22f144c2017-06-12 14:26:21 -0400136 typedef std::vector<std::pair<Value *, uint32_t>> EntryPointVecType;
137 typedef std::list<SPIRVInstruction *> SPIRVInstructionList;
138 typedef std::vector<
139 std::tuple<Value *, SPIRVInstructionList::iterator, uint32_t>>
140 DeferredInstVecType;
141 typedef DenseMap<FunctionType *, std::pair<FunctionType *, uint32_t>>
142 GlobalConstFuncMapType;
143
David Neto44795152017-07-13 15:45:28 -0400144 explicit SPIRVProducerPass(
145 raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
146 ArrayRef<std::pair<unsigned, std::string>> samplerMap, bool outputAsm,
147 bool outputCInitList)
David Netoc2c368d2017-06-30 16:50:17 -0400148 : ModulePass(ID), samplerMap(samplerMap), out(out),
David Neto0676e6f2017-07-11 18:47:44 -0400149 binaryTempOut(binaryTempUnderlyingVector), binaryOut(&out),
David Netoc2c368d2017-06-30 16:50:17 -0400150 descriptorMapOut(descriptor_map_out), outputAsm(outputAsm),
David Neto0676e6f2017-07-11 18:47:44 -0400151 outputCInitList(outputCInitList), patchBoundOffset(0), nextID(1),
David Netoa60b00b2017-09-15 16:34:09 -0400152 OpExtInstImportID(0), HasVariablePointers(false), SamplerTy(nullptr),
153 WorkgroupSizeValueID(0), WorkgroupSizeVarID(0) {}
David Neto22f144c2017-06-12 14:26:21 -0400154
155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.addRequired<DominatorTreeWrapperPass>();
157 AU.addRequired<LoopInfoWrapperPass>();
158 }
159
160 virtual bool runOnModule(Module &module) override;
161
162 // output the SPIR-V header block
163 void outputHeader();
164
165 // patch the SPIR-V header block
166 void patchHeader();
167
168 uint32_t lookupType(Type *Ty) {
169 if (Ty->isPointerTy() &&
170 (Ty->getPointerAddressSpace() != AddressSpace::UniformConstant)) {
171 auto PointeeTy = Ty->getPointerElementType();
172 if (PointeeTy->isStructTy() &&
173 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
174 Ty = PointeeTy;
175 }
176 }
177
178 if (0 == TypeMap.count(Ty)) {
179 Ty->print(errs());
180 llvm_unreachable("Unhandled type!");
181 }
182
183 return TypeMap[Ty];
184 }
185 TypeMapType &getImageTypeMap() { return ImageTypeMap; }
186 TypeList &getTypeList() { return Types; };
187 ValueList &getConstantList() { return Constants; };
188 ValueMapType &getValueMap() { return ValueMap; }
189 ValueMapType &getAllocatedValueMap() { return AllocatedValueMap; }
190 SPIRVInstructionList &getSPIRVInstList() { return SPIRVInsts; };
191 ValueToValueMapTy &getArgumentGVMap() { return ArgumentGVMap; };
192 ValueMapType &getArgumentGVIDMap() { return ArgumentGVIDMap; };
193 EntryPointVecType &getEntryPointVec() { return EntryPointVec; };
194 DeferredInstVecType &getDeferredInstVec() { return DeferredInstVec; };
195 ValueList &getEntryPointInterfacesVec() { return EntryPointInterfacesVec; };
196 uint32_t &getOpExtInstImportID() { return OpExtInstImportID; };
197 std::vector<uint32_t> &getBuiltinDimVec() { return BuiltinDimensionVec; };
198 bool hasVariablePointers() { return true; /* We use StorageBuffer everywhere */ };
199 void setVariablePointers(bool Val) { HasVariablePointers = Val; };
David Neto44795152017-07-13 15:45:28 -0400200 ArrayRef<std::pair<unsigned, std::string>> &getSamplerMap() { return samplerMap; }
David Neto22f144c2017-06-12 14:26:21 -0400201 GlobalConstFuncMapType &getGlobalConstFuncTypeMap() {
202 return GlobalConstFuncTypeMap;
203 }
204 SmallPtrSet<Value *, 16> &getGlobalConstArgSet() {
205 return GlobalConstArgumentSet;
206 }
David Neto1a1a0582017-07-07 12:01:44 -0400207 TypeList &getPointerTypesNeedingArrayStride() {
208 return PointerTypesNeedingArrayStride;
209 }
David Neto22f144c2017-06-12 14:26:21 -0400210
211 void GenerateLLVMIRInfo(Module &M);
212 bool FindExtInst(Module &M);
213 void FindTypePerGlobalVar(GlobalVariable &GV);
214 void FindTypePerFunc(Function &F);
David Neto19a1bad2017-08-25 15:01:41 -0400215 // Inserts |Ty| and relevant sub-types into the |Types| member, indicating that
216 // |Ty| and its subtypes will need a corresponding SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400217 void FindType(Type *Ty);
218 void FindConstantPerGlobalVar(GlobalVariable &GV);
219 void FindConstantPerFunc(Function &F);
220 void FindConstant(Value *V);
221 void GenerateExtInstImport();
David Neto19a1bad2017-08-25 15:01:41 -0400222 // Generates instructions for SPIR-V types corresponding to the LLVM types
223 // saved in the |Types| member. A type follows its subtypes. IDs are
224 // allocated sequentially starting with the current value of nextID, and
225 // with a type following its subtypes. Also updates nextID to just beyond
226 // the last generated ID.
David Neto22f144c2017-06-12 14:26:21 -0400227 void GenerateSPIRVTypes(const DataLayout &DL);
228 void GenerateSPIRVConstants();
229 void GenerateModuleInfo();
230 void GenerateGlobalVar(GlobalVariable &GV);
231 void GenerateSamplers(Module &M);
232 void GenerateFuncPrologue(Function &F);
233 void GenerateFuncBody(Function &F);
234 void GenerateInstForArg(Function &F);
235 spv::Op GetSPIRVCmpOpcode(CmpInst *CmpI);
236 spv::Op GetSPIRVCastOpcode(Instruction &I);
237 spv::Op GetSPIRVBinaryOpcode(Instruction &I);
238 void GenerateInstruction(Instruction &I);
239 void GenerateFuncEpilogue();
240 void HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400241 void HandleDeferredDecorations(const DataLayout& DL);
David Neto22f144c2017-06-12 14:26:21 -0400242 bool is4xi8vec(Type *Ty) const;
243 spv::StorageClass GetStorageClass(unsigned AddrSpace) const;
244 spv::BuiltIn GetBuiltin(StringRef globalVarName) const;
David Neto3fbb4072017-10-16 11:28:14 -0400245 // Returns the GLSL extended instruction enum that the given function
246 // call maps to. If none, then returns the 0 value, i.e. GLSLstd4580Bad.
David Neto22f144c2017-06-12 14:26:21 -0400247 glsl::ExtInst getExtInstEnum(StringRef Name);
David Neto3fbb4072017-10-16 11:28:14 -0400248 // Returns the GLSL extended instruction enum indirectly used by the given
249 // function. That is, to implement the given function, we use an extended
250 // instruction plus one more instruction. If none, then returns the 0 value,
251 // i.e. GLSLstd4580Bad.
252 glsl::ExtInst getIndirectExtInstEnum(StringRef Name);
253 // Returns the single GLSL extended instruction used directly or
254 // indirectly by the given function call.
255 glsl::ExtInst getDirectOrIndirectExtInstEnum(StringRef Name);
David Neto22f144c2017-06-12 14:26:21 -0400256 void PrintResID(SPIRVInstruction *Inst);
257 void PrintOpcode(SPIRVInstruction *Inst);
258 void PrintOperand(SPIRVOperand *Op);
259 void PrintCapability(SPIRVOperand *Op);
260 void PrintExtInst(SPIRVOperand *Op);
261 void PrintAddrModel(SPIRVOperand *Op);
262 void PrintMemModel(SPIRVOperand *Op);
263 void PrintExecModel(SPIRVOperand *Op);
264 void PrintExecMode(SPIRVOperand *Op);
265 void PrintSourceLanguage(SPIRVOperand *Op);
266 void PrintFuncCtrl(SPIRVOperand *Op);
267 void PrintStorageClass(SPIRVOperand *Op);
268 void PrintDecoration(SPIRVOperand *Op);
269 void PrintBuiltIn(SPIRVOperand *Op);
270 void PrintSelectionControl(SPIRVOperand *Op);
271 void PrintLoopControl(SPIRVOperand *Op);
272 void PrintDimensionality(SPIRVOperand *Op);
273 void PrintImageFormat(SPIRVOperand *Op);
274 void PrintMemoryAccess(SPIRVOperand *Op);
275 void PrintImageOperandsType(SPIRVOperand *Op);
276 void WriteSPIRVAssembly();
277 void WriteOneWord(uint32_t Word);
278 void WriteResultID(SPIRVInstruction *Inst);
279 void WriteWordCountAndOpcode(SPIRVInstruction *Inst);
280 void WriteOperand(SPIRVOperand *Op);
281 void WriteSPIRVBinary();
282
283private:
284 static char ID;
David Neto44795152017-07-13 15:45:28 -0400285 ArrayRef<std::pair<unsigned, std::string>> samplerMap;
David Neto22f144c2017-06-12 14:26:21 -0400286 raw_pwrite_stream &out;
David Neto0676e6f2017-07-11 18:47:44 -0400287
288 // TODO(dneto): Wouldn't it be better to always just emit a binary, and then
289 // convert to other formats on demand?
290
291 // When emitting a C initialization list, the WriteSPIRVBinary method
292 // will actually write its words to this vector via binaryTempOut.
293 SmallVector<char, 100> binaryTempUnderlyingVector;
294 raw_svector_ostream binaryTempOut;
295
296 // Binary output writes to this stream, which might be |out| or
297 // |binaryTempOut|. It's the latter when we really want to write a C
298 // initializer list.
299 raw_pwrite_stream* binaryOut;
David Netoc2c368d2017-06-30 16:50:17 -0400300 raw_ostream &descriptorMapOut;
David Neto22f144c2017-06-12 14:26:21 -0400301 const bool outputAsm;
David Neto0676e6f2017-07-11 18:47:44 -0400302 const bool outputCInitList; // If true, output look like {0x7023, ... , 5}
David Neto22f144c2017-06-12 14:26:21 -0400303 uint64_t patchBoundOffset;
304 uint32_t nextID;
305
David Neto19a1bad2017-08-25 15:01:41 -0400306 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400307 TypeMapType TypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400308 // Maps an LLVM image type to its SPIR-V ID.
David Neto22f144c2017-06-12 14:26:21 -0400309 TypeMapType ImageTypeMap;
David Neto19a1bad2017-08-25 15:01:41 -0400310 // A unique-vector of LLVM types that map to a SPIR-V type.
David Neto22f144c2017-06-12 14:26:21 -0400311 TypeList Types;
312 ValueList Constants;
David Neto19a1bad2017-08-25 15:01:41 -0400313 // Maps an LLVM Value pointer to the corresponding SPIR-V Id.
David Neto22f144c2017-06-12 14:26:21 -0400314 ValueMapType ValueMap;
315 ValueMapType AllocatedValueMap;
316 SPIRVInstructionList SPIRVInsts;
317 ValueToValueMapTy ArgumentGVMap;
318 ValueMapType ArgumentGVIDMap;
319 EntryPointVecType EntryPointVec;
320 DeferredInstVecType DeferredInstVec;
321 ValueList EntryPointInterfacesVec;
322 uint32_t OpExtInstImportID;
323 std::vector<uint32_t> BuiltinDimensionVec;
324 bool HasVariablePointers;
325 Type *SamplerTy;
326 GlobalConstFuncMapType GlobalConstFuncTypeMap;
327 SmallPtrSet<Value *, 16> GlobalConstArgumentSet;
David Neto1a1a0582017-07-07 12:01:44 -0400328 // An ordered set of pointer types of Base arguments to OpPtrAccessChain,
329 // and which point into transparent memory (StorageBuffer storage class).
330 // These will require an ArrayStride decoration.
331 // See SPV_KHR_variable_pointers rev 13.
332 TypeList PointerTypesNeedingArrayStride;
David Netoa60b00b2017-09-15 16:34:09 -0400333
334 // This is truly ugly, but works around what look like driver bugs.
335 // For get_local_size, an earlier part of the flow has created a module-scope
336 // variable in Private address space to hold the value for the workgroup
337 // size. Its intializer is a uint3 value marked as builtin WorkgroupSize.
338 // When this is present, save the IDs of the initializer value and variable
339 // in these two variables. We only ever do a vector load from it, and
340 // when we see one of those, substitute just the value of the intializer.
341 // This mimics what Glslang does, and that's what drivers are used to.
342 uint32_t WorkgroupSizeValueID;
343 uint32_t WorkgroupSizeVarID;
David Neto26aaf622017-10-23 18:11:53 -0400344
345 // What module-scope variables already have had their binding information
346 // emitted?
347 DenseSet<Value*> GVarWithEmittedBindingInfo;
David Neto22f144c2017-06-12 14:26:21 -0400348};
349
350char SPIRVProducerPass::ID;
351}
352
353namespace clspv {
David Neto44795152017-07-13 15:45:28 -0400354ModulePass *
355createSPIRVProducerPass(raw_pwrite_stream &out, raw_ostream &descriptor_map_out,
356 ArrayRef<std::pair<unsigned, std::string>> samplerMap,
357 bool outputAsm, bool outputCInitList) {
358 return new SPIRVProducerPass(out, descriptor_map_out, samplerMap, outputAsm,
359 outputCInitList);
David Neto22f144c2017-06-12 14:26:21 -0400360}
David Netoc2c368d2017-06-30 16:50:17 -0400361} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400362
363bool SPIRVProducerPass::runOnModule(Module &module) {
David Neto0676e6f2017-07-11 18:47:44 -0400364 binaryOut = outputCInitList ? &binaryTempOut : &out;
365
David Neto22f144c2017-06-12 14:26:21 -0400366 // SPIR-V always begins with its header information
367 outputHeader();
368
369 // Gather information from the LLVM IR that we require.
370 GenerateLLVMIRInfo(module);
371
372 // If we are using a sampler map, find the type of the sampler.
373 if (0 < getSamplerMap().size()) {
374 auto SamplerStructTy = module.getTypeByName("opencl.sampler_t");
375 if (!SamplerStructTy) {
376 SamplerStructTy =
377 StructType::create(module.getContext(), "opencl.sampler_t");
378 }
379
380 SamplerTy = SamplerStructTy->getPointerTo(AddressSpace::UniformConstant);
381
382 FindType(SamplerTy);
383 }
384
385 // Collect information on global variables too.
386 for (GlobalVariable &GV : module.globals()) {
387 // If the GV is one of our special __spirv_* variables, remove the
388 // initializer as it was only placed there to force LLVM to not throw the
389 // value away.
390 if (GV.getName().startswith("__spirv_")) {
391 GV.setInitializer(nullptr);
392 }
393
394 // Collect types' information from global variable.
395 FindTypePerGlobalVar(GV);
396
397 // Collect constant information from global variable.
398 FindConstantPerGlobalVar(GV);
399
400 // If the variable is an input, entry points need to know about it.
401 if (AddressSpace::Input == GV.getType()->getPointerAddressSpace()) {
David Netofb9a7972017-08-25 17:08:24 -0400402 getEntryPointInterfacesVec().insert(&GV);
David Neto22f144c2017-06-12 14:26:21 -0400403 }
404 }
405
406 // If there are extended instructions, generate OpExtInstImport.
407 if (FindExtInst(module)) {
408 GenerateExtInstImport();
409 }
410
411 // Generate SPIRV instructions for types.
412 const DataLayout &DL = module.getDataLayout();
413 GenerateSPIRVTypes(DL);
414
415 // Generate SPIRV constants.
416 GenerateSPIRVConstants();
417
418 // If we have a sampler map, we might have literal samplers to generate.
419 if (0 < getSamplerMap().size()) {
420 GenerateSamplers(module);
421 }
422
423 // Generate SPIRV variables.
424 for (GlobalVariable &GV : module.globals()) {
425 GenerateGlobalVar(GV);
426 }
427
428 // Generate SPIRV instructions for each function.
429 for (Function &F : module) {
430 if (F.isDeclaration()) {
431 continue;
432 }
433
434 // Generate Function Prologue.
435 GenerateFuncPrologue(F);
436
437 // Generate SPIRV instructions for function body.
438 GenerateFuncBody(F);
439
440 // Generate Function Epilogue.
441 GenerateFuncEpilogue();
442 }
443
444 HandleDeferredInstruction();
David Neto1a1a0582017-07-07 12:01:44 -0400445 HandleDeferredDecorations(DL);
David Neto22f144c2017-06-12 14:26:21 -0400446
447 // Generate SPIRV module information.
448 GenerateModuleInfo();
449
450 if (outputAsm) {
451 WriteSPIRVAssembly();
452 } else {
453 WriteSPIRVBinary();
454 }
455
456 // We need to patch the SPIR-V header to set bound correctly.
457 patchHeader();
David Neto0676e6f2017-07-11 18:47:44 -0400458
459 if (outputCInitList) {
460 bool first = true;
David Neto0676e6f2017-07-11 18:47:44 -0400461 std::ostringstream os;
462
David Neto57fb0b92017-08-04 15:35:09 -0400463 auto emit_word = [&os, &first](uint32_t word) {
David Neto0676e6f2017-07-11 18:47:44 -0400464 if (!first)
David Neto57fb0b92017-08-04 15:35:09 -0400465 os << ",\n";
466 os << word;
David Neto0676e6f2017-07-11 18:47:44 -0400467 first = false;
468 };
469
470 os << "{";
David Neto57fb0b92017-08-04 15:35:09 -0400471 const std::string str(binaryTempOut.str());
472 for (unsigned i = 0; i < str.size(); i += 4) {
473 const uint32_t a = static_cast<unsigned char>(str[i]);
474 const uint32_t b = static_cast<unsigned char>(str[i + 1]);
475 const uint32_t c = static_cast<unsigned char>(str[i + 2]);
476 const uint32_t d = static_cast<unsigned char>(str[i + 3]);
477 emit_word(a | (b << 8) | (c << 16) | (d << 24));
David Neto0676e6f2017-07-11 18:47:44 -0400478 }
479 os << "}\n";
480 out << os.str();
481 }
482
David Neto22f144c2017-06-12 14:26:21 -0400483 return false;
484}
485
486void SPIRVProducerPass::outputHeader() {
487 if (outputAsm) {
488 // for ASM output the header goes into 5 comments at the beginning of the
489 // file
490 out << "; SPIR-V\n";
491
492 // the major version number is in the 2nd highest byte
493 const uint32_t major = (spv::Version >> 16) & 0xFF;
494
495 // the minor version number is in the 2nd lowest byte
496 const uint32_t minor = (spv::Version >> 8) & 0xFF;
497 out << "; Version: " << major << "." << minor << "\n";
498
499 // use Codeplay's vendor ID
500 out << "; Generator: Codeplay; 0\n";
501
502 out << "; Bound: ";
503
504 // we record where we need to come back to and patch in the bound value
505 patchBoundOffset = out.tell();
506
507 // output one space per digit for the max size of a 32 bit unsigned integer
508 // (which is the maximum ID we could possibly be using)
509 for (uint32_t i = std::numeric_limits<uint32_t>::max(); 0 != i; i /= 10) {
510 out << " ";
511 }
512
513 out << "\n";
514
515 out << "; Schema: 0\n";
516 } else {
David Neto0676e6f2017-07-11 18:47:44 -0400517 binaryOut->write(reinterpret_cast<const char *>(&spv::MagicNumber),
David Neto22f144c2017-06-12 14:26:21 -0400518 sizeof(spv::MagicNumber));
David Neto0676e6f2017-07-11 18:47:44 -0400519 binaryOut->write(reinterpret_cast<const char *>(&spv::Version),
David Neto22f144c2017-06-12 14:26:21 -0400520 sizeof(spv::Version));
521
522 // use Codeplay's vendor ID
523 const uint32_t vendor = 3 << 16;
David Neto0676e6f2017-07-11 18:47:44 -0400524 binaryOut->write(reinterpret_cast<const char *>(&vendor), sizeof(vendor));
David Neto22f144c2017-06-12 14:26:21 -0400525
526 // we record where we need to come back to and patch in the bound value
David Neto0676e6f2017-07-11 18:47:44 -0400527 patchBoundOffset = binaryOut->tell();
David Neto22f144c2017-06-12 14:26:21 -0400528
529 // output a bad bound for now
David Neto0676e6f2017-07-11 18:47:44 -0400530 binaryOut->write(reinterpret_cast<const char *>(&nextID), sizeof(nextID));
David Neto22f144c2017-06-12 14:26:21 -0400531
532 // output the schema (reserved for use and must be 0)
533 const uint32_t schema = 0;
David Neto0676e6f2017-07-11 18:47:44 -0400534 binaryOut->write(reinterpret_cast<const char *>(&schema), sizeof(schema));
David Neto22f144c2017-06-12 14:26:21 -0400535 }
536}
537
538void SPIRVProducerPass::patchHeader() {
539 if (outputAsm) {
540 // get the string representation of the max bound used (nextID will be the
541 // max ID used)
542 auto asString = std::to_string(nextID);
543 out.pwrite(asString.c_str(), asString.size(), patchBoundOffset);
544 } else {
545 // for a binary we just write the value of nextID over bound
David Neto0676e6f2017-07-11 18:47:44 -0400546 binaryOut->pwrite(reinterpret_cast<char *>(&nextID), sizeof(nextID),
547 patchBoundOffset);
David Neto22f144c2017-06-12 14:26:21 -0400548 }
549}
550
551void SPIRVProducerPass::GenerateLLVMIRInfo(Module &M) {
552 // This function generates LLVM IR for function such as global variable for
553 // argument, constant and pointer type for argument access. These information
554 // is artificial one because we need Vulkan SPIR-V output. This function is
555 // executed ahead of FindType and FindConstant.
556 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
557 LLVMContext &Context = M.getContext();
558
559 // Map for avoiding to generate struct type with same fields.
560 DenseMap<Type *, Type *> ArgTyMap;
561
562 // Collect global constant variables.
563 SmallVector<GlobalVariable *, 8> GVList;
564 for (GlobalVariable &GV : M.globals()) {
565 if (GV.getType()->getAddressSpace() == AddressSpace::Constant) {
566 GVList.push_back(&GV);
567 }
568 }
569
570 // Change global constant variable's address space to ModuleScopePrivate.
571 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
572 for (auto GV : GVList) {
573 // If there is no user of gv, delete gv.
574 if (GV->use_empty()) {
575 GV->eraseFromParent();
576 continue;
577 }
578
579 // Create new gv with ModuleScopePrivate address space.
580 Type *NewGVTy = GV->getType()->getPointerElementType();
581 GlobalVariable *NewGV = new GlobalVariable(
582 M, NewGVTy, false, GV->getLinkage(), GV->getInitializer(), "", nullptr,
583 GV->getThreadLocalMode(), AddressSpace::ModuleScopePrivate);
584 NewGV->takeName(GV);
585
586 const SmallVector<User *, 8> GVUsers(GV->user_begin(), GV->user_end());
587 SmallVector<User*, 8> CandidateUsers;
588
589 for (User *GVU : GVUsers) {
590 if (CallInst *Call = dyn_cast<CallInst>(GVU)) {
591 // Find argument index.
592 unsigned GVCstArgIdx = 0;
593 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
594 if (GV == Call->getOperand(i)) {
595 GVCstArgIdx = i;
596 }
597 }
598
599 // Record function with global constant.
600 GlobalConstFuncTyMap[Call->getFunctionType()] =
601 std::make_pair(Call->getFunctionType(), GVCstArgIdx);
602 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(GVU)) {
603 // Check GEP users.
604 for (User *GEPU : GEP->users()) {
605 if (CallInst *GEPCall = dyn_cast<CallInst>(GEPU)) {
606 // Find argument index.
607 unsigned GVCstArgIdx = 0;
608 for (unsigned i = 0; i < GEPCall->getNumArgOperands(); i++) {
609 if (GEP == GEPCall->getOperand(i)) {
610 GVCstArgIdx = i;
611 }
612 }
613
614 // Record function with global constant.
615 GlobalConstFuncTyMap[GEPCall->getFunctionType()] =
616 std::make_pair(GEPCall->getFunctionType(), GVCstArgIdx);
617 }
618 }
619 }
620
621 CandidateUsers.push_back(GVU);
622 }
623
624 for (User *U : CandidateUsers) {
625 // Update users of gv with new gv.
626 U->replaceUsesOfWith(GV, NewGV);
627 }
628
629 // Delete original gv.
630 GV->eraseFromParent();
631 }
632
633 bool HasWorkGroupBuiltin = false;
634 for (GlobalVariable &GV : M.globals()) {
635 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
636 if (spv::BuiltInWorkgroupSize == BuiltinType) {
637 HasWorkGroupBuiltin = true;
638 }
639 }
640
641
David Neto26aaf622017-10-23 18:11:53 -0400642
643 // Map kernel functions to their ordinal number in the compilation unit.
644 UniqueVector<Function*> KernelOrdinal;
645
646 // Map the global variables created for kernel args to their creation
647 // order.
648 UniqueVector<GlobalVariable*> KernelArgVarOrdinal;
649
650 // For each kernel argument type, record the kernel arg global variables
651 // generated for that type, the function in which that variable was most
652 // recently used, and the binding number it took. For reproducibility,
653 // we track things by ordinal number (rather than pointer), and we use a
654 // std::set rather than DenseSet since std::set maintains an ordering.
655 // Each tuple is the ordinals of the kernel function, the binding number,
656 // and the ordinal of the kernal-arg-var.
657 //
658 // This table lets us reuse module-scope StorageBuffer variables between
659 // different kernels.
660 DenseMap<Type *, std::set<std::tuple<unsigned, unsigned, unsigned>>>
661 GVarsForType;
662
David Neto22f144c2017-06-12 14:26:21 -0400663 for (Function &F : M) {
664 // Handle kernel function first.
665 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
666 continue;
667 }
David Neto26aaf622017-10-23 18:11:53 -0400668 KernelOrdinal.insert(&F);
David Neto22f144c2017-06-12 14:26:21 -0400669
670 for (BasicBlock &BB : F) {
671 for (Instruction &I : BB) {
672 if (I.getOpcode() == Instruction::ZExt ||
673 I.getOpcode() == Instruction::SExt ||
674 I.getOpcode() == Instruction::UIToFP) {
675 // If there is zext with i1 type, it will be changed to OpSelect. The
676 // OpSelect needs constant 0 and 1 so the constants are added here.
677
678 auto OpTy = I.getOperand(0)->getType();
679
680 if (OpTy->isIntegerTy(1) ||
681 (OpTy->isVectorTy() &&
682 OpTy->getVectorElementType()->isIntegerTy(1))) {
683 if (I.getOpcode() == Instruction::ZExt) {
684 APInt One(32, 1);
685 FindConstant(Constant::getNullValue(I.getType()));
686 FindConstant(Constant::getIntegerValue(I.getType(), One));
687 } else if (I.getOpcode() == Instruction::SExt) {
688 APInt MinusOne(32, UINT64_MAX, true);
689 FindConstant(Constant::getNullValue(I.getType()));
690 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
691 } else {
692 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
693 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
694 }
695 }
696 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
697 Function *Callee = Call->getCalledFunction();
698
699 // Handle image type specially.
700 if (Callee->getName().equals(
701 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
702 Callee->getName().equals(
703 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
704 TypeMapType &OpImageTypeMap = getImageTypeMap();
705 Type *ImageTy =
706 Call->getArgOperand(0)->getType()->getPointerElementType();
707 OpImageTypeMap[ImageTy] = 0;
708
709 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
710 }
711 }
712 }
713 }
714
715 if (M.getTypeByName("opencl.image2d_ro_t") ||
716 M.getTypeByName("opencl.image2d_wo_t") ||
717 M.getTypeByName("opencl.image3d_ro_t") ||
718 M.getTypeByName("opencl.image3d_wo_t")) {
719 // Assume Image type's sampled type is float type.
720 FindType(Type::getFloatTy(Context));
721 }
722
723 if (const MDNode *MD =
724 dyn_cast<Function>(&F)->getMetadata("reqd_work_group_size")) {
725 // We generate constants if the WorkgroupSize builtin is being used.
726 if (HasWorkGroupBuiltin) {
727 // Collect constant information for work group size.
728 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(0)));
729 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(1)));
730 FindConstant(mdconst::extract<ConstantInt>(MD->getOperand(2)));
731 }
732 }
733
734 // Wrap up all argument types with struct type and create global variables
735 // with them.
736 bool HasArgUser = false;
737 unsigned Idx = 0;
738
739 for (const Argument &Arg : F.args()) {
740 Type *ArgTy = Arg.getType();
741 Type *GVTy = nullptr;
742
743 // Check argument type whether it is pointer type or not. If it is
744 // pointer type, add its address space to new global variable for
745 // argument.
746 unsigned AddrSpace = AddressSpace::Global;
747 if (PointerType *ArgPTy = dyn_cast<PointerType>(ArgTy)) {
748 AddrSpace = ArgPTy->getAddressSpace();
749 }
750
751 Type *TmpArgTy = ArgTy;
752
753 // sampler_t and image types have pointer type of struct type with
754 // opaque
755 // type as field. Extract the struct type. It will be used by global
756 // variable for argument.
757 bool IsSamplerType = false;
758 bool IsImageType = false;
759 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
760 if (StructType *STy =
761 dyn_cast<StructType>(TmpArgPTy->getElementType())) {
762 if (STy->isOpaque()) {
763 if (STy->getName().equals("opencl.sampler_t")) {
764 AddrSpace = AddressSpace::UniformConstant;
765 IsSamplerType = true;
766 TmpArgTy = STy;
767 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
768 STy->getName().equals("opencl.image2d_wo_t") ||
769 STy->getName().equals("opencl.image3d_ro_t") ||
770 STy->getName().equals("opencl.image3d_wo_t")) {
771 AddrSpace = AddressSpace::UniformConstant;
772 IsImageType = true;
773 TmpArgTy = STy;
774 } else {
775 llvm_unreachable("Argument has opaque type unsupported???");
776 }
777 }
778 }
779 }
780
781 // LLVM's pointer type is distinguished by address space but we need to
782 // regard constant and global address space as same here. If pointer
783 // type has constant address space, generate new pointer type
784 // temporarily to check previous struct type for argument.
785 if (PointerType *TmpArgPTy = dyn_cast<PointerType>(TmpArgTy)) {
786 AddrSpace = TmpArgPTy->getAddressSpace();
787 if (AddrSpace == AddressSpace::Constant) {
788 TmpArgTy = PointerType::get(TmpArgPTy->getElementType(),
789 AddressSpace::Global);
790 }
791 }
792
793 if (IsSamplerType || IsImageType) {
794 GVTy = TmpArgTy;
795 } else if (ArgTyMap.count(TmpArgTy)) {
796 // If there are arguments handled previously, use its type.
797 GVTy = ArgTyMap[TmpArgTy];
798 } else {
799 // Wrap up argument type with struct type.
David Neto83add0a2017-10-23 15:30:59 -0400800 // Reuse struct types where possible.
David Neto7b2abea2017-10-23 20:02:02 -0400801 SmallVector<Type*,1> members{ArgTy};
David Neto83add0a2017-10-23 15:30:59 -0400802 StructType *STy = StructType::get(Context, members);
David Neto22f144c2017-06-12 14:26:21 -0400803
804 GVTy = STy;
805 ArgTyMap[TmpArgTy] = STy;
806 }
807
808 // In order to build type map between llvm type and spirv id, LLVM
809 // global variable is needed. It has llvm type and other instructions
810 // can access it with its type.
David Neto26aaf622017-10-23 18:11:53 -0400811 //
812 // Reuse a global variable if it was created for a different entry point.
813
814 // Returns a new global variable for this kernel argument, and remembers
815 // it in KernelArgVarOrdinal.
816 auto make_gvar = [&]() {
817 auto result = new GlobalVariable(
818 M, GVTy, false, GlobalValue::ExternalLinkage, UndefValue::get(GVTy),
819 F.getName() + ".arg." + std::to_string(Idx), nullptr,
820 GlobalValue::ThreadLocalMode::NotThreadLocal, AddrSpace);
821 KernelArgVarOrdinal.insert(result);
822 return result;
823 };
824
825 // Make a new variable if there was none for this type, or if we can
826 // reuse one created for a different function but not yet reused for
827 // the current function, *and* the binding is the same.
828 // Always make a new variable if we're forcing distinct descriptor sets.
829 GlobalVariable *GV = nullptr;
830 auto which_set = GVarsForType.find(GVTy);
831 if (IsSamplerType || IsImageType || which_set == GVarsForType.end() ||
832 distinct_kernel_descriptor_sets) {
833 GV = make_gvar();
834 } else {
835 auto &set = which_set->second;
836 // Reuse a variable if it was associated with a different function.
837 for (auto iter = set.begin(), end = set.end();
838 iter != end; ++iter) {
839 const unsigned fn_ordinal = std::get<0>(*iter);
840 const unsigned binding = std::get<1>(*iter);
841 if (fn_ordinal != KernelOrdinal.idFor(&F) && binding == Idx) {
842 GV = KernelArgVarOrdinal[std::get<2>(*iter)];
843 // Remove it from the set. We'll add it back later.
844 set.erase(iter);
845 break;
846 }
847 }
848 if (!GV) {
849 GV = make_gvar();
850 }
851 }
852 assert(GV);
853 GVarsForType[GVTy].insert(std::make_tuple(KernelOrdinal.idFor(&F), Idx,
854 KernelArgVarOrdinal.idFor(GV)));
David Neto22f144c2017-06-12 14:26:21 -0400855
856 // Generate type info for argument global variable.
David Neto26aaf622017-10-23 18:11:53 -0400857 FindType(GV->getType());
David Neto22f144c2017-06-12 14:26:21 -0400858
David Neto26aaf622017-10-23 18:11:53 -0400859 ArgGVMap[&Arg] = GV;
860
861 Idx++;
David Neto22f144c2017-06-12 14:26:21 -0400862
863 // Generate pointer type of argument type for OpAccessChain of argument.
864 if (!Arg.use_empty()) {
865 if (!isa<PointerType>(ArgTy)) {
866 FindType(PointerType::get(ArgTy, AddrSpace));
867 }
868 HasArgUser = true;
869 }
870 }
871
872 if (HasArgUser) {
873 // Generate constant 0 for OpAccessChain of argument.
874 Type *IdxTy = Type::getInt32Ty(Context);
875 FindConstant(ConstantInt::get(IdxTy, 0));
876 FindType(IdxTy);
877 }
878
879 // Collect types' information from function.
880 FindTypePerFunc(F);
881
882 // Collect constant information from function.
883 FindConstantPerFunc(F);
884 }
885
886 for (Function &F : M) {
887 // Handle non-kernel functions.
888 if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL) {
889 continue;
890 }
891
892 for (BasicBlock &BB : F) {
893 for (Instruction &I : BB) {
894 if (I.getOpcode() == Instruction::ZExt ||
895 I.getOpcode() == Instruction::SExt ||
896 I.getOpcode() == Instruction::UIToFP) {
897 // If there is zext with i1 type, it will be changed to OpSelect. The
898 // OpSelect needs constant 0 and 1 so the constants are added here.
899
900 auto OpTy = I.getOperand(0)->getType();
901
902 if (OpTy->isIntegerTy(1) ||
903 (OpTy->isVectorTy() &&
904 OpTy->getVectorElementType()->isIntegerTy(1))) {
905 if (I.getOpcode() == Instruction::ZExt) {
906 APInt One(32, 1);
907 FindConstant(Constant::getNullValue(I.getType()));
908 FindConstant(Constant::getIntegerValue(I.getType(), One));
909 } else if (I.getOpcode() == Instruction::SExt) {
910 APInt MinusOne(32, UINT64_MAX, true);
911 FindConstant(Constant::getNullValue(I.getType()));
912 FindConstant(Constant::getIntegerValue(I.getType(), MinusOne));
913 } else {
914 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
915 FindConstant(ConstantFP::get(Context, APFloat(1.0f)));
916 }
917 }
918 } else if (CallInst *Call = dyn_cast<CallInst>(&I)) {
919 Function *Callee = Call->getCalledFunction();
920
921 // Handle image type specially.
922 if (Callee->getName().equals(
923 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
924 Callee->getName().equals(
925 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
926 TypeMapType &OpImageTypeMap = getImageTypeMap();
927 Type *ImageTy =
928 Call->getArgOperand(0)->getType()->getPointerElementType();
929 OpImageTypeMap[ImageTy] = 0;
930
931 FindConstant(ConstantFP::get(Context, APFloat(0.0f)));
932 }
933 }
934 }
935 }
936
937 if (M.getTypeByName("opencl.image2d_ro_t") ||
938 M.getTypeByName("opencl.image2d_wo_t") ||
939 M.getTypeByName("opencl.image3d_ro_t") ||
940 M.getTypeByName("opencl.image3d_wo_t")) {
941 // Assume Image type's sampled type is float type.
942 FindType(Type::getFloatTy(Context));
943 }
944
945 // Collect types' information from function.
946 FindTypePerFunc(F);
947
948 // Collect constant information from function.
949 FindConstantPerFunc(F);
950 }
951}
952
953bool SPIRVProducerPass::FindExtInst(Module &M) {
954 LLVMContext &Context = M.getContext();
955 bool HasExtInst = false;
956
957 for (Function &F : M) {
958 for (BasicBlock &BB : F) {
959 for (Instruction &I : BB) {
960 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
961 Function *Callee = Call->getCalledFunction();
962 // Check whether this call is for extend instructions.
David Neto3fbb4072017-10-16 11:28:14 -0400963 auto callee_name = Callee->getName();
964 const glsl::ExtInst EInst = getExtInstEnum(callee_name);
965 const glsl::ExtInst IndirectEInst =
966 getIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -0400967
David Neto3fbb4072017-10-16 11:28:14 -0400968 HasExtInst |=
969 (EInst != kGlslExtInstBad) || (IndirectEInst != kGlslExtInstBad);
970
971 if (IndirectEInst) {
972 // Register extra constants if needed.
973
974 // Registers a type and constant for computing the result of the
975 // given instruction. If the result of the instruction is a vector,
976 // then make a splat vector constant with the same number of
977 // elements.
978 auto register_constant = [this, &I](Constant *constant) {
979 FindType(constant->getType());
980 FindConstant(constant);
981 if (auto *vectorTy = dyn_cast<VectorType>(I.getType())) {
982 // Register the splat vector of the value with the same
983 // width as the result of the instruction.
984 auto *vec_constant = ConstantVector::getSplat(
985 static_cast<unsigned>(vectorTy->getNumElements()),
986 constant);
987 FindConstant(vec_constant);
988 FindType(vec_constant->getType());
989 }
990 };
991 switch (IndirectEInst) {
992 case glsl::ExtInstFindUMsb:
993 // clz needs OpExtInst and OpISub with constant 31, or splat
994 // vector of 31. Add it to the constant list here.
995 register_constant(
996 ConstantInt::get(Type::getInt32Ty(Context), 31));
997 break;
998 case glsl::ExtInstAcos:
999 case glsl::ExtInstAsin:
1000 case glsl::ExtInstAtan2:
1001 // We need 1/pi for acospi, asinpi, atan2pi.
1002 register_constant(
1003 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
1004 break;
1005 default:
1006 assert(false && "internally inconsistent");
1007 }
David Neto22f144c2017-06-12 14:26:21 -04001008 }
1009 }
1010 }
1011 }
1012 }
1013
1014 return HasExtInst;
1015}
1016
1017void SPIRVProducerPass::FindTypePerGlobalVar(GlobalVariable &GV) {
1018 // Investigate global variable's type.
1019 FindType(GV.getType());
1020}
1021
1022void SPIRVProducerPass::FindTypePerFunc(Function &F) {
1023 // Investigate function's type.
1024 FunctionType *FTy = F.getFunctionType();
1025
1026 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
1027 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
1028 // Handle function with global constant parameters.
1029 if (GlobalConstFuncTyMap.count(FTy)) {
1030 uint32_t GVCstArgIdx = GlobalConstFuncTypeMap[FTy].second;
1031 SmallVector<Type *, 4> NewFuncParamTys;
1032 for (unsigned i = 0; i < FTy->getNumParams(); i++) {
1033 Type *ParamTy = FTy->getParamType(i);
1034 if (i == GVCstArgIdx) {
1035 Type *EleTy = ParamTy->getPointerElementType();
1036 ParamTy = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1037 }
1038
1039 NewFuncParamTys.push_back(ParamTy);
1040 }
1041
1042 FunctionType *NewFTy =
1043 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1044 GlobalConstFuncTyMap[FTy] = std::make_pair(NewFTy, GVCstArgIdx);
1045 FTy = NewFTy;
1046 }
1047
1048 FindType(FTy);
1049 } else {
1050 // As kernel functions do not have parameters, create new function type and
1051 // add it to type map.
1052 SmallVector<Type *, 4> NewFuncParamTys;
1053 FunctionType *NewFTy =
1054 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
1055 FindType(NewFTy);
1056 }
1057
1058 // Investigate instructions' type in function body.
1059 for (BasicBlock &BB : F) {
1060 for (Instruction &I : BB) {
1061 if (isa<ShuffleVectorInst>(I)) {
1062 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1063 // Ignore type for mask of shuffle vector instruction.
1064 if (i == 2) {
1065 continue;
1066 }
1067
1068 Value *Op = I.getOperand(i);
1069 if (!isa<MetadataAsValue>(Op)) {
1070 FindType(Op->getType());
1071 }
1072 }
1073
1074 FindType(I.getType());
1075 continue;
1076 }
1077
1078 // Work through the operands of the instruction.
1079 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1080 Value *const Op = I.getOperand(i);
1081 // If any of the operands is a constant, find the type!
1082 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1083 FindType(Op->getType());
1084 }
1085 }
1086
1087 for (Use &Op : I.operands()) {
1088 if (CallInst *Call = dyn_cast<CallInst>(&I)) {
1089 // Avoid to check call instruction's type.
1090 break;
1091 }
1092 if (!isa<MetadataAsValue>(&Op)) {
1093 FindType(Op->getType());
1094 continue;
1095 }
1096 }
1097
1098 CallInst *Call = dyn_cast<CallInst>(&I);
1099
1100 // We don't want to track the type of this call as we are going to replace
1101 // it.
1102 if (Call && ("__translate_sampler_initializer" ==
1103 Call->getCalledFunction()->getName())) {
1104 continue;
1105 }
1106
1107 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1108 // If gep's base operand has ModuleScopePrivate address space, make gep
1109 // return ModuleScopePrivate address space.
1110 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate) {
1111 // Add pointer type with private address space for global constant to
1112 // type list.
1113 Type *EleTy = I.getType()->getPointerElementType();
1114 Type *NewPTy =
1115 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
1116
1117 FindType(NewPTy);
1118 continue;
1119 }
1120 }
1121
1122 FindType(I.getType());
1123 }
1124 }
1125}
1126
1127void SPIRVProducerPass::FindType(Type *Ty) {
1128 TypeList &TyList = getTypeList();
1129
1130 if (0 != TyList.idFor(Ty)) {
1131 return;
1132 }
1133
1134 if (Ty->isPointerTy()) {
1135 auto AddrSpace = Ty->getPointerAddressSpace();
1136 if ((AddressSpace::Constant == AddrSpace) ||
1137 (AddressSpace::Global == AddrSpace)) {
1138 auto PointeeTy = Ty->getPointerElementType();
1139
1140 if (PointeeTy->isStructTy() &&
1141 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1142 FindType(PointeeTy);
1143 auto ActualPointerTy =
1144 PointeeTy->getPointerTo(AddressSpace::UniformConstant);
1145 FindType(ActualPointerTy);
1146 return;
1147 }
1148 }
1149 }
1150
1151 // OpTypeArray has constant and we need to support type of the constant.
1152 if (isa<ArrayType>(Ty)) {
1153 LLVMContext &Context = Ty->getContext();
1154 FindType(Type::getInt32Ty(Context));
1155 }
1156
1157 for (Type *SubTy : Ty->subtypes()) {
1158 FindType(SubTy);
1159 }
1160
1161 TyList.insert(Ty);
1162}
1163
1164void SPIRVProducerPass::FindConstantPerGlobalVar(GlobalVariable &GV) {
1165 // If the global variable has a (non undef) initializer.
1166 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
1167 FindConstant(GV.getInitializer());
1168 }
1169}
1170
1171void SPIRVProducerPass::FindConstantPerFunc(Function &F) {
1172 // Investigate constants in function body.
1173 for (BasicBlock &BB : F) {
1174 for (Instruction &I : BB) {
1175 CallInst *Call = dyn_cast<CallInst>(&I);
1176
1177 if (Call && ("__translate_sampler_initializer" ==
1178 Call->getCalledFunction()->getName())) {
1179 // We've handled these constants elsewhere, so skip it.
1180 continue;
1181 }
1182
1183 if (isa<AllocaInst>(I)) {
1184 // Alloca instruction has constant for the number of element. Ignore it.
1185 continue;
1186 } else if (isa<ShuffleVectorInst>(I)) {
1187 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1188 // Ignore constant for mask of shuffle vector instruction.
1189 if (i == 2) {
1190 continue;
1191 }
1192
1193 if (isa<Constant>(I.getOperand(i)) &&
1194 !isa<GlobalValue>(I.getOperand(i))) {
1195 FindConstant(I.getOperand(i));
1196 }
1197 }
1198
1199 continue;
1200 } else if (isa<InsertElementInst>(I)) {
1201 // Handle InsertElement with <4 x i8> specially.
1202 Type *CompositeTy = I.getOperand(0)->getType();
1203 if (is4xi8vec(CompositeTy)) {
1204 LLVMContext &Context = CompositeTy->getContext();
1205 if (isa<Constant>(I.getOperand(0))) {
1206 FindConstant(I.getOperand(0));
1207 }
1208
1209 if (isa<Constant>(I.getOperand(1))) {
1210 FindConstant(I.getOperand(1));
1211 }
1212
1213 // Add mask constant 0xFF.
1214 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1215 FindConstant(CstFF);
1216
1217 // Add shift amount constant.
1218 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
1219 uint64_t Idx = CI->getZExtValue();
1220 Constant *CstShiftAmount =
1221 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1222 FindConstant(CstShiftAmount);
1223 }
1224
1225 continue;
1226 }
1227
1228 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1229 // Ignore constant for index of InsertElement instruction.
1230 if (i == 2) {
1231 continue;
1232 }
1233
1234 if (isa<Constant>(I.getOperand(i)) &&
1235 !isa<GlobalValue>(I.getOperand(i))) {
1236 FindConstant(I.getOperand(i));
1237 }
1238 }
1239
1240 continue;
1241 } else if (isa<ExtractElementInst>(I)) {
1242 // Handle ExtractElement with <4 x i8> specially.
1243 Type *CompositeTy = I.getOperand(0)->getType();
1244 if (is4xi8vec(CompositeTy)) {
1245 LLVMContext &Context = CompositeTy->getContext();
1246 if (isa<Constant>(I.getOperand(0))) {
1247 FindConstant(I.getOperand(0));
1248 }
1249
1250 // Add mask constant 0xFF.
1251 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
1252 FindConstant(CstFF);
1253
1254 // Add shift amount constant.
1255 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1256 uint64_t Idx = CI->getZExtValue();
1257 Constant *CstShiftAmount =
1258 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
1259 FindConstant(CstShiftAmount);
1260 } else {
1261 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
1262 FindConstant(Cst8);
1263 }
1264
1265 continue;
1266 }
1267
1268 for (unsigned i = 0; i < I.getNumOperands(); i++) {
1269 // Ignore constant for index of ExtractElement instruction.
1270 if (i == 1) {
1271 continue;
1272 }
1273
1274 if (isa<Constant>(I.getOperand(i)) &&
1275 !isa<GlobalValue>(I.getOperand(i))) {
1276 FindConstant(I.getOperand(i));
1277 }
1278 }
1279
1280 continue;
1281 } else if ((Instruction::Xor == I.getOpcode()) && I.getType()->isIntegerTy(1)) {
1282 // 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
1283 bool foundConstantTrue = false;
1284 for (Use &Op : I.operands()) {
1285 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1286 auto CI = cast<ConstantInt>(Op);
1287
1288 if (CI->isZero() || foundConstantTrue) {
1289 // 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.
1290 FindConstant(Op);
1291 } else {
1292 foundConstantTrue = true;
1293 }
1294 }
1295 }
1296
1297 continue;
David Netod2de94a2017-08-28 17:27:47 -04001298 } else if (isa<TruncInst>(I)) {
1299 // For truncation to i8 we mask against 255.
1300 Type *ToTy = I.getType();
1301 if (8u == ToTy->getPrimitiveSizeInBits()) {
1302 LLVMContext &Context = ToTy->getContext();
1303 Constant *Cst255 = ConstantInt::get(Type::getInt32Ty(Context), 0xff);
1304 FindConstant(Cst255);
1305 }
1306 // Fall through.
Neil Henning39672102017-09-29 14:33:13 +01001307 } else if (isa<AtomicRMWInst>(I)) {
1308 LLVMContext &Context = I.getContext();
1309
1310 FindConstant(
1311 ConstantInt::get(Type::getInt32Ty(Context), spv::ScopeDevice));
1312 FindConstant(ConstantInt::get(
1313 Type::getInt32Ty(Context),
1314 spv::MemorySemanticsUniformMemoryMask |
1315 spv::MemorySemanticsSequentiallyConsistentMask));
David Neto22f144c2017-06-12 14:26:21 -04001316 }
1317
1318 for (Use &Op : I.operands()) {
1319 if (isa<Constant>(Op) && !isa<GlobalValue>(Op)) {
1320 FindConstant(Op);
1321 }
1322 }
1323 }
1324 }
1325}
1326
1327void SPIRVProducerPass::FindConstant(Value *V) {
David Neto22f144c2017-06-12 14:26:21 -04001328 ValueList &CstList = getConstantList();
1329
David Netofb9a7972017-08-25 17:08:24 -04001330 // If V is already tracked, ignore it.
1331 if (0 != CstList.idFor(V)) {
David Neto22f144c2017-06-12 14:26:21 -04001332 return;
1333 }
1334
1335 Constant *Cst = cast<Constant>(V);
1336
1337 // Handle constant with <4 x i8> type specially.
1338 Type *CstTy = Cst->getType();
1339 if (is4xi8vec(CstTy)) {
1340 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001341 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001342 }
1343 }
1344
1345 if (Cst->getNumOperands()) {
1346 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end(); I != E;
1347 ++I) {
1348 FindConstant(*I);
1349 }
1350
David Netofb9a7972017-08-25 17:08:24 -04001351 CstList.insert(Cst);
David Neto22f144c2017-06-12 14:26:21 -04001352 return;
1353 } else if (const ConstantDataSequential *CDS =
1354 dyn_cast<ConstantDataSequential>(Cst)) {
1355 // Add constants for each element to constant list.
1356 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
1357 Constant *EleCst = CDS->getElementAsConstant(i);
1358 FindConstant(EleCst);
1359 }
1360 }
1361
1362 if (!isa<GlobalValue>(V)) {
David Netofb9a7972017-08-25 17:08:24 -04001363 CstList.insert(V);
David Neto22f144c2017-06-12 14:26:21 -04001364 }
1365}
1366
1367spv::StorageClass SPIRVProducerPass::GetStorageClass(unsigned AddrSpace) const {
1368 switch (AddrSpace) {
1369 default:
1370 llvm_unreachable("Unsupported OpenCL address space");
1371 case AddressSpace::Private:
1372 return spv::StorageClassFunction;
1373 case AddressSpace::Global:
1374 case AddressSpace::Constant:
1375 return spv::StorageClassStorageBuffer;
1376 case AddressSpace::Input:
1377 return spv::StorageClassInput;
1378 case AddressSpace::Local:
1379 return spv::StorageClassWorkgroup;
1380 case AddressSpace::UniformConstant:
1381 return spv::StorageClassUniformConstant;
1382 case AddressSpace::ModuleScopePrivate:
1383 return spv::StorageClassPrivate;
1384 }
1385}
1386
1387spv::BuiltIn SPIRVProducerPass::GetBuiltin(StringRef Name) const {
1388 return StringSwitch<spv::BuiltIn>(Name)
1389 .Case("__spirv_GlobalInvocationId", spv::BuiltInGlobalInvocationId)
1390 .Case("__spirv_LocalInvocationId", spv::BuiltInLocalInvocationId)
1391 .Case("__spirv_WorkgroupSize", spv::BuiltInWorkgroupSize)
1392 .Case("__spirv_NumWorkgroups", spv::BuiltInNumWorkgroups)
1393 .Case("__spirv_WorkgroupId", spv::BuiltInWorkgroupId)
1394 .Default(spv::BuiltInMax);
1395}
1396
1397void SPIRVProducerPass::GenerateExtInstImport() {
1398 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1399 uint32_t &ExtInstImportID = getOpExtInstImportID();
1400
1401 //
1402 // Generate OpExtInstImport.
1403 //
1404 // Ops[0] ... Ops[n] = Name (Literal String)
1405 SPIRVOperandList Ops;
1406
1407 SPIRVOperand *Name =
1408 new SPIRVOperand(SPIRVOperandType::LITERAL_STRING, "GLSL.std.450");
1409 Ops.push_back(Name);
1410
1411 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
1412 assert(NameWordSize < (UINT16_MAX - 2));
1413 if ((Name->getLiteralStr().size() + 1) % 4) {
1414 NameWordSize += 1;
1415 }
1416
1417 uint16_t WordCount = static_cast<uint16_t>(2 + NameWordSize);
1418 ExtInstImportID = nextID;
1419
1420 SPIRVInstruction *Inst =
1421 new SPIRVInstruction(WordCount, spv::OpExtInstImport, nextID++, Ops);
1422 SPIRVInstList.push_back(Inst);
1423}
1424
1425void SPIRVProducerPass::GenerateSPIRVTypes(const DataLayout &DL) {
1426 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1427 ValueMapType &VMap = getValueMap();
1428 ValueMapType &AllocatedVMap = getAllocatedValueMap();
1429 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
1430
1431 // Map for OpTypeRuntimeArray. If argument has pointer type, 2 spirv type
1432 // instructions are generated. They are OpTypePointer and OpTypeRuntimeArray.
1433 DenseMap<Type *, uint32_t> OpRuntimeTyMap;
1434
1435 for (Type *Ty : getTypeList()) {
1436 // Update TypeMap with nextID for reference later.
1437 TypeMap[Ty] = nextID;
1438
1439 switch (Ty->getTypeID()) {
1440 default: {
1441 Ty->print(errs());
1442 llvm_unreachable("Unsupported type???");
1443 break;
1444 }
1445 case Type::MetadataTyID:
1446 case Type::LabelTyID: {
1447 // Ignore these types.
1448 break;
1449 }
1450 case Type::PointerTyID: {
1451 PointerType *PTy = cast<PointerType>(Ty);
1452 unsigned AddrSpace = PTy->getAddressSpace();
1453
1454 // For the purposes of our Vulkan SPIR-V type system, constant and global
1455 // are conflated.
1456 bool UseExistingOpTypePointer = false;
1457 if (AddressSpace::Constant == AddrSpace) {
1458 AddrSpace = AddressSpace::Global;
1459
1460 // Check to see if we already created this type (for instance, if we had
1461 // a constant <type>* and a global <type>*, the type would be created by
1462 // one of these types, and shared by both).
1463 auto GlobalTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1464 if (0 < TypeMap.count(GlobalTy)) {
1465 TypeMap[PTy] = TypeMap[GlobalTy];
1466 break;
1467 }
1468 } else if (AddressSpace::Global == AddrSpace) {
1469 AddrSpace = AddressSpace::Constant;
1470
1471 // Check to see if we already created this type (for instance, if we had
1472 // a constant <type>* and a global <type>*, the type would be created by
1473 // one of these types, and shared by both).
1474 auto ConstantTy = PTy->getPointerElementType()->getPointerTo(AddrSpace);
1475 if (0 < TypeMap.count(ConstantTy)) {
1476 TypeMap[PTy] = TypeMap[ConstantTy];
1477 UseExistingOpTypePointer = true;
1478 }
1479 }
1480
1481 bool IsOpTypeRuntimeArray = false;
1482 bool HasArgUser = false;
1483
1484 for (auto ArgGV : ArgGVMap) {
1485 auto Arg = ArgGV.first;
1486
1487 Type *ArgTy = Arg->getType();
1488 if (ArgTy == PTy) {
1489 if (AddrSpace != AddressSpace::UniformConstant) {
1490 IsOpTypeRuntimeArray = true;
1491 }
1492
1493 for (auto U : Arg->users()) {
1494 if (!isa<GetElementPtrInst>(U) || (U->getType() == PTy)) {
1495 HasArgUser = true;
1496 break;
1497 }
1498 }
1499 }
1500 }
1501
1502 if ((!IsOpTypeRuntimeArray || HasArgUser) && !UseExistingOpTypePointer) {
1503 //
1504 // Generate OpTypePointer.
1505 //
1506
1507 // OpTypePointer
1508 // Ops[0] = Storage Class
1509 // Ops[1] = Element Type ID
1510 SPIRVOperandList Ops;
1511
1512 spv::StorageClass StorageClass = GetStorageClass(AddrSpace);
1513
1514 SPIRVOperand *StorageClassOp =
1515 new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass);
1516 Ops.push_back(StorageClassOp);
1517
1518 uint32_t EleTyID = lookupType(PTy->getElementType());
1519 SPIRVOperand *EleTyOp =
1520 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1521 Ops.push_back(EleTyOp);
1522
1523 spv::Op Opcode = spv::OpTypePointer;
1524 uint16_t WordCount = 4;
1525
1526 SPIRVInstruction *Inst =
1527 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1528 SPIRVInstList.push_back(Inst);
1529 }
1530
1531 if (IsOpTypeRuntimeArray) {
1532 //
1533 // Generate OpTypeRuntimeArray.
1534 //
1535
1536 // OpTypeRuntimeArray
1537 // Ops[0] = Element Type ID
1538 SPIRVOperandList Ops;
1539
1540 uint32_t EleTyID = lookupType(PTy->getElementType());
1541 SPIRVOperand *EleTyOp =
1542 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1543 Ops.push_back(EleTyOp);
1544
1545 spv::Op Opcode = spv::OpTypeRuntimeArray;
1546 uint16_t WordCount = 3;
1547
1548 uint32_t OpTypeRuntimeArrayID = nextID;
1549 assert(0 == OpRuntimeTyMap.count(Ty));
1550 OpRuntimeTyMap[Ty] = nextID;
1551
1552 SPIRVInstruction *Inst =
1553 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
1554 SPIRVInstList.push_back(Inst);
1555
1556 // Generate OpDecorate.
1557 auto DecoInsertPoint =
1558 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1559 [](SPIRVInstruction *Inst) -> bool {
1560 return Inst->getOpcode() != spv::OpDecorate &&
1561 Inst->getOpcode() != spv::OpMemberDecorate &&
1562 Inst->getOpcode() != spv::OpExtInstImport;
1563 });
1564
1565 // Ops[0] = Target ID
1566 // Ops[1] = Decoration (ArrayStride)
1567 // Ops[2] = Stride Number(Literal Number)
1568 Ops.clear();
1569
1570 SPIRVOperand *PTyIDOp =
1571 new SPIRVOperand(SPIRVOperandType::NUMBERID, OpTypeRuntimeArrayID);
1572 Ops.push_back(PTyIDOp);
1573
1574 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID,
1575 spv::DecorationArrayStride);
1576 Ops.push_back(DecoOp);
1577
1578 std::vector<uint32_t> LiteralNum;
1579 Type *EleTy = PTy->getElementType();
Neil Henning39672102017-09-29 14:33:13 +01001580 LiteralNum.push_back(static_cast<uint32_t>(DL.getTypeAllocSize(EleTy)));
David Neto22f144c2017-06-12 14:26:21 -04001581 SPIRVOperand *ArrayStrideOp =
1582 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1583 Ops.push_back(ArrayStrideOp);
1584
1585 SPIRVInstruction *DecoInst =
1586 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
1587 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1588 }
1589 break;
1590 }
1591 case Type::StructTyID: {
1592 LLVMContext &Context = Ty->getContext();
1593
1594 StructType *STy = cast<StructType>(Ty);
1595
1596 // Handle sampler type.
1597 if (STy->isOpaque()) {
1598 if (STy->getName().equals("opencl.sampler_t")) {
1599 //
1600 // Generate OpTypeSampler
1601 //
1602 // Empty Ops.
1603 SPIRVOperandList Ops;
1604
1605 SPIRVInstruction *Inst =
1606 new SPIRVInstruction(2, spv::OpTypeSampler, nextID++, Ops);
1607 SPIRVInstList.push_back(Inst);
1608 break;
1609 } else if (STy->getName().equals("opencl.image2d_ro_t") ||
1610 STy->getName().equals("opencl.image2d_wo_t") ||
1611 STy->getName().equals("opencl.image3d_ro_t") ||
1612 STy->getName().equals("opencl.image3d_wo_t")) {
1613 //
1614 // Generate OpTypeImage
1615 //
1616 // Ops[0] = Sampled Type ID
1617 // Ops[1] = Dim ID
1618 // Ops[2] = Depth (Literal Number)
1619 // Ops[3] = Arrayed (Literal Number)
1620 // Ops[4] = MS (Literal Number)
1621 // Ops[5] = Sampled (Literal Number)
1622 // Ops[6] = Image Format ID
1623 //
1624 SPIRVOperandList Ops;
1625
1626 // TODO: Changed Sampled Type according to situations.
1627 uint32_t SampledTyID = lookupType(Type::getFloatTy(Context));
1628 SPIRVOperand *SampledTyIDOp =
1629 new SPIRVOperand(SPIRVOperandType::NUMBERID, SampledTyID);
1630 Ops.push_back(SampledTyIDOp);
1631
1632 spv::Dim DimID = spv::Dim2D;
1633 if (STy->getName().equals("opencl.image3d_ro_t") ||
1634 STy->getName().equals("opencl.image3d_wo_t")) {
1635 DimID = spv::Dim3D;
1636 }
1637 SPIRVOperand *DimIDOp =
1638 new SPIRVOperand(SPIRVOperandType::NUMBERID, DimID);
1639 Ops.push_back(DimIDOp);
1640
1641 // TODO: Set up Depth.
1642 std::vector<uint32_t> LiteralNum;
1643 LiteralNum.push_back(0);
1644 SPIRVOperand *DepthOp =
1645 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1646 Ops.push_back(DepthOp);
1647
1648 // TODO: Set up Arrayed.
1649 LiteralNum.clear();
1650 LiteralNum.push_back(0);
1651 SPIRVOperand *ArrayedOp =
1652 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1653 Ops.push_back(ArrayedOp);
1654
1655 // TODO: Set up MS.
1656 LiteralNum.clear();
1657 LiteralNum.push_back(0);
1658 SPIRVOperand *MSOp =
1659 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1660 Ops.push_back(MSOp);
1661
1662 // TODO: Set up Sampled.
1663 //
1664 // From Spec
1665 //
1666 // 0 indicates this is only known at run time, not at compile time
1667 // 1 indicates will be used with sampler
1668 // 2 indicates will be used without a sampler (a storage image)
1669 uint32_t Sampled = 1;
1670 if (STy->getName().equals("opencl.image2d_wo_t") ||
1671 STy->getName().equals("opencl.image3d_wo_t")) {
1672 Sampled = 2;
1673 }
1674 LiteralNum.clear();
1675 LiteralNum.push_back(Sampled);
1676 SPIRVOperand *SampledOp =
1677 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1678 Ops.push_back(SampledOp);
1679
1680 // TODO: Set up Image Format.
1681 SPIRVOperand *ImageFormatOp = new SPIRVOperand(
1682 SPIRVOperandType::NUMBERID, spv::ImageFormatUnknown);
1683 Ops.push_back(ImageFormatOp);
1684
1685 SPIRVInstruction *Inst =
1686 new SPIRVInstruction(9, spv::OpTypeImage, nextID++, Ops);
1687 SPIRVInstList.push_back(Inst);
1688 break;
1689 }
1690 }
1691
1692 //
1693 // Generate OpTypeStruct
1694 //
1695 // Ops[0] ... Ops[n] = Member IDs
1696 SPIRVOperandList Ops;
1697
1698 for (auto *EleTy : STy->elements()) {
1699 uint32_t EleTyID = lookupType(EleTy);
1700
1701 // Check OpTypeRuntimeArray.
1702 if (isa<PointerType>(EleTy)) {
1703 for (auto ArgGV : ArgGVMap) {
1704 Type *ArgTy = ArgGV.first->getType();
1705 if (ArgTy == EleTy) {
1706 assert(0 != OpRuntimeTyMap.count(EleTy));
1707 EleTyID = OpRuntimeTyMap[EleTy];
1708 }
1709 }
1710 }
1711
1712 SPIRVOperand *EleTyOp =
1713 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1714 Ops.push_back(EleTyOp);
1715 }
1716
1717 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1718 uint32_t STyID = nextID;
1719
1720 SPIRVInstruction *Inst =
1721 new SPIRVInstruction(WordCount, spv::OpTypeStruct, nextID++, Ops);
1722 SPIRVInstList.push_back(Inst);
1723
1724 // Generate OpMemberDecorate.
1725 auto DecoInsertPoint =
1726 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
1727 [](SPIRVInstruction *Inst) -> bool {
1728 return Inst->getOpcode() != spv::OpDecorate &&
1729 Inst->getOpcode() != spv::OpMemberDecorate &&
1730 Inst->getOpcode() != spv::OpExtInstImport;
1731 });
1732
David Netoc463b372017-08-10 15:32:21 -04001733 const auto StructLayout = DL.getStructLayout(STy);
1734
David Neto22f144c2017-06-12 14:26:21 -04001735 for (unsigned MemberIdx = 0; MemberIdx < STy->getNumElements();
1736 MemberIdx++) {
1737 // Ops[0] = Structure Type ID
1738 // Ops[1] = Member Index(Literal Number)
1739 // Ops[2] = Decoration (Offset)
1740 // Ops[3] = Byte Offset (Literal Number)
1741 Ops.clear();
1742
1743 SPIRVOperand *STyIDOp =
1744 new SPIRVOperand(SPIRVOperandType::NUMBERID, STyID);
1745 Ops.push_back(STyIDOp);
1746
1747 std::vector<uint32_t> LiteralNum;
1748 LiteralNum.push_back(MemberIdx);
1749 SPIRVOperand *MemberIdxOp =
1750 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1751 Ops.push_back(MemberIdxOp);
1752
1753 SPIRVOperand *DecoOp =
1754 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationOffset);
1755 Ops.push_back(DecoOp);
1756
1757 LiteralNum.clear();
David Netoc463b372017-08-10 15:32:21 -04001758 const auto ByteOffset =
1759 uint32_t(StructLayout->getElementOffset(MemberIdx));
David Neto22f144c2017-06-12 14:26:21 -04001760 LiteralNum.push_back(ByteOffset);
1761 SPIRVOperand *ByteOffsetOp =
1762 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1763 Ops.push_back(ByteOffsetOp);
1764
1765 SPIRVInstruction *DecoInst =
1766 new SPIRVInstruction(5, spv::OpMemberDecorate, 0 /* No id */, Ops);
1767 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
David Neto22f144c2017-06-12 14:26:21 -04001768 }
1769
1770 // Generate OpDecorate.
1771 for (auto ArgGV : ArgGVMap) {
1772 Type *ArgGVTy = ArgGV.second->getType();
1773 PointerType *PTy = cast<PointerType>(ArgGVTy);
1774 Type *ArgTy = PTy->getElementType();
1775
1776 // Struct type from argument is already distinguished with the other
1777 // struct types on llvm types. As a result, if current processing struct
1778 // type is same with argument type, we can generate OpDecorate with
1779 // Block or BufferBlock.
1780 if (ArgTy == STy) {
1781 // Ops[0] = Target ID
1782 // Ops[1] = Decoration (Block or BufferBlock)
1783 Ops.clear();
1784
1785 SPIRVOperand *STyIDOp =
1786 new SPIRVOperand(SPIRVOperandType::NUMBERID, STyID);
1787 Ops.push_back(STyIDOp);
1788
David Neto6e392822017-08-04 14:06:10 -04001789 // Use Block decorations with StorageBuffer storage class.
1790 const spv::Decoration Deco = spv::DecorationBlock;
David Neto22f144c2017-06-12 14:26:21 -04001791
1792 SPIRVOperand *DecoOp =
1793 new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
1794 Ops.push_back(DecoOp);
1795
1796 SPIRVInstruction *DecoInst =
1797 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
1798 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
1799 break;
1800 }
1801 }
1802 break;
1803 }
1804 case Type::IntegerTyID: {
1805 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1806
1807 if (BitWidth == 1) {
1808 SPIRVInstruction *Inst =
1809 new SPIRVInstruction(2, spv::OpTypeBool, nextID++, {});
1810 SPIRVInstList.push_back(Inst);
1811 } else {
1812 // i8 is added to TypeMap as i32.
David Neto391aeb12017-08-26 15:51:58 -04001813 // No matter what LLVM type is requested first, always alias the
1814 // second one's SPIR-V type to be the same as the one we generated
1815 // first.
Neil Henning39672102017-09-29 14:33:13 +01001816 unsigned aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001817 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001818 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001819 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001820 } else if (BitWidth == 32) {
1821 aliasToWidth = 8;
1822 }
1823 if (aliasToWidth) {
1824 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1825 auto where = TypeMap.find(otherType);
1826 if (where == TypeMap.end()) {
1827 // Go ahead and make it, but also map the other type to it.
1828 TypeMap[otherType] = nextID;
1829 } else {
1830 // Alias this SPIR-V type the existing type.
1831 TypeMap[Ty] = where->second;
1832 break;
1833 }
David Neto22f144c2017-06-12 14:26:21 -04001834 }
1835
1836 SPIRVOperand *Ops[2] = {
1837 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, BitWidth),
1838 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, 0u)};
1839
1840 SPIRVInstList.push_back(
1841 new SPIRVInstruction(4, spv::OpTypeInt, nextID++, Ops));
1842 }
1843 break;
1844 }
1845 case Type::HalfTyID:
1846 case Type::FloatTyID:
1847 case Type::DoubleTyID: {
1848 SPIRVOperand *WidthOp = new SPIRVOperand(
1849 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1850
1851 SPIRVInstList.push_back(
1852 new SPIRVInstruction(3, spv::OpTypeFloat, nextID++, WidthOp));
1853 break;
1854 }
1855 case Type::ArrayTyID: {
1856 LLVMContext &Context = Ty->getContext();
1857 ArrayType *ArrTy = cast<ArrayType>(Ty);
1858 //
1859 // Generate OpConstant and OpTypeArray.
1860 //
1861
1862 //
1863 // Generate OpConstant for array length.
1864 //
1865 // Ops[0] = Result Type ID
1866 // Ops[1] .. Ops[n] = Values LiteralNumber
1867 SPIRVOperandList Ops;
1868
1869 Type *LengthTy = Type::getInt32Ty(Context);
1870 uint32_t ResTyID = lookupType(LengthTy);
1871 SPIRVOperand *ResTyOp =
1872 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
1873 Ops.push_back(ResTyOp);
1874
1875 uint64_t Length = ArrTy->getArrayNumElements();
1876 assert(Length < UINT32_MAX);
1877 std::vector<uint32_t> LiteralNum;
1878 LiteralNum.push_back(static_cast<uint32_t>(Length));
1879 SPIRVOperand *ValOp =
1880 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1881 Ops.push_back(ValOp);
1882
1883 // Add constant for length to constant list.
1884 Constant *CstLength = ConstantInt::get(LengthTy, Length);
1885 AllocatedVMap[CstLength] = nextID;
1886 VMap[CstLength] = nextID;
1887 uint32_t LengthID = nextID;
1888
1889 SPIRVInstruction *CstInst =
1890 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
1891 SPIRVInstList.push_back(CstInst);
1892
1893 //
1894 // Generate OpTypeArray.
1895 //
1896 // Ops[0] = Element Type ID
1897 // Ops[1] = Array Length Constant ID
1898 Ops.clear();
1899
1900 uint32_t EleTyID = lookupType(ArrTy->getElementType());
1901 SPIRVOperand *EleTyOp =
1902 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1903 Ops.push_back(EleTyOp);
1904
1905 SPIRVOperand *LengthOp =
1906 new SPIRVOperand(SPIRVOperandType::NUMBERID, LengthID);
1907 Ops.push_back(LengthOp);
1908
1909 // Update TypeMap with nextID.
1910 TypeMap[Ty] = nextID;
1911
1912 SPIRVInstruction *ArrayInst =
1913 new SPIRVInstruction(4, spv::OpTypeArray, nextID++, Ops);
1914 SPIRVInstList.push_back(ArrayInst);
1915 break;
1916 }
1917 case Type::VectorTyID: {
1918 // <4 x i8> is changed to i32.
1919 LLVMContext &Context = Ty->getContext();
1920 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
1921 if (Ty->getVectorNumElements() == 4) {
1922 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
1923 break;
1924 } else {
1925 Ty->print(errs());
1926 llvm_unreachable("Support above i8 vector type");
1927 }
1928 }
1929
1930 // Ops[0] = Component Type ID
1931 // Ops[1] = Component Count (Literal Number)
1932 SPIRVOperand *Ops[2] = {
1933 new SPIRVOperand(SPIRVOperandType::NUMBERID,
1934 lookupType(Ty->getVectorElementType())),
1935 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
1936 Ty->getVectorNumElements())};
1937
1938 SPIRVInstList.push_back(
1939 new SPIRVInstruction(4, spv::OpTypeVector, nextID++, Ops));
1940 break;
1941 }
1942 case Type::VoidTyID: {
1943 SPIRVInstruction *Inst =
1944 new SPIRVInstruction(2, spv::OpTypeVoid, nextID++, {});
1945 SPIRVInstList.push_back(Inst);
1946 break;
1947 }
1948 case Type::FunctionTyID: {
1949 // Generate SPIRV instruction for function type.
1950 FunctionType *FTy = cast<FunctionType>(Ty);
1951
1952 // Ops[0] = Return Type ID
1953 // Ops[1] ... Ops[n] = Parameter Type IDs
1954 SPIRVOperandList Ops;
1955
1956 // Find SPIRV instruction for return type
1957 uint32_t RetTyID = lookupType(FTy->getReturnType());
1958
1959 SPIRVOperand *RetTyOp =
1960 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
1961 Ops.push_back(RetTyOp);
1962
1963 // Find SPIRV instructions for parameter types
1964 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1965 // Find SPIRV instruction for parameter type.
1966 auto ParamTy = FTy->getParamType(k);
1967 if (ParamTy->isPointerTy()) {
1968 auto PointeeTy = ParamTy->getPointerElementType();
1969 if (PointeeTy->isStructTy() &&
1970 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1971 ParamTy = PointeeTy;
1972 }
1973 }
1974
1975 uint32_t ParamTyID = lookupType(ParamTy);
1976 SPIRVOperand *ParamTyOp =
1977 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
1978 Ops.push_back(ParamTyOp);
1979 }
1980
1981 // Return type id is included in operand list.
1982 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1983
1984 SPIRVInstruction *Inst =
1985 new SPIRVInstruction(WordCount, spv::OpTypeFunction, nextID++, Ops);
1986 SPIRVInstList.push_back(Inst);
1987 break;
1988 }
1989 }
1990 }
1991
1992 // Generate OpTypeSampledImage.
1993 TypeMapType &OpImageTypeMap = getImageTypeMap();
1994 for (auto &ImageType : OpImageTypeMap) {
1995 //
1996 // Generate OpTypeSampledImage.
1997 //
1998 // Ops[0] = Image Type ID
1999 //
2000 SPIRVOperandList Ops;
2001
2002 Type *ImgTy = ImageType.first;
2003 uint32_t ImgTyID = TypeMap[ImgTy];
2004 SPIRVOperand *ImgTyOp =
2005 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImgTyID);
2006 Ops.push_back(ImgTyOp);
2007
2008 // Update OpImageTypeMap.
2009 ImageType.second = nextID;
2010
2011 SPIRVInstruction *Inst =
2012 new SPIRVInstruction(3, spv::OpTypeSampledImage, nextID++, Ops);
2013 SPIRVInstList.push_back(Inst);
2014 }
2015}
2016
2017void SPIRVProducerPass::GenerateSPIRVConstants() {
2018 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2019 ValueMapType &VMap = getValueMap();
2020 ValueMapType &AllocatedVMap = getAllocatedValueMap();
2021 ValueList &CstList = getConstantList();
2022
2023 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04002024 // UniqueVector ids are 1-based.
2025 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04002026
2027 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04002028 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04002029 continue;
2030 }
2031
David Netofb9a7972017-08-25 17:08:24 -04002032 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04002033 VMap[Cst] = nextID;
2034
2035 //
2036 // Generate OpConstant.
2037 //
2038
2039 // Ops[0] = Result Type ID
2040 // Ops[1] .. Ops[n] = Values LiteralNumber
2041 SPIRVOperandList Ops;
2042
2043 uint32_t ResTyID = lookupType(Cst->getType());
2044 SPIRVOperand *ResTyIDOp =
2045 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
2046 Ops.push_back(ResTyIDOp);
2047
2048 std::vector<uint32_t> LiteralNum;
2049 uint16_t WordCount = 0;
2050 spv::Op Opcode = spv::OpNop;
2051
2052 if (isa<UndefValue>(Cst)) {
2053 // Ops[0] = Result Type ID
David Netoc66b3352017-10-20 14:28:46 -04002054 Opcode = spv::OpUndef;
2055 if (hack_undef) {
2056 Type *type = Cst->getType();
2057 if (type->isFPOrFPVectorTy() || type->isIntOrIntVectorTy()) {
2058 Opcode = spv::OpConstantNull;
2059 }
2060 }
David Neto22f144c2017-06-12 14:26:21 -04002061 WordCount = 3;
2062 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
2063 unsigned BitWidth = CI->getBitWidth();
2064 if (BitWidth == 1) {
2065 // If the bitwidth of constant is 1, generate OpConstantTrue or
2066 // OpConstantFalse.
2067 if (CI->getZExtValue()) {
2068 // Ops[0] = Result Type ID
2069 Opcode = spv::OpConstantTrue;
2070 } else {
2071 // Ops[0] = Result Type ID
2072 Opcode = spv::OpConstantFalse;
2073 }
2074 WordCount = 3;
2075 } else {
2076 auto V = CI->getZExtValue();
2077 LiteralNum.push_back(V & 0xFFFFFFFF);
2078
2079 if (BitWidth > 32) {
2080 LiteralNum.push_back(V >> 32);
2081 }
2082
2083 Opcode = spv::OpConstant;
2084 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2085
2086 SPIRVOperand *CstValue =
2087 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2088 Ops.push_back(CstValue);
2089 }
2090 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
2091 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
2092 Type *CFPTy = CFP->getType();
2093 if (CFPTy->isFloatTy()) {
2094 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
2095 } else {
2096 CFPTy->print(errs());
2097 llvm_unreachable("Implement this ConstantFP Type");
2098 }
2099
2100 Opcode = spv::OpConstant;
2101 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
2102
2103 SPIRVOperand *CstValue =
2104 new SPIRVOperand(SPIRVOperandType::LITERAL_FLOAT, LiteralNum);
2105 Ops.push_back(CstValue);
2106 } else if (isa<ConstantDataSequential>(Cst) &&
2107 cast<ConstantDataSequential>(Cst)->isString()) {
2108 Cst->print(errs());
2109 llvm_unreachable("Implement this Constant");
2110
2111 } else if (const ConstantDataSequential *CDS =
2112 dyn_cast<ConstantDataSequential>(Cst)) {
David Neto49351ac2017-08-26 17:32:20 -04002113 // Let's convert <4 x i8> constant to int constant specially.
2114 // This case occurs when all the values are specified as constant
2115 // ints.
2116 Type *CstTy = Cst->getType();
2117 if (is4xi8vec(CstTy)) {
2118 LLVMContext &Context = CstTy->getContext();
2119
2120 //
2121 // Generate OpConstant with OpTypeInt 32 0.
2122 //
Neil Henning39672102017-09-29 14:33:13 +01002123 uint32_t IntValue = 0;
2124 for (unsigned k = 0; k < 4; k++) {
2125 const uint64_t Val = CDS->getElementAsInteger(k);
David Neto49351ac2017-08-26 17:32:20 -04002126 IntValue = (IntValue << 8) | (Val & 0xffu);
2127 }
2128
2129 Type *i32 = Type::getInt32Ty(Context);
2130 Constant *CstInt = ConstantInt::get(i32, IntValue);
2131 // If this constant is already registered on VMap, use it.
2132 if (VMap.count(CstInt)) {
2133 uint32_t CstID = VMap[CstInt];
2134 VMap[Cst] = CstID;
2135 continue;
2136 }
2137
2138 LiteralNum.push_back(IntValue);
2139 SPIRVOperand *CstValue =
2140 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2141 Ops.push_back(CstValue);
2142
2143 SPIRVInstruction *CstInst =
2144 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2145 SPIRVInstList.push_back(CstInst);
2146
2147 continue;
2148 }
2149
2150 // A normal constant-data-sequential case.
David Neto22f144c2017-06-12 14:26:21 -04002151 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
2152 Constant *EleCst = CDS->getElementAsConstant(k);
2153 uint32_t EleCstID = VMap[EleCst];
2154 SPIRVOperand *EleCstIDOp =
2155 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleCstID);
2156 Ops.push_back(EleCstIDOp);
2157 }
2158
2159 Opcode = spv::OpConstantComposite;
2160 WordCount = static_cast<uint16_t>(3 + CDS->getNumElements());
2161 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
2162 // Let's convert <4 x i8> constant to int constant specially.
David Neto49351ac2017-08-26 17:32:20 -04002163 // This case occurs when at least one of the values is an undef.
David Neto22f144c2017-06-12 14:26:21 -04002164 Type *CstTy = Cst->getType();
2165 if (is4xi8vec(CstTy)) {
2166 LLVMContext &Context = CstTy->getContext();
2167
2168 //
2169 // Generate OpConstant with OpTypeInt 32 0.
2170 //
Neil Henning39672102017-09-29 14:33:13 +01002171 uint32_t IntValue = 0;
David Neto22f144c2017-06-12 14:26:21 -04002172 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
2173 I != E; ++I) {
2174 uint64_t Val = 0;
David Neto49351ac2017-08-26 17:32:20 -04002175 const Value* CV = *I;
Neil Henning39672102017-09-29 14:33:13 +01002176 if (auto *CI2 = dyn_cast<ConstantInt>(CV)) {
2177 Val = CI2->getZExtValue();
David Neto22f144c2017-06-12 14:26:21 -04002178 }
David Neto49351ac2017-08-26 17:32:20 -04002179 IntValue = (IntValue << 8) | (Val & 0xffu);
David Neto22f144c2017-06-12 14:26:21 -04002180 }
2181
David Neto49351ac2017-08-26 17:32:20 -04002182 Type *i32 = Type::getInt32Ty(Context);
2183 Constant *CstInt = ConstantInt::get(i32, IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002184 // If this constant is already registered on VMap, use it.
2185 if (VMap.count(CstInt)) {
2186 uint32_t CstID = VMap[CstInt];
2187 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04002188 continue;
David Neto22f144c2017-06-12 14:26:21 -04002189 }
2190
David Neto49351ac2017-08-26 17:32:20 -04002191 LiteralNum.push_back(IntValue);
David Neto22f144c2017-06-12 14:26:21 -04002192 SPIRVOperand *CstValue =
2193 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2194 Ops.push_back(CstValue);
2195
2196 SPIRVInstruction *CstInst =
2197 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
2198 SPIRVInstList.push_back(CstInst);
2199
David Neto19a1bad2017-08-25 15:01:41 -04002200 continue;
David Neto22f144c2017-06-12 14:26:21 -04002201 }
2202
2203 // We use a constant composite in SPIR-V for our constant aggregate in
2204 // LLVM.
2205 Opcode = spv::OpConstantComposite;
2206 WordCount = static_cast<uint16_t>(3 + CA->getNumOperands());
2207
2208 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
2209 // Look up the ID of the element of this aggregate (which we will
2210 // previously have created a constant for).
2211 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2212
2213 // And add an operand to the composite we are constructing
2214 Ops.push_back(
2215 new SPIRVOperand(SPIRVOperandType::NUMBERID, ElementConstantID));
2216 }
2217 } else if (Cst->isNullValue()) {
2218 Opcode = spv::OpConstantNull;
2219 WordCount = 3;
2220 } else {
2221 Cst->print(errs());
2222 llvm_unreachable("Unsupported Constant???");
2223 }
2224
2225 SPIRVInstruction *CstInst =
2226 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
2227 SPIRVInstList.push_back(CstInst);
2228 }
2229}
2230
2231void SPIRVProducerPass::GenerateSamplers(Module &M) {
2232 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2233 ValueMapType &VMap = getValueMap();
2234
2235 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
2236
2237 unsigned BindingIdx = 0;
2238
2239 // Generate the sampler map.
2240 for (auto SamplerLiteral : getSamplerMap()) {
2241 // Generate OpVariable.
2242 //
2243 // GIDOps[0] : Result Type ID
2244 // GIDOps[1] : Storage Class
2245 SPIRVOperandList Ops;
2246
2247 Ops.push_back(
2248 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(SamplerTy)));
2249
2250 spv::StorageClass StorageClass = spv::StorageClassUniformConstant;
2251 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2252
2253 SPIRVInstruction *Inst = new SPIRVInstruction(
2254 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID, Ops);
2255 SPIRVInstList.push_back(Inst);
2256
David Neto44795152017-07-13 15:45:28 -04002257 SamplerLiteralToIDMap[SamplerLiteral.first] = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002258
2259 // Find Insert Point for OpDecorate.
2260 auto DecoInsertPoint =
2261 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2262 [](SPIRVInstruction *Inst) -> bool {
2263 return Inst->getOpcode() != spv::OpDecorate &&
2264 Inst->getOpcode() != spv::OpMemberDecorate &&
2265 Inst->getOpcode() != spv::OpExtInstImport;
2266 });
2267
2268 // Ops[0] = Target ID
2269 // Ops[1] = Decoration (DescriptorSet)
2270 // Ops[2] = LiteralNumber according to Decoration
2271 Ops.clear();
2272
David Neto44795152017-07-13 15:45:28 -04002273 SPIRVOperand *ArgIDOp =
2274 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2275 SamplerLiteralToIDMap[SamplerLiteral.first]);
David Neto22f144c2017-06-12 14:26:21 -04002276 Ops.push_back(ArgIDOp);
2277
2278 spv::Decoration Deco = spv::DecorationDescriptorSet;
2279 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2280 Ops.push_back(DecoOp);
2281
David Neto44795152017-07-13 15:45:28 -04002282 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
2283 << SamplerLiteral.second << "\",descriptorSet,0,binding,"
David Netoc2c368d2017-06-30 16:50:17 -04002284 << BindingIdx << "\n";
2285
David Neto22f144c2017-06-12 14:26:21 -04002286 std::vector<uint32_t> LiteralNum;
2287 LiteralNum.push_back(0);
2288 SPIRVOperand *DescSet =
2289 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2290 Ops.push_back(DescSet);
2291
2292 SPIRVInstruction *DescDecoInst =
2293 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2294 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2295
2296 // Ops[0] = Target ID
2297 // Ops[1] = Decoration (Binding)
2298 // Ops[2] = LiteralNumber according to Decoration
2299 Ops.clear();
2300
2301 Ops.push_back(ArgIDOp);
2302
2303 Deco = spv::DecorationBinding;
2304 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2305 Ops.push_back(DecoOp);
2306
2307 LiteralNum.clear();
2308 LiteralNum.push_back(BindingIdx++);
2309 SPIRVOperand *Binding =
2310 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2311 Ops.push_back(Binding);
2312
2313 SPIRVInstruction *BindDecoInst =
2314 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2315 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2316 }
2317
2318 const char *TranslateSamplerFunctionName = "__translate_sampler_initializer";
2319
2320 auto SamplerFunction = M.getFunction(TranslateSamplerFunctionName);
2321
2322 // If there are no uses of the sampler function, no work to do!
2323 if (!SamplerFunction) {
2324 return;
2325 }
2326
2327 // Iterate through the users of the sampler function.
2328 for (auto User : SamplerFunction->users()) {
2329 if (auto CI = dyn_cast<CallInst>(User)) {
2330 // Get the literal used to initialize the sampler.
2331 auto Constant = dyn_cast<ConstantInt>(CI->getArgOperand(0));
2332
2333 if (!Constant) {
2334 CI->getArgOperand(0)->print(errs());
2335 llvm_unreachable("Argument of sampler initializer was non-constant!");
2336 }
2337
2338 auto SamplerLiteral = static_cast<unsigned>(Constant->getZExtValue());
2339
2340 if (0 == SamplerLiteralToIDMap.count(SamplerLiteral)) {
2341 Constant->print(errs());
2342 llvm_unreachable("Sampler literal was not found in sampler map!");
2343 }
2344
2345 // Calls to the sampler literal function to initialize a sampler are
2346 // re-routed to the global variables declared for the sampler.
2347 VMap[CI] = SamplerLiteralToIDMap[SamplerLiteral];
2348 }
2349 }
2350}
2351
2352void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
2353 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2354 ValueMapType &VMap = getValueMap();
2355 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2356
2357 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2358 Type *Ty = GV.getType();
2359 PointerType *PTy = cast<PointerType>(Ty);
2360
2361 uint32_t InitializerID = 0;
2362
2363 // Workgroup size is handled differently (it goes into a constant)
2364 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2365 std::vector<bool> HasMDVec;
2366 uint32_t PrevXDimCst = 0xFFFFFFFF;
2367 uint32_t PrevYDimCst = 0xFFFFFFFF;
2368 uint32_t PrevZDimCst = 0xFFFFFFFF;
2369 for (Function &Func : *GV.getParent()) {
2370 if (Func.isDeclaration()) {
2371 continue;
2372 }
2373
2374 // We only need to check kernels.
2375 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2376 continue;
2377 }
2378
2379 if (const MDNode *MD =
2380 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2381 uint32_t CurXDimCst = static_cast<uint32_t>(
2382 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2383 uint32_t CurYDimCst = static_cast<uint32_t>(
2384 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2385 uint32_t CurZDimCst = static_cast<uint32_t>(
2386 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2387
2388 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2389 PrevZDimCst == 0xFFFFFFFF) {
2390 PrevXDimCst = CurXDimCst;
2391 PrevYDimCst = CurYDimCst;
2392 PrevZDimCst = CurZDimCst;
2393 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2394 CurZDimCst != PrevZDimCst) {
2395 llvm_unreachable(
2396 "reqd_work_group_size must be the same across all kernels");
2397 } else {
2398 continue;
2399 }
2400
2401 //
2402 // Generate OpConstantComposite.
2403 //
2404 // Ops[0] : Result Type ID
2405 // Ops[1] : Constant size for x dimension.
2406 // Ops[2] : Constant size for y dimension.
2407 // Ops[3] : Constant size for z dimension.
2408 SPIRVOperandList Ops;
2409
2410 uint32_t XDimCstID =
2411 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2412 uint32_t YDimCstID =
2413 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2414 uint32_t ZDimCstID =
2415 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2416
2417 InitializerID = nextID;
2418
2419 Ops.push_back(
2420 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2421 lookupType(Ty->getPointerElementType())));
2422
2423 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2424 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2425 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2426
2427 SPIRVInstruction *Inst =
2428 new SPIRVInstruction(6, spv::OpConstantComposite, nextID++, Ops);
2429 SPIRVInstList.push_back(Inst);
2430
2431 HasMDVec.push_back(true);
2432 } else {
2433 HasMDVec.push_back(false);
2434 }
2435 }
2436
2437 // Check all kernels have same definitions for work_group_size.
2438 bool HasMD = false;
2439 if (!HasMDVec.empty()) {
2440 HasMD = HasMDVec[0];
2441 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2442 if (HasMD != HasMDVec[i]) {
2443 llvm_unreachable(
2444 "Kernels should have consistent work group size definition");
2445 }
2446 }
2447 }
2448
2449 // If all kernels do not have metadata for reqd_work_group_size, generate
2450 // OpSpecConstants for x/y/z dimension.
2451 if (!HasMD) {
2452 //
2453 // Generate OpSpecConstants for x/y/z dimension.
2454 //
2455 // Ops[0] : Result Type ID
2456 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2457 uint32_t XDimCstID = 0;
2458 uint32_t YDimCstID = 0;
2459 uint32_t ZDimCstID = 0;
2460
2461 // X Dimension
2462 SPIRVOperandList Ops;
2463
2464 Ops.push_back(new SPIRVOperand(
2465 SPIRVOperandType::NUMBERID,
2466 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2467
2468 std::vector<uint32_t> LiteralNum;
2469 LiteralNum.push_back(1);
2470 SPIRVOperand *XDim =
2471 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2472 Ops.push_back(XDim);
2473
2474 XDimCstID = nextID;
2475 BuiltinDimVec.push_back(XDimCstID);
2476
2477 SPIRVInstruction *XDimCstInst =
2478 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2479 SPIRVInstList.push_back(XDimCstInst);
2480
2481 // Y Dimension
2482 Ops.clear();
2483
2484 Ops.push_back(new SPIRVOperand(
2485 SPIRVOperandType::NUMBERID,
2486 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2487
2488 LiteralNum.clear();
2489 LiteralNum.push_back(1);
2490 SPIRVOperand *YDim =
2491 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2492 Ops.push_back(YDim);
2493
2494 YDimCstID = nextID;
2495 BuiltinDimVec.push_back(YDimCstID);
2496
2497 SPIRVInstruction *YDimCstInst =
2498 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2499 SPIRVInstList.push_back(YDimCstInst);
2500
2501 // Z Dimension
2502 Ops.clear();
2503
2504 Ops.push_back(new SPIRVOperand(
2505 SPIRVOperandType::NUMBERID,
2506 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2507
2508 LiteralNum.clear();
2509 LiteralNum.push_back(1);
2510 SPIRVOperand *ZDim =
2511 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2512 Ops.push_back(ZDim);
2513
2514 ZDimCstID = nextID;
2515 BuiltinDimVec.push_back(ZDimCstID);
2516
2517 SPIRVInstruction *ZDimCstInst =
2518 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2519 SPIRVInstList.push_back(ZDimCstInst);
2520
2521 //
2522 // Generate OpSpecConstantComposite.
2523 //
2524 // Ops[0] : Result Type ID
2525 // Ops[1] : Constant size for x dimension.
2526 // Ops[2] : Constant size for y dimension.
2527 // Ops[3] : Constant size for z dimension.
2528 InitializerID = nextID;
2529
2530 Ops.clear();
2531
2532 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
2533 lookupType(Ty->getPointerElementType())));
2534
2535 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2536 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2537 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2538
2539 SPIRVInstruction *Inst =
2540 new SPIRVInstruction(6, spv::OpSpecConstantComposite, nextID++, Ops);
2541 SPIRVInstList.push_back(Inst);
2542 }
2543 }
2544
2545 if (GV.hasInitializer()) {
2546 InitializerID = VMap[GV.getInitializer()];
2547 }
2548
2549 VMap[&GV] = nextID;
2550
2551 //
2552 // Generate OpVariable.
2553 //
2554 // GIDOps[0] : Result Type ID
2555 // GIDOps[1] : Storage Class
2556 SPIRVOperandList Ops;
2557
2558 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(Ty)));
2559
2560 spv::StorageClass StorageClass = GetStorageClass(PTy->getAddressSpace());
2561 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2562
2563 if (0 != InitializerID) {
2564 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, InitializerID));
2565 }
2566
2567 SPIRVInstruction *Inst = new SPIRVInstruction(
2568 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID++, Ops);
2569 SPIRVInstList.push_back(Inst);
2570
2571 // If we have a builtin.
2572 if (spv::BuiltInMax != BuiltinType) {
2573 // Find Insert Point for OpDecorate.
2574 auto DecoInsertPoint =
2575 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2576 [](SPIRVInstruction *Inst) -> bool {
2577 return Inst->getOpcode() != spv::OpDecorate &&
2578 Inst->getOpcode() != spv::OpMemberDecorate &&
2579 Inst->getOpcode() != spv::OpExtInstImport;
2580 });
2581 //
2582 // Generate OpDecorate.
2583 //
2584 // DOps[0] = Target ID
2585 // DOps[1] = Decoration (Builtin)
2586 // DOps[2] = BuiltIn ID
2587 uint32_t ResultID;
2588
2589 // WorkgroupSize is different, we decorate the constant composite that has
2590 // its value, rather than the variable that we use to access the value.
2591 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2592 ResultID = InitializerID;
David Netoa60b00b2017-09-15 16:34:09 -04002593 // Save both the value and variable IDs for later.
2594 WorkgroupSizeValueID = InitializerID;
2595 WorkgroupSizeVarID = VMap[&GV];
David Neto22f144c2017-06-12 14:26:21 -04002596 } else {
2597 ResultID = VMap[&GV];
2598 }
2599
2600 SPIRVOperandList DOps;
2601 SPIRVOperand *ResultIDOp =
2602 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResultID);
2603 DOps.push_back(ResultIDOp);
2604
2605 spv::Decoration Deco = spv::DecorationBuiltIn;
2606 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2607 DOps.push_back(DecoOp);
2608
2609 SPIRVOperand *Builtin =
2610 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinType);
2611 DOps.push_back(Builtin);
2612
2613 SPIRVInstruction *DescDecoInst =
2614 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps);
2615 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2616 }
2617}
2618
2619void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
2620 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2621 ValueMapType &VMap = getValueMap();
2622 EntryPointVecType &EntryPoints = getEntryPointVec();
2623 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
2624 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
2625 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2626 auto &GlobalConstArgSet = getGlobalConstArgSet();
2627
2628 FunctionType *FTy = F.getFunctionType();
2629
2630 //
2631 // Generate OpVariable and OpDecorate for kernel function with arguments.
2632 //
2633 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2634
2635 // Find Insert Point for OpDecorate.
2636 auto DecoInsertPoint =
2637 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2638 [](SPIRVInstruction *Inst) -> bool {
2639 return Inst->getOpcode() != spv::OpDecorate &&
2640 Inst->getOpcode() != spv::OpMemberDecorate &&
2641 Inst->getOpcode() != spv::OpExtInstImport;
2642 });
2643
2644 uint32_t DescriptorSetIdx = (0 < getSamplerMap().size()) ? 1u : 0u;
David Netocd8ca5f2017-10-02 23:34:11 -04002645 if (distinct_kernel_descriptor_sets) {
2646 for (Function &Func : *F.getParent()) {
2647 if (Func.isDeclaration()) {
2648 continue;
David Neto22f144c2017-06-12 14:26:21 -04002649 }
David Netocd8ca5f2017-10-02 23:34:11 -04002650
2651 if (Func.getCallingConv() == CallingConv::SPIR_KERNEL) {
2652 if (&Func == &F) {
2653 break;
2654 }
2655 DescriptorSetIdx++;
2656 }
David Neto22f144c2017-06-12 14:26:21 -04002657 }
2658 }
2659
David Neto156783e2017-07-05 15:39:41 -04002660 const auto *ArgMap = F.getMetadata("kernel_arg_map");
2661 // Emit descriptor map entries, if there was explicit metadata
2662 // attached.
2663 if (ArgMap) {
2664 for (const auto &arg : ArgMap->operands()) {
2665 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
David Neto48f56a42017-10-06 16:44:25 -04002666 assert(arg_node->getNumOperands() == 5);
David Neto156783e2017-07-05 15:39:41 -04002667 const auto name =
2668 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2669 const auto old_index =
2670 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2671 const auto new_index =
2672 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2673 const auto offset =
2674 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
David Neto4feb7a42017-10-06 17:29:42 -04002675 const auto argKind =
David Neto48f56a42017-10-06 16:44:25 -04002676 dyn_cast<MDString>(arg_node->getOperand(4))->getString();
David Neto156783e2017-07-05 15:39:41 -04002677 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2678 << ",argOrdinal," << old_index << ",descriptorSet,"
2679 << DescriptorSetIdx << ",binding," << new_index
David Neto4feb7a42017-10-06 17:29:42 -04002680 << ",offset," << offset << ",argKind," << argKind
David Neto48f56a42017-10-06 16:44:25 -04002681 << "\n";
David Neto156783e2017-07-05 15:39:41 -04002682 }
2683 }
2684
David Neto22f144c2017-06-12 14:26:21 -04002685 uint32_t BindingIdx = 0;
2686 for (auto &Arg : F.args()) {
2687 Value *NewGV = ArgGVMap[&Arg];
2688 VMap[&Arg] = VMap[NewGV];
2689 ArgGVIDMap[&Arg] = VMap[&Arg];
2690
David Neto156783e2017-07-05 15:39:41 -04002691 // Emit a descriptor map entry for this arg, in case there was no explicit
2692 // kernel arg mapping metadata.
2693 if (!ArgMap) {
2694 descriptorMapOut << "kernel," << F.getName() << ",arg," << Arg.getName()
2695 << ",argOrdinal," << BindingIdx << ",descriptorSet,"
2696 << DescriptorSetIdx << ",binding," << BindingIdx
David Neto4feb7a42017-10-06 17:29:42 -04002697 << ",offset,0,argKind,"
2698 << clspv::GetArgKindForType(Arg.getType()) << "\n";
David Netoc2c368d2017-06-30 16:50:17 -04002699 }
2700
David Neto26aaf622017-10-23 18:11:53 -04002701 if (GVarWithEmittedBindingInfo.count(NewGV)) {
2702 BindingIdx++;
2703 continue;
2704 }
2705 GVarWithEmittedBindingInfo.insert(NewGV);
2706
David Neto22f144c2017-06-12 14:26:21 -04002707 // Ops[0] = Target ID
2708 // Ops[1] = Decoration (DescriptorSet)
2709 // Ops[2] = LiteralNumber according to Decoration
2710 SPIRVOperandList Ops;
2711
2712 SPIRVOperand *ArgIDOp =
2713 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2714 Ops.push_back(ArgIDOp);
2715
2716 spv::Decoration Deco = spv::DecorationDescriptorSet;
2717 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2718 Ops.push_back(DecoOp);
2719
2720 std::vector<uint32_t> LiteralNum;
2721 LiteralNum.push_back(DescriptorSetIdx);
2722 SPIRVOperand *DescSet =
2723 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2724 Ops.push_back(DescSet);
2725
2726 SPIRVInstruction *DescDecoInst =
2727 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2728 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2729
2730 // Ops[0] = Target ID
2731 // Ops[1] = Decoration (Binding)
2732 // Ops[2] = LiteralNumber according to Decoration
2733 Ops.clear();
2734
2735 Ops.push_back(ArgIDOp);
2736
2737 Deco = spv::DecorationBinding;
2738 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2739 Ops.push_back(DecoOp);
2740
2741 LiteralNum.clear();
2742 LiteralNum.push_back(BindingIdx++);
2743 SPIRVOperand *Binding =
2744 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2745 Ops.push_back(Binding);
2746
2747 SPIRVInstruction *BindDecoInst =
2748 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2749 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2750
2751 // Handle image type argument.
2752 bool HasReadOnlyImageType = false;
2753 bool HasWriteOnlyImageType = false;
2754 if (PointerType *ArgPTy = dyn_cast<PointerType>(Arg.getType())) {
2755 if (StructType *STy = dyn_cast<StructType>(ArgPTy->getElementType())) {
2756 if (STy->isOpaque()) {
2757 if (STy->getName().equals("opencl.image2d_ro_t") ||
2758 STy->getName().equals("opencl.image3d_ro_t")) {
2759 HasReadOnlyImageType = true;
2760 } else if (STy->getName().equals("opencl.image2d_wo_t") ||
2761 STy->getName().equals("opencl.image3d_wo_t")) {
2762 HasWriteOnlyImageType = true;
2763 }
2764 }
2765 }
2766 }
2767
2768 if (HasReadOnlyImageType || HasWriteOnlyImageType) {
2769 // Ops[0] = Target ID
2770 // Ops[1] = Decoration (NonReadable or NonWritable)
2771 Ops.clear();
2772
2773 ArgIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2774 Ops.push_back(ArgIDOp);
2775
2776 Deco = spv::DecorationNonReadable;
2777 if (HasReadOnlyImageType) {
2778 Deco = spv::DecorationNonWritable;
2779 }
2780 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2781 Ops.push_back(DecoOp);
2782
2783 DescDecoInst =
2784 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2785 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2786 }
2787
2788 // Handle const address space.
2789 if (NewGV->getType()->getPointerAddressSpace() ==
2790 AddressSpace::Constant) {
2791 // Ops[0] = Target ID
2792 // Ops[1] = Decoration (NonWriteable)
2793 Ops.clear();
2794
2795 Ops.push_back(ArgIDOp);
2796
2797 Deco = spv::DecorationNonWritable;
2798 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2799 Ops.push_back(DecoOp);
2800
2801 BindDecoInst =
2802 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2803 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2804 }
2805 }
2806 }
2807
2808 //
2809 // Generate OPFunction.
2810 //
2811
2812 // FOps[0] : Result Type ID
2813 // FOps[1] : Function Control
2814 // FOps[2] : Function Type ID
2815 SPIRVOperandList FOps;
2816
2817 // Find SPIRV instruction for return type.
2818 uint32_t RetTyID = lookupType(FTy->getReturnType());
2819 SPIRVOperand *RetTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
2820 FOps.push_back(RetTyOp);
2821
2822 // Check function attributes for SPIRV Function Control.
2823 uint32_t FuncControl = spv::FunctionControlMaskNone;
2824 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2825 FuncControl |= spv::FunctionControlInlineMask;
2826 }
2827 if (F.hasFnAttribute(Attribute::NoInline)) {
2828 FuncControl |= spv::FunctionControlDontInlineMask;
2829 }
2830 // TODO: Check llvm attribute for Function Control Pure.
2831 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2832 FuncControl |= spv::FunctionControlPureMask;
2833 }
2834 // TODO: Check llvm attribute for Function Control Const.
2835 if (F.hasFnAttribute(Attribute::ReadNone)) {
2836 FuncControl |= spv::FunctionControlConstMask;
2837 }
2838
2839 SPIRVOperand *FunctionControlOp =
2840 new SPIRVOperand(SPIRVOperandType::NUMBERID, FuncControl);
2841 FOps.push_back(FunctionControlOp);
2842
2843 uint32_t FTyID;
2844 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2845 SmallVector<Type *, 4> NewFuncParamTys;
2846 FunctionType *NewFTy =
2847 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
2848 FTyID = lookupType(NewFTy);
2849 } else {
2850 // Handle function with global constant parameters.
2851 if (GlobalConstFuncTyMap.count(FTy)) {
2852 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
2853 } else {
2854 FTyID = lookupType(FTy);
2855 }
2856 }
2857
2858 SPIRVOperand *FTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, FTyID);
2859 FOps.push_back(FTyOp);
2860
2861 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2862 EntryPoints.push_back(std::make_pair(&F, nextID));
2863 }
2864
2865 VMap[&F] = nextID;
2866
2867 // Generate SPIRV instruction for function.
2868 SPIRVInstruction *FuncInst =
2869 new SPIRVInstruction(5, spv::OpFunction, nextID++, FOps);
2870 SPIRVInstList.push_back(FuncInst);
2871
2872 //
2873 // Generate OpFunctionParameter for Normal function.
2874 //
2875
2876 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2877 // Iterate Argument for name instead of param type from function type.
2878 unsigned ArgIdx = 0;
2879 for (Argument &Arg : F.args()) {
2880 VMap[&Arg] = nextID;
2881
2882 // ParamOps[0] : Result Type ID
2883 SPIRVOperandList ParamOps;
2884
2885 // Find SPIRV instruction for parameter type.
2886 uint32_t ParamTyID = lookupType(Arg.getType());
2887 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2888 if (GlobalConstFuncTyMap.count(FTy)) {
2889 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2890 Type *EleTy = PTy->getPointerElementType();
2891 Type *ArgTy =
2892 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
2893 ParamTyID = lookupType(ArgTy);
2894 GlobalConstArgSet.insert(&Arg);
2895 }
2896 }
2897 }
2898 SPIRVOperand *ParamTyOp =
2899 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
2900 ParamOps.push_back(ParamTyOp);
2901
2902 // Generate SPIRV instruction for parameter.
2903 SPIRVInstruction *ParamInst =
2904 new SPIRVInstruction(3, spv::OpFunctionParameter, nextID++, ParamOps);
2905 SPIRVInstList.push_back(ParamInst);
2906
2907 ArgIdx++;
2908 }
2909 }
2910}
2911
2912void SPIRVProducerPass::GenerateModuleInfo() {
2913 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2914 EntryPointVecType &EntryPoints = getEntryPointVec();
2915 ValueMapType &VMap = getValueMap();
2916 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
2917 uint32_t &ExtInstImportID = getOpExtInstImportID();
2918 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2919
2920 // Set up insert point.
2921 auto InsertPoint = SPIRVInstList.begin();
2922
2923 //
2924 // Generate OpCapability
2925 //
2926 // TODO: Which llvm information is mapped to SPIRV Capapbility?
2927
2928 // Ops[0] = Capability
2929 SPIRVOperandList Ops;
2930
2931 SPIRVInstruction *CapInst = new SPIRVInstruction(
2932 2, spv::OpCapability, 0 /* No id */,
2933 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::CapabilityShader));
2934 SPIRVInstList.insert(InsertPoint, CapInst);
2935
2936 for (Type *Ty : getTypeList()) {
2937 // Find the i16 type.
2938 if (Ty->isIntegerTy(16)) {
2939 // Generate OpCapability for i16 type.
2940 SPIRVInstList.insert(
2941 InsertPoint,
2942 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2943 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2944 spv::CapabilityInt16)));
2945 } else if (Ty->isIntegerTy(64)) {
2946 // Generate OpCapability for i64 type.
2947 SPIRVInstList.insert(
2948 InsertPoint,
2949 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2950 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2951 spv::CapabilityInt64)));
2952 } else if (Ty->isHalfTy()) {
2953 // Generate OpCapability for half type.
2954 SPIRVInstList.insert(
2955 InsertPoint,
2956 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2957 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2958 spv::CapabilityFloat16)));
2959 } else if (Ty->isDoubleTy()) {
2960 // Generate OpCapability for double type.
2961 SPIRVInstList.insert(
2962 InsertPoint,
2963 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2964 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2965 spv::CapabilityFloat64)));
2966 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
2967 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04002968 if (STy->getName().equals("opencl.image2d_wo_t") ||
2969 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002970 // Generate OpCapability for write only image type.
2971 SPIRVInstList.insert(
2972 InsertPoint,
2973 new SPIRVInstruction(
2974 2, spv::OpCapability, 0 /* No id */,
2975 new SPIRVOperand(
2976 SPIRVOperandType::NUMBERID,
2977 spv::CapabilityStorageImageWriteWithoutFormat)));
2978 }
2979 }
2980 }
2981 }
2982
2983 if (hasVariablePointers()) {
2984 //
2985 // Generate OpCapability and OpExtension
2986 //
2987
2988 //
2989 // Generate OpCapability.
2990 //
2991 // Ops[0] = Capability
2992 //
2993 Ops.clear();
2994
2995 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
2996 spv::CapabilityVariablePointers));
2997
2998 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(2, spv::OpCapability,
2999 0 /* No id */, Ops));
3000
3001 //
3002 // Generate OpExtension.
3003 //
3004 // Ops[0] = Name (Literal String)
3005 //
David Netoa772fd12017-08-04 14:17:33 -04003006 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
3007 "SPV_KHR_variable_pointers"}) {
3008 Ops.clear();
David Neto22f144c2017-06-12 14:26:21 -04003009
David Netoa772fd12017-08-04 14:17:33 -04003010 SPIRVOperand *Name =
3011 new SPIRVOperand(SPIRVOperandType::LITERAL_STRING, extension);
3012 Ops.push_back(Name);
David Neto22f144c2017-06-12 14:26:21 -04003013
David Netoa772fd12017-08-04 14:17:33 -04003014 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
3015 if ((Name->getLiteralStr().size() + 1) % 4) {
3016 NameWordSize += 1;
3017 }
3018
3019 assert((NameWordSize + 1) < UINT16_MAX);
3020 uint16_t WordCount = static_cast<uint16_t>(1 + NameWordSize);
3021
3022 SPIRVInstruction *ExtensionInst =
3023 new SPIRVInstruction(WordCount, spv::OpExtension, 0 /* No id */, Ops);
3024 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04003025 }
David Neto22f144c2017-06-12 14:26:21 -04003026 }
3027
3028 if (ExtInstImportID) {
3029 ++InsertPoint;
3030 }
3031
3032 //
3033 // Generate OpMemoryModel
3034 //
3035 // Memory model for Vulkan will always be GLSL450.
3036
3037 // Ops[0] = Addressing Model
3038 // Ops[1] = Memory Model
3039 Ops.clear();
3040 SPIRVOperand *AddrModel =
3041 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::AddressingModelLogical);
3042 Ops.push_back(AddrModel);
3043
3044 SPIRVOperand *MemModel =
3045 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::MemoryModelGLSL450);
3046 Ops.push_back(MemModel);
3047
3048 SPIRVInstruction *MemModelInst =
3049 new SPIRVInstruction(3, spv::OpMemoryModel, 0 /* No id */, Ops);
3050 SPIRVInstList.insert(InsertPoint, MemModelInst);
3051
3052 //
3053 // Generate OpEntryPoint
3054 //
3055 for (auto EntryPoint : EntryPoints) {
3056 // Ops[0] = Execution Model
3057 // Ops[1] = EntryPoint ID
3058 // Ops[2] = Name (Literal String)
3059 // ...
3060 //
3061 // TODO: Do we need to consider Interface ID for forward references???
3062 Ops.clear();
3063 SPIRVOperand *ExecModel = new SPIRVOperand(SPIRVOperandType::NUMBERID,
3064 spv::ExecutionModelGLCompute);
3065 Ops.push_back(ExecModel);
3066
3067 SPIRVOperand *EntryPointID =
3068 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
3069 Ops.push_back(EntryPointID);
3070
3071 SPIRVOperand *Name = new SPIRVOperand(SPIRVOperandType::LITERAL_STRING,
3072 EntryPoint.first->getName());
3073 Ops.push_back(Name);
3074
3075 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
3076 if ((Name->getLiteralStr().size() + 1) % 4) {
3077 NameWordSize += 1;
3078 }
3079
3080 assert((3 + NameWordSize) < UINT16_MAX);
3081 uint16_t WordCount = static_cast<uint16_t>(3 + NameWordSize);
3082
3083 for (Value *Interface : EntryPointInterfaces) {
3084 SPIRVOperand *GIDOp =
3085 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[Interface]);
3086 Ops.push_back(GIDOp);
3087 WordCount++;
3088 }
3089
3090 SPIRVInstruction *EntryPointInst =
3091 new SPIRVInstruction(WordCount, spv::OpEntryPoint, 0 /* No id */, Ops);
3092 SPIRVInstList.insert(InsertPoint, EntryPointInst);
3093 }
3094
3095 for (auto EntryPoint : EntryPoints) {
3096 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
3097 ->getMetadata("reqd_work_group_size")) {
3098
3099 if (!BuiltinDimVec.empty()) {
3100 llvm_unreachable(
3101 "Kernels should have consistent work group size definition");
3102 }
3103
3104 //
3105 // Generate OpExecutionMode
3106 //
3107
3108 // Ops[0] = Entry Point ID
3109 // Ops[1] = Execution Mode
3110 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
3111 Ops.clear();
3112 SPIRVOperand *EntryPointID =
3113 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
3114 Ops.push_back(EntryPointID);
3115
3116 SPIRVOperand *ExecMode = new SPIRVOperand(SPIRVOperandType::NUMBERID,
3117 spv::ExecutionModeLocalSize);
3118 Ops.push_back(ExecMode);
3119
3120 uint32_t XDim = static_cast<uint32_t>(
3121 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
3122 uint32_t YDim = static_cast<uint32_t>(
3123 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
3124 uint32_t ZDim = static_cast<uint32_t>(
3125 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
3126
3127 std::vector<uint32_t> LiteralNum;
3128 LiteralNum.push_back(XDim);
3129 SPIRVOperand *XDimOp =
3130 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3131 Ops.push_back(XDimOp);
3132
3133 LiteralNum.clear();
3134 LiteralNum.push_back(YDim);
3135 SPIRVOperand *YDimOp =
3136 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3137 Ops.push_back(YDimOp);
3138
3139 LiteralNum.clear();
3140 LiteralNum.push_back(ZDim);
3141 SPIRVOperand *ZDimOp =
3142 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3143 Ops.push_back(ZDimOp);
3144
3145 SPIRVInstruction *ExecModeInst =
3146 new SPIRVInstruction(static_cast<uint16_t>(1 + Ops.size()),
3147 spv::OpExecutionMode, 0 /* No id */, Ops);
3148 SPIRVInstList.insert(InsertPoint, ExecModeInst);
3149 }
3150 }
3151
3152 //
3153 // Generate OpSource.
3154 //
3155 // Ops[0] = SourceLanguage ID
3156 // Ops[1] = Version (LiteralNum)
3157 //
3158 Ops.clear();
3159 SPIRVOperand *SourceLanguage =
3160 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::SourceLanguageOpenCL_C);
3161 Ops.push_back(SourceLanguage);
3162
3163 std::vector<uint32_t> LiteralNum;
3164 LiteralNum.push_back(120);
3165 SPIRVOperand *Version =
3166 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3167 Ops.push_back(Version);
3168
3169 SPIRVInstruction *OpenSourceInst =
3170 new SPIRVInstruction(3, spv::OpSource, 0 /* No id */, Ops);
3171 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
3172
3173 if (!BuiltinDimVec.empty()) {
3174 //
3175 // Generate OpDecorates for x/y/z dimension.
3176 //
3177 // Ops[0] = Target ID
3178 // Ops[1] = Decoration (SpecId)
3179 // Ops[2] = Specialization Cosntant ID (Literal Number)
3180
3181 // X Dimension
3182 Ops.clear();
3183
3184 SPIRVOperand *TargetID =
3185 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[0]);
3186 Ops.push_back(TargetID);
3187
3188 SPIRVOperand *DecoOp =
3189 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3190 Ops.push_back(DecoOp);
3191
3192 LiteralNum.clear();
3193 LiteralNum.push_back(0);
3194 SPIRVOperand *XDim =
3195 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3196 Ops.push_back(XDim);
3197
3198 SPIRVInstruction *XDimDecoInst =
3199 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3200 SPIRVInstList.insert(InsertPoint, XDimDecoInst);
3201
3202 // Y Dimension
3203 Ops.clear();
3204
3205 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[1]);
3206 Ops.push_back(TargetID);
3207
3208 DecoOp =
3209 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3210 Ops.push_back(DecoOp);
3211
3212 LiteralNum.clear();
3213 LiteralNum.push_back(1);
3214 SPIRVOperand *YDim =
3215 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3216 Ops.push_back(YDim);
3217
3218 SPIRVInstruction *YDimDecoInst =
3219 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3220 SPIRVInstList.insert(InsertPoint, YDimDecoInst);
3221
3222 // Z Dimension
3223 Ops.clear();
3224
3225 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[2]);
3226 Ops.push_back(TargetID);
3227
3228 DecoOp =
3229 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3230 Ops.push_back(DecoOp);
3231
3232 LiteralNum.clear();
3233 LiteralNum.push_back(2);
3234 SPIRVOperand *ZDim =
3235 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3236 Ops.push_back(ZDim);
3237
3238 SPIRVInstruction *ZDimDecoInst =
3239 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3240 SPIRVInstList.insert(InsertPoint, ZDimDecoInst);
3241 }
3242}
3243
3244void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3245 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3246 ValueMapType &VMap = getValueMap();
3247 Module *Module = F.getParent();
3248 LLVMContext &Context = Module->getContext();
3249 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3250
3251 for (Argument &Arg : F.args()) {
3252 if (Arg.use_empty()) {
3253 continue;
3254 }
3255
3256 // Check the type of users of arguments.
3257 bool HasOnlyGEPUse = true;
3258 for (auto *U : Arg.users()) {
3259 if (!isa<GetElementPtrInst>(U) && isa<Instruction>(U)) {
3260 HasOnlyGEPUse = false;
3261 break;
3262 }
3263 }
3264
3265 Type *ArgTy = Arg.getType();
3266
3267 if (PointerType *PTy = dyn_cast<PointerType>(ArgTy)) {
3268 if (StructType *STy = dyn_cast<StructType>(PTy->getElementType())) {
3269 if (STy->isOpaque()) {
3270 // Generate OpLoad for sampler and image types.
3271 if (STy->getName().equals("opencl.sampler_t") ||
3272 STy->getName().equals("opencl.image2d_ro_t") ||
3273 STy->getName().equals("opencl.image2d_wo_t") ||
3274 STy->getName().equals("opencl.image3d_ro_t") ||
3275 STy->getName().equals("opencl.image3d_wo_t")) {
3276 //
3277 // Generate OpLoad.
3278 //
3279 // Ops[0] = Result Type ID
3280 // Ops[1] = Pointer ID
3281 // Ops[2] ... Ops[n] = Optional Memory Access
3282 //
3283 // TODO: Do we need to implement Optional Memory Access???
3284 SPIRVOperandList Ops;
3285
3286 // Use type with address space modified.
3287 ArgTy = ArgGVMap[&Arg]->getType()->getPointerElementType();
3288
3289 uint32_t ResTyID = lookupType(ArgTy);
3290 SPIRVOperand *ResTyIDOp =
3291 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3292 Ops.push_back(ResTyIDOp);
3293
3294 uint32_t PointerID = VMap[&Arg];
3295 SPIRVOperand *PointerIDOp =
3296 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3297 Ops.push_back(PointerIDOp);
3298
3299 VMap[&Arg] = nextID;
3300 SPIRVInstruction *Inst =
3301 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3302 SPIRVInstList.push_back(Inst);
3303 continue;
3304 }
3305 }
3306 }
3307
3308 if (!HasOnlyGEPUse) {
3309 //
3310 // Generate OpAccessChain.
3311 //
3312 // Ops[0] = Result Type ID
3313 // Ops[1] = Base ID
3314 // Ops[2] ... Ops[n] = Indexes ID
3315 SPIRVOperandList Ops;
3316
3317 uint32_t ResTyID = lookupType(ArgTy);
3318 if (!isa<PointerType>(ArgTy)) {
3319 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3320 }
3321 SPIRVOperand *ResTyOp =
3322 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3323 Ops.push_back(ResTyOp);
3324
3325 uint32_t BaseID = VMap[&Arg];
3326 SPIRVOperand *BaseOp =
3327 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3328 Ops.push_back(BaseOp);
3329
3330 Type *IdxTy = Type::getInt32Ty(Context);
3331 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3332 SPIRVOperand *IndexIDOp =
3333 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3334 Ops.push_back(IndexIDOp);
3335 Ops.push_back(IndexIDOp);
3336
3337 // Generate SPIRV instruction for argument.
3338 VMap[&Arg] = nextID;
3339 SPIRVInstruction *ArgInst =
3340 new SPIRVInstruction(6, spv::OpAccessChain, nextID++, Ops);
3341 SPIRVInstList.push_back(ArgInst);
3342 } else {
3343 // For GEP uses, generate OpAccessChain with folding GEP ahead of GEP.
3344 // Nothing to do here.
3345 }
3346 } else {
3347 //
3348 // Generate OpAccessChain and OpLoad for non-pointer type argument.
3349 //
3350
3351 //
3352 // Generate OpAccessChain.
3353 //
3354 // Ops[0] = Result Type ID
3355 // Ops[1] = Base ID
3356 // Ops[2] ... Ops[n] = Indexes ID
3357 SPIRVOperandList Ops;
3358
3359 uint32_t ResTyID = lookupType(ArgTy);
3360 if (!isa<PointerType>(ArgTy)) {
3361 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3362 }
3363 SPIRVOperand *ResTyIDOp =
3364 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3365 Ops.push_back(ResTyIDOp);
3366
3367 uint32_t BaseID = VMap[&Arg];
3368 SPIRVOperand *BaseOp =
3369 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3370 Ops.push_back(BaseOp);
3371
3372 Type *IdxTy = Type::getInt32Ty(Context);
3373 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3374 SPIRVOperand *IndexIDOp =
3375 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3376 Ops.push_back(IndexIDOp);
3377
3378 // Generate SPIRV instruction for argument.
3379 uint32_t PointerID = nextID;
3380 VMap[&Arg] = nextID;
3381 SPIRVInstruction *ArgInst =
3382 new SPIRVInstruction(5, spv::OpAccessChain, nextID++, Ops);
3383 SPIRVInstList.push_back(ArgInst);
3384
3385 //
3386 // Generate OpLoad.
3387 //
3388
3389 // Ops[0] = Result Type ID
3390 // Ops[1] = Pointer ID
3391 // Ops[2] ... Ops[n] = Optional Memory Access
3392 //
3393 // TODO: Do we need to implement Optional Memory Access???
3394 Ops.clear();
3395
3396 ResTyID = lookupType(ArgTy);
3397 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3398 Ops.push_back(ResTyIDOp);
3399
3400 SPIRVOperand *PointerIDOp =
3401 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3402 Ops.push_back(PointerIDOp);
3403
3404 VMap[&Arg] = nextID;
3405 SPIRVInstruction *Inst =
3406 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3407 SPIRVInstList.push_back(Inst);
3408 }
3409 }
3410}
3411
3412void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3413 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3414 ValueMapType &VMap = getValueMap();
3415
3416 bool IsKernel = false;
3417 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3418 IsKernel = true;
3419 }
3420
3421 for (BasicBlock &BB : F) {
3422 // Register BasicBlock to ValueMap.
3423 VMap[&BB] = nextID;
3424
3425 //
3426 // Generate OpLabel for Basic Block.
3427 //
3428 SPIRVOperandList Ops;
3429 SPIRVInstruction *Inst =
3430 new SPIRVInstruction(2, spv::OpLabel, nextID++, Ops);
3431 SPIRVInstList.push_back(Inst);
3432
David Neto6dcd4712017-06-23 11:06:47 -04003433 // OpVariable instructions must come first.
3434 for (Instruction &I : BB) {
3435 if (isa<AllocaInst>(I)) {
3436 GenerateInstruction(I);
3437 }
3438 }
3439
David Neto22f144c2017-06-12 14:26:21 -04003440 if (&BB == &F.getEntryBlock() && IsKernel) {
3441 GenerateInstForArg(F);
3442 }
3443
3444 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003445 if (!isa<AllocaInst>(I)) {
3446 GenerateInstruction(I);
3447 }
David Neto22f144c2017-06-12 14:26:21 -04003448 }
3449 }
3450}
3451
3452spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3453 const std::map<CmpInst::Predicate, spv::Op> Map = {
3454 {CmpInst::ICMP_EQ, spv::OpIEqual},
3455 {CmpInst::ICMP_NE, spv::OpINotEqual},
3456 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3457 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3458 {CmpInst::ICMP_ULT, spv::OpULessThan},
3459 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3460 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3461 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3462 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3463 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3464 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3465 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3466 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3467 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3468 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3469 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3470 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3471 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3472 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3473 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3474 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3475 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3476
3477 assert(0 != Map.count(I->getPredicate()));
3478
3479 return Map.at(I->getPredicate());
3480}
3481
3482spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3483 const std::map<unsigned, spv::Op> Map{
3484 {Instruction::Trunc, spv::OpUConvert},
3485 {Instruction::ZExt, spv::OpUConvert},
3486 {Instruction::SExt, spv::OpSConvert},
3487 {Instruction::FPToUI, spv::OpConvertFToU},
3488 {Instruction::FPToSI, spv::OpConvertFToS},
3489 {Instruction::UIToFP, spv::OpConvertUToF},
3490 {Instruction::SIToFP, spv::OpConvertSToF},
3491 {Instruction::FPTrunc, spv::OpFConvert},
3492 {Instruction::FPExt, spv::OpFConvert},
3493 {Instruction::BitCast, spv::OpBitcast}};
3494
3495 assert(0 != Map.count(I.getOpcode()));
3496
3497 return Map.at(I.getOpcode());
3498}
3499
3500spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3501 if (I.getType()->isIntegerTy(1)) {
3502 switch (I.getOpcode()) {
3503 default:
3504 break;
3505 case Instruction::Or:
3506 return spv::OpLogicalOr;
3507 case Instruction::And:
3508 return spv::OpLogicalAnd;
3509 case Instruction::Xor:
3510 return spv::OpLogicalNotEqual;
3511 }
3512 }
3513
3514 const std::map<unsigned, spv::Op> Map {
3515 {Instruction::Add, spv::OpIAdd},
3516 {Instruction::FAdd, spv::OpFAdd},
3517 {Instruction::Sub, spv::OpISub},
3518 {Instruction::FSub, spv::OpFSub},
3519 {Instruction::Mul, spv::OpIMul},
3520 {Instruction::FMul, spv::OpFMul},
3521 {Instruction::UDiv, spv::OpUDiv},
3522 {Instruction::SDiv, spv::OpSDiv},
3523 {Instruction::FDiv, spv::OpFDiv},
3524 {Instruction::URem, spv::OpUMod},
3525 {Instruction::SRem, spv::OpSRem},
3526 {Instruction::FRem, spv::OpFRem},
3527 {Instruction::Or, spv::OpBitwiseOr},
3528 {Instruction::Xor, spv::OpBitwiseXor},
3529 {Instruction::And, spv::OpBitwiseAnd},
3530 {Instruction::Shl, spv::OpShiftLeftLogical},
3531 {Instruction::LShr, spv::OpShiftRightLogical},
3532 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3533
3534 assert(0 != Map.count(I.getOpcode()));
3535
3536 return Map.at(I.getOpcode());
3537}
3538
3539void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3540 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3541 ValueMapType &VMap = getValueMap();
3542 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3543 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
3544 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3545 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3546
3547 // Register Instruction to ValueMap.
3548 if (0 == VMap[&I]) {
3549 VMap[&I] = nextID;
3550 }
3551
3552 switch (I.getOpcode()) {
3553 default: {
3554 if (Instruction::isCast(I.getOpcode())) {
3555 //
3556 // Generate SPIRV instructions for cast operators.
3557 //
3558
David Netod2de94a2017-08-28 17:27:47 -04003559
3560 auto Ty = I.getType();
David Neto22f144c2017-06-12 14:26:21 -04003561 auto OpTy = I.getOperand(0)->getType();
David Netod2de94a2017-08-28 17:27:47 -04003562 auto toI8 = Ty == Type::getInt8Ty(Context);
3563 auto fromI32 = OpTy == Type::getInt32Ty(Context);
David Neto22f144c2017-06-12 14:26:21 -04003564 // Handle zext, sext and uitofp with i1 type specially.
3565 if ((I.getOpcode() == Instruction::ZExt ||
3566 I.getOpcode() == Instruction::SExt ||
3567 I.getOpcode() == Instruction::UIToFP) &&
3568 (OpTy->isIntegerTy(1) ||
3569 (OpTy->isVectorTy() &&
3570 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3571 //
3572 // Generate OpSelect.
3573 //
3574
3575 // Ops[0] = Result Type ID
3576 // Ops[1] = Condition ID
3577 // Ops[2] = True Constant ID
3578 // Ops[3] = False Constant ID
3579 SPIRVOperandList Ops;
3580
3581 uint32_t ResTyID = lookupType(I.getType());
3582 SPIRVOperand *ResTyIDOp =
3583 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3584 Ops.push_back(ResTyIDOp);
3585
3586 // TODO: zext's first operand should be compare instructions???
3587 uint32_t CondID = VMap[I.getOperand(0)];
3588 SPIRVOperand *CondIDOp =
3589 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3590 Ops.push_back(CondIDOp);
3591
3592 uint32_t TrueID = 0;
3593 if (I.getOpcode() == Instruction::ZExt) {
3594 APInt One(32, 1);
3595 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3596 } else if (I.getOpcode() == Instruction::SExt) {
3597 APInt MinusOne(32, UINT64_MAX, true);
3598 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3599 } else {
3600 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3601 }
3602 SPIRVOperand *TrueIDOp =
3603 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3604 Ops.push_back(TrueIDOp);
3605
3606 uint32_t FalseID = 0;
3607 if (I.getOpcode() == Instruction::ZExt) {
3608 FalseID = VMap[Constant::getNullValue(I.getType())];
3609 } else if (I.getOpcode() == Instruction::SExt) {
3610 FalseID = VMap[Constant::getNullValue(I.getType())];
3611 } else {
3612 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3613 }
3614 SPIRVOperand *FalseIDOp =
3615 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3616 Ops.push_back(FalseIDOp);
3617
3618 SPIRVInstruction *Inst =
3619 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3620 SPIRVInstList.push_back(Inst);
David Netod2de94a2017-08-28 17:27:47 -04003621 } else if (I.getOpcode() == Instruction::Trunc && fromI32 && toI8) {
3622 // The SPIR-V target type is a 32-bit int. Keep only the bottom
3623 // 8 bits.
3624 // Before:
3625 // %result = trunc i32 %a to i8
3626 // After
3627 // %result = OpBitwiseAnd %uint %a %uint_255
3628
3629 SPIRVOperandList Ops;
3630
3631 uint32_t ResTyID = lookupType(OpTy);
3632 SPIRVOperand *ResTyIDOp =
3633 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3634 Ops.push_back(ResTyIDOp);
3635
3636 uint32_t Op0ID = VMap[I.getOperand(0)];
3637 SPIRVOperand *Op0IDOp =
3638 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3639 Ops.push_back(Op0IDOp);
3640
3641 Type *UintTy = Type::getInt32Ty(Context);
3642 uint32_t MaskID = VMap[ConstantInt::get(UintTy, 255)];
3643 SPIRVOperand *MaskOp =
3644 new SPIRVOperand(SPIRVOperandType::NUMBERID, MaskID);
3645 Ops.push_back(MaskOp);
3646
3647 SPIRVInstruction *Inst =
3648 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3649 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04003650 } else {
3651 // Ops[0] = Result Type ID
3652 // Ops[1] = Source Value ID
3653 SPIRVOperandList Ops;
3654
3655 uint32_t ResTyID = lookupType(I.getType());
3656 SPIRVOperand *ResTyIDOp =
3657 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3658 Ops.push_back(ResTyIDOp);
3659
3660 uint32_t SrcID = VMap[I.getOperand(0)];
3661 SPIRVOperand *SrcIDOp =
3662 new SPIRVOperand(SPIRVOperandType::NUMBERID, SrcID);
3663 Ops.push_back(SrcIDOp);
3664
3665 SPIRVInstruction *Inst =
3666 new SPIRVInstruction(4, GetSPIRVCastOpcode(I), nextID++, Ops);
3667 SPIRVInstList.push_back(Inst);
3668 }
3669 } else if (isa<BinaryOperator>(I)) {
3670 //
3671 // Generate SPIRV instructions for binary operators.
3672 //
3673
3674 // Handle xor with i1 type specially.
3675 if (I.getOpcode() == Instruction::Xor &&
3676 I.getType() == Type::getInt1Ty(Context) &&
3677 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3678 //
3679 // Generate OpLogicalNot.
3680 //
3681 // Ops[0] = Result Type ID
3682 // Ops[1] = Operand
3683 SPIRVOperandList Ops;
3684
3685 uint32_t ResTyID = lookupType(I.getType());
3686 SPIRVOperand *ResTyIDOp =
3687 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3688 Ops.push_back(ResTyIDOp);
3689
3690 Value *CondV = I.getOperand(0);
3691 if (isa<Constant>(I.getOperand(0))) {
3692 CondV = I.getOperand(1);
3693 }
3694 uint32_t CondID = VMap[CondV];
3695 SPIRVOperand *CondIDOp =
3696 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3697 Ops.push_back(CondIDOp);
3698
3699 SPIRVInstruction *Inst =
3700 new SPIRVInstruction(4, spv::OpLogicalNot, nextID++, Ops);
3701 SPIRVInstList.push_back(Inst);
3702 } else {
3703 // Ops[0] = Result Type ID
3704 // Ops[1] = Operand 0
3705 // Ops[2] = Operand 1
3706 SPIRVOperandList Ops;
3707
3708 uint32_t ResTyID = lookupType(I.getType());
3709 SPIRVOperand *ResTyIDOp =
3710 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3711 Ops.push_back(ResTyIDOp);
3712
3713 uint32_t Op0ID = VMap[I.getOperand(0)];
3714 SPIRVOperand *Op0IDOp =
3715 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3716 Ops.push_back(Op0IDOp);
3717
3718 uint32_t Op1ID = VMap[I.getOperand(1)];
3719 SPIRVOperand *Op1IDOp =
3720 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3721 Ops.push_back(Op1IDOp);
3722
3723 SPIRVInstruction *Inst =
3724 new SPIRVInstruction(5, GetSPIRVBinaryOpcode(I), nextID++, Ops);
3725 SPIRVInstList.push_back(Inst);
3726 }
3727 } else {
3728 I.print(errs());
3729 llvm_unreachable("Unsupported instruction???");
3730 }
3731 break;
3732 }
3733 case Instruction::GetElementPtr: {
3734 auto &GlobalConstArgSet = getGlobalConstArgSet();
3735
3736 //
3737 // Generate OpAccessChain.
3738 //
3739 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3740
3741 //
3742 // Generate OpAccessChain.
3743 //
3744
3745 // Ops[0] = Result Type ID
3746 // Ops[1] = Base ID
3747 // Ops[2] ... Ops[n] = Indexes ID
3748 SPIRVOperandList Ops;
3749
David Neto1a1a0582017-07-07 12:01:44 -04003750 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003751 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3752 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3753 // Use pointer type with private address space for global constant.
3754 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003755 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003756 }
David Neto1a1a0582017-07-07 12:01:44 -04003757 const uint32_t ResTyID = lookupType(ResultType);
David Neto22f144c2017-06-12 14:26:21 -04003758 SPIRVOperand *ResTyIDOp =
3759 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3760 Ops.push_back(ResTyIDOp);
3761
3762 // Check whether GEP's pointer operand is pointer argument.
3763 bool HasArgBasePointer = false;
3764 for (auto ArgGV : ArgGVMap) {
3765 if (ArgGV.first == GEP->getPointerOperand()) {
3766 if (isa<PointerType>(ArgGV.first->getType())) {
3767 HasArgBasePointer = true;
3768 } else {
3769 llvm_unreachable(
3770 "GEP's pointer operand is argument of non-poninter type???");
3771 }
3772 }
3773 }
3774
3775 uint32_t BaseID;
3776 if (HasArgBasePointer) {
3777 // Point to global variable for argument directly.
3778 BaseID = ArgGVIDMap[GEP->getPointerOperand()];
3779 } else {
3780 BaseID = VMap[GEP->getPointerOperand()];
3781 }
3782
3783 SPIRVOperand *BaseIDOp =
3784 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3785 Ops.push_back(BaseIDOp);
3786
3787 uint16_t WordCount = 4;
3788
3789 if (HasArgBasePointer) {
3790 // If GEP's pointer operand is argument, add one more index for struct
3791 // type to wrap up argument type.
3792 Type *IdxTy = Type::getInt32Ty(Context);
3793 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3794 SPIRVOperand *IndexIDOp =
3795 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3796 Ops.push_back(IndexIDOp);
3797
3798 WordCount++;
3799 }
3800
3801 //
3802 // Follows below rules for gep.
3803 //
3804 // 1. If gep's first index is 0 and gep's base is not kernel function's
3805 // argument, generate OpAccessChain and ignore gep's first index.
3806 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3807 // first index.
3808 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3809 // use gep's first index.
3810 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3811 // gep's first index.
3812 //
3813 spv::Op Opcode = spv::OpAccessChain;
3814 unsigned offset = 0;
3815 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
3816 if (CstInt->getZExtValue() == 0 && !HasArgBasePointer) {
3817 offset = 1;
3818 } else if (CstInt->getZExtValue() != 0 && !HasArgBasePointer) {
3819 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003820 }
3821 } else if (!HasArgBasePointer) {
3822 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003823 }
3824
3825 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003826 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003827 // Do we need to generate ArrayStride? Check against the GEP result type
3828 // rather than the pointer type of the base because when indexing into
3829 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3830 // for something else in the SPIR-V.
3831 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3832 if (GetStorageClass(ResultType->getAddressSpace()) ==
3833 spv::StorageClassStorageBuffer) {
3834 // Save the need to generate an ArrayStride decoration. But defer
3835 // generation until later, so we only make one decoration.
3836 getPointerTypesNeedingArrayStride().insert(ResultType);
3837 }
David Neto22f144c2017-06-12 14:26:21 -04003838 }
3839
3840 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
3841 uint32_t IndexID = VMap[*II];
3842 SPIRVOperand *IndexIDOp =
3843 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3844 Ops.push_back(IndexIDOp);
3845
3846 WordCount++;
3847 }
3848
3849 SPIRVInstruction *Inst =
3850 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3851 SPIRVInstList.push_back(Inst);
3852 break;
3853 }
3854 case Instruction::ExtractValue: {
3855 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3856 // Ops[0] = Result Type ID
3857 // Ops[1] = Composite ID
3858 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3859 SPIRVOperandList Ops;
3860
3861 uint32_t ResTyID = lookupType(I.getType());
3862 SPIRVOperand *ResTyIDOp =
3863 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3864 Ops.push_back(ResTyIDOp);
3865
3866 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
3867 SPIRVOperand *CompositeIDOp =
3868 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
3869 Ops.push_back(CompositeIDOp);
3870
3871 for (auto &Index : EVI->indices()) {
3872 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3873 }
3874
3875 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3876 SPIRVInstruction *Inst =
3877 new SPIRVInstruction(WordCount, spv::OpCompositeExtract, nextID++, Ops);
3878 SPIRVInstList.push_back(Inst);
3879 break;
3880 }
3881 case Instruction::InsertValue: {
3882 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3883 // Ops[0] = Result Type ID
3884 // Ops[1] = Object ID
3885 // Ops[2] = Composite ID
3886 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3887 SPIRVOperandList Ops;
3888
3889 uint32_t ResTyID = lookupType(I.getType());
3890 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID));
3891
3892 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
3893 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID));
3894
3895 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
3896 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID));
3897
3898 for (auto &Index : IVI->indices()) {
3899 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3900 }
3901
3902 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3903 SPIRVInstruction *Inst =
3904 new SPIRVInstruction(WordCount, spv::OpCompositeInsert, nextID++, Ops);
3905 SPIRVInstList.push_back(Inst);
3906 break;
3907 }
3908 case Instruction::Select: {
3909 //
3910 // Generate OpSelect.
3911 //
3912
3913 // Ops[0] = Result Type ID
3914 // Ops[1] = Condition ID
3915 // Ops[2] = True Constant ID
3916 // Ops[3] = False Constant ID
3917 SPIRVOperandList Ops;
3918
3919 // Find SPIRV instruction for parameter type.
3920 auto Ty = I.getType();
3921 if (Ty->isPointerTy()) {
3922 auto PointeeTy = Ty->getPointerElementType();
3923 if (PointeeTy->isStructTy() &&
3924 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3925 Ty = PointeeTy;
3926 }
3927 }
3928
3929 uint32_t ResTyID = lookupType(Ty);
3930 SPIRVOperand *ResTyIDOp =
3931 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3932 Ops.push_back(ResTyIDOp);
3933
3934 uint32_t CondID = VMap[I.getOperand(0)];
3935 SPIRVOperand *CondIDOp =
3936 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3937 Ops.push_back(CondIDOp);
3938
3939 uint32_t TrueID = VMap[I.getOperand(1)];
3940 SPIRVOperand *TrueIDOp =
3941 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3942 Ops.push_back(TrueIDOp);
3943
3944 uint32_t FalseID = VMap[I.getOperand(2)];
3945 SPIRVOperand *FalseIDOp =
3946 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3947 Ops.push_back(FalseIDOp);
3948
3949 SPIRVInstruction *Inst =
3950 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3951 SPIRVInstList.push_back(Inst);
3952 break;
3953 }
3954 case Instruction::ExtractElement: {
3955 // Handle <4 x i8> type manually.
3956 Type *CompositeTy = I.getOperand(0)->getType();
3957 if (is4xi8vec(CompositeTy)) {
3958 //
3959 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3960 // <4 x i8>.
3961 //
3962
3963 //
3964 // Generate OpShiftRightLogical
3965 //
3966 // Ops[0] = Result Type ID
3967 // Ops[1] = Operand 0
3968 // Ops[2] = Operand 1
3969 //
3970 SPIRVOperandList Ops;
3971
3972 uint32_t ResTyID = lookupType(CompositeTy);
3973 SPIRVOperand *ResTyIDOp =
3974 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3975 Ops.push_back(ResTyIDOp);
3976
3977 uint32_t Op0ID = VMap[I.getOperand(0)];
3978 SPIRVOperand *Op0IDOp =
3979 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3980 Ops.push_back(Op0IDOp);
3981
3982 uint32_t Op1ID = 0;
3983 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3984 // Handle constant index.
3985 uint64_t Idx = CI->getZExtValue();
3986 Value *ShiftAmount =
3987 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3988 Op1ID = VMap[ShiftAmount];
3989 } else {
3990 // Handle variable index.
3991 SPIRVOperandList TmpOps;
3992
3993 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
3994 SPIRVOperand *TmpResTyIDOp =
3995 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
3996 TmpOps.push_back(TmpResTyIDOp);
3997
3998 uint32_t IdxID = VMap[I.getOperand(1)];
3999 SPIRVOperand *TmpOp0IDOp =
4000 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
4001 TmpOps.push_back(TmpOp0IDOp);
4002
4003 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
4004 uint32_t Cst8ID = VMap[Cst8];
4005 SPIRVOperand *TmpOp1IDOp =
4006 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
4007 TmpOps.push_back(TmpOp1IDOp);
4008
4009 Op1ID = nextID;
4010
4011 SPIRVInstruction *TmpInst =
4012 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
4013 SPIRVInstList.push_back(TmpInst);
4014 }
4015 SPIRVOperand *Op1IDOp =
4016 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4017 Ops.push_back(Op1IDOp);
4018
4019 uint32_t ShiftID = nextID;
4020
4021 SPIRVInstruction *Inst =
4022 new SPIRVInstruction(5, spv::OpShiftRightLogical, nextID++, Ops);
4023 SPIRVInstList.push_back(Inst);
4024
4025 //
4026 // Generate OpBitwiseAnd
4027 //
4028 // Ops[0] = Result Type ID
4029 // Ops[1] = Operand 0
4030 // Ops[2] = Operand 1
4031 //
4032 Ops.clear();
4033
4034 ResTyID = lookupType(CompositeTy);
4035 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4036 Ops.push_back(ResTyIDOp);
4037
4038 Op0ID = ShiftID;
4039 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4040 Ops.push_back(Op0IDOp);
4041
4042 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4043 Op1ID = VMap[CstFF];
4044 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4045 Ops.push_back(Op1IDOp);
4046
David Neto9b2d6252017-09-06 15:47:37 -04004047 // Reset mapping for this value to the result of the bitwise and.
4048 VMap[&I] = nextID;
4049
David Neto22f144c2017-06-12 14:26:21 -04004050 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4051 SPIRVInstList.push_back(Inst);
4052 break;
4053 }
4054
4055 // Ops[0] = Result Type ID
4056 // Ops[1] = Composite ID
4057 // Ops[2] ... Ops[n] = Indexes (Literal Number)
4058 SPIRVOperandList Ops;
4059
4060 uint32_t ResTyID = lookupType(I.getType());
4061 SPIRVOperand *ResTyIDOp =
4062 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4063 Ops.push_back(ResTyIDOp);
4064
4065 uint32_t CompositeID = VMap[I.getOperand(0)];
4066 SPIRVOperand *CompositeIDOp =
4067 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
4068 Ops.push_back(CompositeIDOp);
4069
4070 spv::Op Opcode = spv::OpCompositeExtract;
4071 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
4072 std::vector<uint32_t> LiteralNum;
4073 assert(CI->getZExtValue() < UINT32_MAX);
4074 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
4075 SPIRVOperand *Indexes =
4076 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4077 Ops.push_back(Indexes);
4078 } else {
4079 uint32_t IndexID = VMap[I.getOperand(1)];
4080 SPIRVOperand *IndexIDOp =
4081 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
4082 Ops.push_back(IndexIDOp);
4083 Opcode = spv::OpVectorExtractDynamic;
4084 }
4085
4086 uint16_t WordCount = 5;
4087 SPIRVInstruction *Inst =
4088 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4089 SPIRVInstList.push_back(Inst);
4090 break;
4091 }
4092 case Instruction::InsertElement: {
4093 // Handle <4 x i8> type manually.
4094 Type *CompositeTy = I.getOperand(0)->getType();
4095 if (is4xi8vec(CompositeTy)) {
4096 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
4097 uint32_t CstFFID = VMap[CstFF];
4098
4099 uint32_t ShiftAmountID = 0;
4100 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4101 // Handle constant index.
4102 uint64_t Idx = CI->getZExtValue();
4103 Value *ShiftAmount =
4104 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
4105 ShiftAmountID = VMap[ShiftAmount];
4106 } else {
4107 // Handle variable index.
4108 SPIRVOperandList TmpOps;
4109
4110 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
4111 SPIRVOperand *TmpResTyIDOp =
4112 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
4113 TmpOps.push_back(TmpResTyIDOp);
4114
4115 uint32_t IdxID = VMap[I.getOperand(2)];
4116 SPIRVOperand *TmpOp0IDOp =
4117 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
4118 TmpOps.push_back(TmpOp0IDOp);
4119
4120 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
4121 uint32_t Cst8ID = VMap[Cst8];
4122 SPIRVOperand *TmpOp1IDOp =
4123 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
4124 TmpOps.push_back(TmpOp1IDOp);
4125
4126 ShiftAmountID = nextID;
4127
4128 SPIRVInstruction *TmpInst =
4129 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
4130 SPIRVInstList.push_back(TmpInst);
4131 }
4132
4133 //
4134 // Generate mask operations.
4135 //
4136
4137 // ShiftLeft mask according to index of insertelement.
4138 SPIRVOperandList Ops;
4139
4140 uint32_t ResTyID = lookupType(CompositeTy);
4141 SPIRVOperand *ResTyIDOp =
4142 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4143 Ops.push_back(ResTyIDOp);
4144
4145 uint32_t Op0ID = CstFFID;
4146 SPIRVOperand *Op0IDOp =
4147 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4148 Ops.push_back(Op0IDOp);
4149
4150 uint32_t Op1ID = ShiftAmountID;
4151 SPIRVOperand *Op1IDOp =
4152 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4153 Ops.push_back(Op1IDOp);
4154
4155 uint32_t MaskID = nextID;
4156
4157 SPIRVInstruction *Inst =
4158 new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
4159 SPIRVInstList.push_back(Inst);
4160
4161 // Inverse mask.
4162 Ops.clear();
4163
4164 Ops.push_back(ResTyIDOp);
4165
4166 Op0ID = MaskID;
4167 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4168 Ops.push_back(Op0IDOp);
4169
4170 uint32_t InvMaskID = nextID;
4171
David Netoa394f392017-08-26 20:45:29 -04004172 Inst = new SPIRVInstruction(4, spv::OpNot, nextID++, Ops);
David Neto22f144c2017-06-12 14:26:21 -04004173 SPIRVInstList.push_back(Inst);
4174
4175 // Apply mask.
4176 Ops.clear();
4177
4178 Ops.push_back(ResTyIDOp);
4179
4180 Op0ID = VMap[I.getOperand(0)];
4181 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4182 Ops.push_back(Op0IDOp);
4183
4184 Op1ID = InvMaskID;
4185 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4186 Ops.push_back(Op1IDOp);
4187
4188 uint32_t OrgValID = nextID;
4189
4190 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4191 SPIRVInstList.push_back(Inst);
4192
4193 // Create correct value according to index of insertelement.
4194 Ops.clear();
4195
4196 Ops.push_back(ResTyIDOp);
4197
4198 Op0ID = VMap[I.getOperand(1)];
4199 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4200 Ops.push_back(Op0IDOp);
4201
4202 Op1ID = ShiftAmountID;
4203 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4204 Ops.push_back(Op1IDOp);
4205
4206 uint32_t InsertValID = nextID;
4207
4208 Inst = new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
4209 SPIRVInstList.push_back(Inst);
4210
4211 // Insert value to original value.
4212 Ops.clear();
4213
4214 Ops.push_back(ResTyIDOp);
4215
4216 Op0ID = OrgValID;
4217 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
4218 Ops.push_back(Op0IDOp);
4219
4220 Op1ID = InsertValID;
4221 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4222 Ops.push_back(Op1IDOp);
4223
David Netoa394f392017-08-26 20:45:29 -04004224 VMap[&I] = nextID;
4225
David Neto22f144c2017-06-12 14:26:21 -04004226 Inst = new SPIRVInstruction(5, spv::OpBitwiseOr, nextID++, Ops);
4227 SPIRVInstList.push_back(Inst);
4228
4229 break;
4230 }
4231
4232 // Ops[0] = Result Type ID
4233 // Ops[1] = Object ID
4234 // Ops[2] = Composite ID
4235 // Ops[3] ... Ops[n] = Indexes (Literal Number)
4236 SPIRVOperandList Ops;
4237
4238 uint32_t ResTyID = lookupType(I.getType());
4239 SPIRVOperand *ResTyIDOp =
4240 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4241 Ops.push_back(ResTyIDOp);
4242
4243 uint32_t ObjectID = VMap[I.getOperand(1)];
4244 SPIRVOperand *ObjectIDOp =
4245 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
4246 Ops.push_back(ObjectIDOp);
4247
4248 uint32_t CompositeID = VMap[I.getOperand(0)];
4249 SPIRVOperand *CompositeIDOp =
4250 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
4251 Ops.push_back(CompositeIDOp);
4252
4253 spv::Op Opcode = spv::OpCompositeInsert;
4254 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
4255 std::vector<uint32_t> LiteralNum;
4256 assert(CI->getZExtValue() < UINT32_MAX);
4257 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
4258 SPIRVOperand *Indexes =
4259 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4260 Ops.push_back(Indexes);
4261 } else {
4262 uint32_t IndexID = VMap[I.getOperand(1)];
4263 SPIRVOperand *IndexIDOp =
4264 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
4265 Ops.push_back(IndexIDOp);
4266 Opcode = spv::OpVectorInsertDynamic;
4267 }
4268
4269 uint16_t WordCount = 6;
4270 SPIRVInstruction *Inst =
4271 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4272 SPIRVInstList.push_back(Inst);
4273 break;
4274 }
4275 case Instruction::ShuffleVector: {
4276 // Ops[0] = Result Type ID
4277 // Ops[1] = Vector 1 ID
4278 // Ops[2] = Vector 2 ID
4279 // Ops[3] ... Ops[n] = Components (Literal Number)
4280 SPIRVOperandList Ops;
4281
4282 uint32_t ResTyID = lookupType(I.getType());
4283 SPIRVOperand *ResTyIDOp =
4284 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4285 Ops.push_back(ResTyIDOp);
4286
4287 uint32_t Vec1ID = VMap[I.getOperand(0)];
4288 SPIRVOperand *Vec1IDOp =
4289 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec1ID);
4290 Ops.push_back(Vec1IDOp);
4291
4292 uint32_t Vec2ID = VMap[I.getOperand(1)];
4293 SPIRVOperand *Vec2IDOp =
4294 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec2ID);
4295 Ops.push_back(Vec2IDOp);
4296
4297 uint64_t NumElements = 0;
4298 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4299 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4300
4301 if (Cst->isNullValue()) {
4302 for (unsigned i = 0; i < NumElements; i++) {
4303 std::vector<uint32_t> LiteralNum;
4304 LiteralNum.push_back(0);
4305 SPIRVOperand *Component =
4306 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4307 Ops.push_back(Component);
4308 }
4309 } else if (const ConstantDataSequential *CDS =
4310 dyn_cast<ConstantDataSequential>(Cst)) {
4311 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4312 std::vector<uint32_t> LiteralNum;
4313 assert(CDS->getElementAsInteger(i) < UINT32_MAX);
4314 LiteralNum.push_back(
4315 static_cast<uint32_t>(CDS->getElementAsInteger(i)));
4316 SPIRVOperand *Component =
4317 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4318 Ops.push_back(Component);
4319 }
4320 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4321 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4322 auto Op = CV->getOperand(i);
4323
4324 uint32_t literal = 0;
4325
4326 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4327 literal = static_cast<uint32_t>(CI->getZExtValue());
4328 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4329 literal = 0xFFFFFFFFu;
4330 } else {
4331 Op->print(errs());
4332 llvm_unreachable("Unsupported element in ConstantVector!");
4333 }
4334
4335 std::vector<uint32_t> LiteralNum;
4336 LiteralNum.push_back(literal);
4337 SPIRVOperand *Component =
4338 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4339 Ops.push_back(Component);
4340 }
4341 } else {
4342 Cst->print(errs());
4343 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4344 }
4345 }
4346
4347 uint16_t WordCount = static_cast<uint16_t>(5 + NumElements);
4348 SPIRVInstruction *Inst =
4349 new SPIRVInstruction(WordCount, spv::OpVectorShuffle, nextID++, Ops);
4350 SPIRVInstList.push_back(Inst);
4351 break;
4352 }
4353 case Instruction::ICmp:
4354 case Instruction::FCmp: {
4355 CmpInst *CmpI = cast<CmpInst>(&I);
4356
4357 // Ops[0] = Result Type ID
4358 // Ops[1] = Operand 1 ID
4359 // Ops[2] = Operand 2 ID
4360 SPIRVOperandList Ops;
4361
4362 uint32_t ResTyID = lookupType(CmpI->getType());
4363 SPIRVOperand *ResTyIDOp =
4364 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4365 Ops.push_back(ResTyIDOp);
4366
David Netod4ca2e62017-07-06 18:47:35 -04004367 // Pointer equality is invalid.
4368 Type* ArgTy = CmpI->getOperand(0)->getType();
4369 if (isa<PointerType>(ArgTy)) {
4370 CmpI->print(errs());
4371 std::string name = I.getParent()->getParent()->getName();
4372 errs()
4373 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4374 << "in function " << name << "\n";
4375 llvm_unreachable("Pointer equality check is invalid");
4376 break;
4377 }
4378
David Neto22f144c2017-06-12 14:26:21 -04004379 uint32_t Op1ID = VMap[CmpI->getOperand(0)];
4380 SPIRVOperand *Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4381 Ops.push_back(Op1IDOp);
4382
4383 uint32_t Op2ID = VMap[CmpI->getOperand(1)];
4384 SPIRVOperand *Op2IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op2ID);
4385 Ops.push_back(Op2IDOp);
4386
4387 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4388 SPIRVInstruction *Inst = new SPIRVInstruction(5, Opcode, nextID++, Ops);
4389 SPIRVInstList.push_back(Inst);
4390 break;
4391 }
4392 case Instruction::Br: {
4393 // Branch instrucion is deferred because it needs label's ID. Record slot's
4394 // location on SPIRVInstructionList.
4395 DeferredInsts.push_back(
4396 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4397 break;
4398 }
4399 case Instruction::Switch: {
4400 I.print(errs());
4401 llvm_unreachable("Unsupported instruction???");
4402 break;
4403 }
4404 case Instruction::IndirectBr: {
4405 I.print(errs());
4406 llvm_unreachable("Unsupported instruction???");
4407 break;
4408 }
4409 case Instruction::PHI: {
4410 // Branch instrucion is deferred because it needs label's ID. Record slot's
4411 // location on SPIRVInstructionList.
4412 DeferredInsts.push_back(
4413 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4414 break;
4415 }
4416 case Instruction::Alloca: {
4417 //
4418 // Generate OpVariable.
4419 //
4420 // Ops[0] : Result Type ID
4421 // Ops[1] : Storage Class
4422 SPIRVOperandList Ops;
4423
4424 Type *ResTy = I.getType();
4425 uint32_t ResTyID = lookupType(ResTy);
4426 SPIRVOperand *ResTyOp =
4427 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4428 Ops.push_back(ResTyOp);
4429
4430 spv::StorageClass StorageClass = spv::StorageClassFunction;
4431 SPIRVOperand *StorageClassOp =
4432 new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass);
4433 Ops.push_back(StorageClassOp);
4434
4435 SPIRVInstruction *Inst =
4436 new SPIRVInstruction(4, spv::OpVariable, nextID++, Ops);
4437 SPIRVInstList.push_back(Inst);
4438 break;
4439 }
4440 case Instruction::Load: {
4441 LoadInst *LD = cast<LoadInst>(&I);
4442 //
4443 // Generate OpLoad.
4444 //
4445
David Neto0a2f98d2017-09-15 19:38:40 -04004446 uint32_t ResTyID = lookupType(LD->getType());
David Netoa60b00b2017-09-15 16:34:09 -04004447 uint32_t PointerID = VMap[LD->getPointerOperand()];
4448
4449 // This is a hack to work around what looks like a driver bug.
4450 // When we're loading from the special variable holding the WorkgroupSize
David Neto0a2f98d2017-09-15 19:38:40 -04004451 // builtin value, use an OpBitWiseAnd of the value's ID rather than
4452 // generating a load.
David Netoa60b00b2017-09-15 16:34:09 -04004453 if (PointerID == WorkgroupSizeVarID) {
David Neto0a2f98d2017-09-15 19:38:40 -04004454 // Generate a bitwise-and of the original value with itself.
4455 // We should have been able to get away with just an OpCopyObject,
4456 // but we need something more complex to get past certain driver bugs.
4457 // This is ridiculous, but necessary.
4458 // TODO(dneto): Revisit this once drivers fix their bugs.
4459
4460 SPIRVOperandList Ops;
4461
4462 SPIRVOperand *ResTyIDOp =
4463 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4464 Ops.push_back(ResTyIDOp);
4465
4466 SPIRVOperand *ValueIDOp0 =
4467 new SPIRVOperand(SPIRVOperandType::NUMBERID, WorkgroupSizeValueID);
4468 Ops.push_back(ValueIDOp0);
4469
4470 SPIRVOperand *ValueIDOp1 =
4471 new SPIRVOperand(SPIRVOperandType::NUMBERID, WorkgroupSizeValueID);
4472 Ops.push_back(ValueIDOp1);
4473
4474 SPIRVInstruction *Inst =
4475 new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
4476 SPIRVInstList.push_back(Inst);
David Netoa60b00b2017-09-15 16:34:09 -04004477 break;
4478 }
4479
4480 // This is the normal path. Generate a load.
4481
David Neto22f144c2017-06-12 14:26:21 -04004482 // Ops[0] = Result Type ID
4483 // Ops[1] = Pointer ID
4484 // Ops[2] ... Ops[n] = Optional Memory Access
4485 //
4486 // TODO: Do we need to implement Optional Memory Access???
David Neto0a2f98d2017-09-15 19:38:40 -04004487
David Neto22f144c2017-06-12 14:26:21 -04004488 SPIRVOperandList Ops;
4489
David Neto22f144c2017-06-12 14:26:21 -04004490 SPIRVOperand *ResTyIDOp =
4491 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4492 Ops.push_back(ResTyIDOp);
4493
David Neto22f144c2017-06-12 14:26:21 -04004494 SPIRVOperand *PointerIDOp =
4495 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4496 Ops.push_back(PointerIDOp);
4497
4498 SPIRVInstruction *Inst =
4499 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4500 SPIRVInstList.push_back(Inst);
4501 break;
4502 }
4503 case Instruction::Store: {
4504 StoreInst *ST = cast<StoreInst>(&I);
4505 //
4506 // Generate OpStore.
4507 //
4508
4509 // Ops[0] = Pointer ID
4510 // Ops[1] = Object ID
4511 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4512 //
4513 // TODO: Do we need to implement Optional Memory Access???
4514 SPIRVOperand *Ops[2] = {new SPIRVOperand(SPIRVOperandType::NUMBERID,
4515 VMap[ST->getPointerOperand()]),
4516 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4517 VMap[ST->getValueOperand()])};
4518
4519 SPIRVInstruction *Inst =
4520 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4521 SPIRVInstList.push_back(Inst);
4522 break;
4523 }
4524 case Instruction::AtomicCmpXchg: {
4525 I.print(errs());
4526 llvm_unreachable("Unsupported instruction???");
4527 break;
4528 }
4529 case Instruction::AtomicRMW: {
Neil Henning39672102017-09-29 14:33:13 +01004530 AtomicRMWInst *AtomicRMW = dyn_cast<AtomicRMWInst>(&I);
4531
4532 spv::Op opcode;
4533
4534 switch (AtomicRMW->getOperation()) {
4535 default:
4536 I.print(errs());
4537 llvm_unreachable("Unsupported instruction???");
4538 case llvm::AtomicRMWInst::Add:
4539 opcode = spv::OpAtomicIAdd;
4540 break;
4541 case llvm::AtomicRMWInst::Sub:
4542 opcode = spv::OpAtomicISub;
4543 break;
4544 case llvm::AtomicRMWInst::Xchg:
4545 opcode = spv::OpAtomicExchange;
4546 break;
4547 case llvm::AtomicRMWInst::Min:
4548 opcode = spv::OpAtomicSMin;
4549 break;
4550 case llvm::AtomicRMWInst::Max:
4551 opcode = spv::OpAtomicSMax;
4552 break;
4553 case llvm::AtomicRMWInst::UMin:
4554 opcode = spv::OpAtomicUMin;
4555 break;
4556 case llvm::AtomicRMWInst::UMax:
4557 opcode = spv::OpAtomicUMax;
4558 break;
4559 case llvm::AtomicRMWInst::And:
4560 opcode = spv::OpAtomicAnd;
4561 break;
4562 case llvm::AtomicRMWInst::Or:
4563 opcode = spv::OpAtomicOr;
4564 break;
4565 case llvm::AtomicRMWInst::Xor:
4566 opcode = spv::OpAtomicXor;
4567 break;
4568 }
4569
4570 //
4571 // Generate OpAtomic*.
4572 //
4573 SPIRVOperandList Ops;
4574
4575 uint32_t TyID = lookupType(I.getType());
4576 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4577
4578 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4579 VMap[AtomicRMW->getPointerOperand()]));
4580
4581 auto IntTy = Type::getInt32Ty(I.getContext());
4582
4583 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
4584
4585 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4586 VMap[ConstantScopeDevice]));
4587
4588 const auto ConstantMemorySemantics = ConstantInt::get(
4589 IntTy, spv::MemorySemanticsUniformMemoryMask |
4590 spv::MemorySemanticsSequentiallyConsistentMask);
4591
4592 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4593 VMap[ConstantMemorySemantics]));
4594
4595 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4596 VMap[AtomicRMW->getValOperand()]));
4597
4598 VMap[&I] = nextID;
4599
4600 SPIRVInstruction *Inst = new SPIRVInstruction(
4601 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4602 SPIRVInstList.push_back(Inst);
David Neto22f144c2017-06-12 14:26:21 -04004603 break;
4604 }
4605 case Instruction::Fence: {
4606 I.print(errs());
4607 llvm_unreachable("Unsupported instruction???");
4608 break;
4609 }
4610 case Instruction::Call: {
4611 CallInst *Call = dyn_cast<CallInst>(&I);
4612 Function *Callee = Call->getCalledFunction();
4613
4614 // Sampler initializers become a load of the corresponding sampler.
4615 if (Callee->getName().equals("__translate_sampler_initializer")) {
4616 // Check that the sampler map was definitely used though.
4617 if (0 == getSamplerMap().size()) {
4618 llvm_unreachable("Sampler literal in source without sampler map!");
4619 }
4620
4621 SPIRVOperandList Ops;
4622
4623 uint32_t ResTyID = lookupType(SamplerTy->getPointerElementType());
4624 SPIRVOperand *ResTyIDOp =
4625 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4626 Ops.push_back(ResTyIDOp);
4627
4628 uint32_t PointerID = VMap[Call];
4629 SPIRVOperand *PointerIDOp =
4630 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4631 Ops.push_back(PointerIDOp);
4632
4633 VMap[Call] = nextID;
4634 SPIRVInstruction *Inst =
4635 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4636 SPIRVInstList.push_back(Inst);
4637
4638 break;
4639 }
4640
4641 if (Callee->getName().startswith("spirv.atomic")) {
4642 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4643 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4644 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4645 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4646 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4647 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4648 .Case("spirv.atomic_compare_exchange",
4649 spv::OpAtomicCompareExchange)
4650 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4651 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4652 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4653 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4654 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4655 .Case("spirv.atomic_or", spv::OpAtomicOr)
4656 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4657 .Default(spv::OpNop);
4658
4659 //
4660 // Generate OpAtomic*.
4661 //
4662 SPIRVOperandList Ops;
4663
4664 uint32_t TyID = lookupType(I.getType());
4665 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4666
4667 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4668 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4669 VMap[Call->getArgOperand(i)]));
4670 }
4671
4672 VMap[&I] = nextID;
4673
4674 SPIRVInstruction *Inst = new SPIRVInstruction(
4675 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4676 SPIRVInstList.push_back(Inst);
4677 break;
4678 }
4679
4680 if (Callee->getName().startswith("_Z3dot")) {
4681 // If the argument is a vector type, generate OpDot
4682 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4683 //
4684 // Generate OpDot.
4685 //
4686 SPIRVOperandList Ops;
4687
4688 uint32_t TyID = lookupType(I.getType());
4689 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4690
4691 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4692 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4693 VMap[Call->getArgOperand(i)]));
4694 }
4695
4696 VMap[&I] = nextID;
4697
4698 SPIRVInstruction *Inst = new SPIRVInstruction(
4699 static_cast<uint16_t>(2 + Ops.size()), spv::OpDot, nextID++, Ops);
4700 SPIRVInstList.push_back(Inst);
4701 } else {
4702 //
4703 // Generate OpFMul.
4704 //
4705 SPIRVOperandList Ops;
4706
4707 uint32_t TyID = lookupType(I.getType());
4708 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4709
4710 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4711 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4712 VMap[Call->getArgOperand(i)]));
4713 }
4714
4715 VMap[&I] = nextID;
4716
4717 SPIRVInstruction *Inst = new SPIRVInstruction(
4718 static_cast<uint16_t>(2 + Ops.size()), spv::OpFMul, nextID++, Ops);
4719 SPIRVInstList.push_back(Inst);
4720 }
4721 break;
4722 }
4723
David Neto8505ebf2017-10-13 18:50:50 -04004724 if (Callee->getName().startswith("_Z4fmod")) {
4725 // OpenCL fmod(x,y) is x - y * trunc(x/y)
4726 // The sign for a non-zero result is taken from x.
4727 // (Try an example.)
4728 // So translate to OpFRem
4729
4730 SPIRVOperandList Ops;
4731
4732 uint32_t TyID = lookupType(I.getType());
4733 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4734
4735 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4736 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4737 VMap[Call->getArgOperand(i)]));
4738 }
4739
4740 VMap[&I] = nextID;
4741
4742 SPIRVInstruction *Inst = new SPIRVInstruction(
4743 static_cast<uint16_t>(2 + Ops.size()), spv::OpFRem, nextID++, Ops);
4744 SPIRVInstList.push_back(Inst);
4745 break;
4746 }
4747
David Neto22f144c2017-06-12 14:26:21 -04004748 // spirv.store_null.* intrinsics become OpStore's.
4749 if (Callee->getName().startswith("spirv.store_null")) {
4750 //
4751 // Generate OpStore.
4752 //
4753
4754 // Ops[0] = Pointer ID
4755 // Ops[1] = Object ID
4756 // Ops[2] ... Ops[n]
4757 SPIRVOperandList Ops;
4758
4759 uint32_t PointerID = VMap[Call->getArgOperand(0)];
4760 SPIRVOperand *PointerIDOp =
4761 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4762 Ops.push_back(PointerIDOp);
4763
4764 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
4765 SPIRVOperand *ObjectIDOp =
4766 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
4767 Ops.push_back(ObjectIDOp);
4768
4769 SPIRVInstruction *Inst =
4770 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4771 SPIRVInstList.push_back(Inst);
4772
4773 break;
4774 }
4775
4776 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4777 if (Callee->getName().startswith("spirv.copy_memory")) {
4778 //
4779 // Generate OpCopyMemory.
4780 //
4781
4782 // Ops[0] = Dst ID
4783 // Ops[1] = Src ID
4784 // Ops[2] = Memory Access
4785 // Ops[3] = Alignment
4786
4787 auto IsVolatile =
4788 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4789
4790 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4791 : spv::MemoryAccessMaskNone;
4792
4793 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4794
4795 auto Alignment =
4796 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4797
4798 SPIRVOperand *Ops[4] = {
4799 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4800 VMap[Call->getArgOperand(0)]),
4801 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4802 VMap[Call->getArgOperand(1)]),
4803 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, MemoryAccess),
4804 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
4805 static_cast<uint32_t>(Alignment))};
4806
4807 SPIRVInstruction *Inst =
4808 new SPIRVInstruction(5, spv::OpCopyMemory, 0 /* No id */, Ops);
4809
4810 SPIRVInstList.push_back(Inst);
4811
4812 break;
4813 }
4814
4815 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4816 // with unit.
4817 if (Callee->getName().equals("_Z3absj") ||
4818 Callee->getName().equals("_Z3absDv2_j") ||
4819 Callee->getName().equals("_Z3absDv3_j") ||
4820 Callee->getName().equals("_Z3absDv4_j")) {
4821 VMap[&I] = VMap[Call->getOperand(0)];
4822 break;
4823 }
4824
4825 // barrier is converted to OpControlBarrier
4826 if (Callee->getName().equals("__spirv_control_barrier")) {
4827 //
4828 // Generate OpControlBarrier.
4829 //
4830 // Ops[0] = Execution Scope ID
4831 // Ops[1] = Memory Scope ID
4832 // Ops[2] = Memory Semantics ID
4833 //
4834 Value *ExecutionScope = Call->getArgOperand(0);
4835 Value *MemoryScope = Call->getArgOperand(1);
4836 Value *MemorySemantics = Call->getArgOperand(2);
4837
4838 SPIRVOperand *Ops[3] = {
4839 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[ExecutionScope]),
4840 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemoryScope]),
4841 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemorySemantics])};
4842
4843 SPIRVInstList.push_back(
4844 new SPIRVInstruction(4, spv::OpControlBarrier, 0 /* No id */, Ops));
4845 break;
4846 }
4847
4848 // memory barrier is converted to OpMemoryBarrier
4849 if (Callee->getName().equals("__spirv_memory_barrier")) {
4850 //
4851 // Generate OpMemoryBarrier.
4852 //
4853 // Ops[0] = Memory Scope ID
4854 // Ops[1] = Memory Semantics ID
4855 //
4856 SPIRVOperandList Ops;
4857
4858 Value *MemoryScope = Call->getArgOperand(0);
4859 Value *MemorySemantics = Call->getArgOperand(1);
4860
4861 uint32_t MemoryScopeID = VMap[MemoryScope];
4862 Ops.push_back(
4863 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemoryScopeID));
4864
4865 uint32_t MemorySemanticsID = VMap[MemorySemantics];
4866 Ops.push_back(
4867 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemorySemanticsID));
4868
4869 SPIRVInstruction *Inst =
4870 new SPIRVInstruction(3, spv::OpMemoryBarrier, 0 /* No id */, Ops);
4871 SPIRVInstList.push_back(Inst);
4872 break;
4873 }
4874
4875 // isinf is converted to OpIsInf
4876 if (Callee->getName().equals("__spirv_isinff") ||
4877 Callee->getName().equals("__spirv_isinfDv2_f") ||
4878 Callee->getName().equals("__spirv_isinfDv3_f") ||
4879 Callee->getName().equals("__spirv_isinfDv4_f")) {
4880 //
4881 // Generate OpIsInf.
4882 //
4883 // Ops[0] = Result Type ID
4884 // Ops[1] = X ID
4885 //
4886 SPIRVOperandList Ops;
4887
4888 uint32_t TyID = lookupType(I.getType());
4889 SPIRVOperand *ResTyIDOp =
4890 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4891 Ops.push_back(ResTyIDOp);
4892
4893 uint32_t XID = VMap[Call->getArgOperand(0)];
4894 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4895
4896 VMap[&I] = nextID;
4897
4898 SPIRVInstruction *Inst =
4899 new SPIRVInstruction(4, spv::OpIsInf, nextID++, Ops);
4900 SPIRVInstList.push_back(Inst);
4901 break;
4902 }
4903
4904 // isnan is converted to OpIsNan
4905 if (Callee->getName().equals("__spirv_isnanf") ||
4906 Callee->getName().equals("__spirv_isnanDv2_f") ||
4907 Callee->getName().equals("__spirv_isnanDv3_f") ||
4908 Callee->getName().equals("__spirv_isnanDv4_f")) {
4909 //
4910 // Generate OpIsInf.
4911 //
4912 // Ops[0] = Result Type ID
4913 // Ops[1] = X ID
4914 //
4915 SPIRVOperandList Ops;
4916
4917 uint32_t TyID = lookupType(I.getType());
4918 SPIRVOperand *ResTyIDOp =
4919 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4920 Ops.push_back(ResTyIDOp);
4921
4922 uint32_t XID = VMap[Call->getArgOperand(0)];
4923 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4924
4925 VMap[&I] = nextID;
4926
4927 SPIRVInstruction *Inst =
4928 new SPIRVInstruction(4, spv::OpIsNan, nextID++, Ops);
4929 SPIRVInstList.push_back(Inst);
4930 break;
4931 }
4932
4933 // all is converted to OpAll
4934 if (Callee->getName().equals("__spirv_allDv2_i") ||
4935 Callee->getName().equals("__spirv_allDv3_i") ||
4936 Callee->getName().equals("__spirv_allDv4_i")) {
4937 //
4938 // Generate OpAll.
4939 //
4940 // Ops[0] = Result Type ID
4941 // Ops[1] = Vector ID
4942 //
4943 SPIRVOperandList Ops;
4944
4945 uint32_t TyID = lookupType(I.getType());
4946 SPIRVOperand *ResTyIDOp =
4947 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4948 Ops.push_back(ResTyIDOp);
4949
4950 uint32_t VectorID = VMap[Call->getArgOperand(0)];
4951 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
4952
4953 VMap[&I] = nextID;
4954
4955 SPIRVInstruction *Inst =
4956 new SPIRVInstruction(4, spv::OpAll, nextID++, Ops);
4957 SPIRVInstList.push_back(Inst);
4958 break;
4959 }
4960
4961 // any is converted to OpAny
4962 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4963 Callee->getName().equals("__spirv_anyDv3_i") ||
4964 Callee->getName().equals("__spirv_anyDv4_i")) {
4965 //
4966 // Generate OpAny.
4967 //
4968 // Ops[0] = Result Type ID
4969 // Ops[1] = Vector ID
4970 //
4971 SPIRVOperandList Ops;
4972
4973 uint32_t TyID = lookupType(I.getType());
4974 SPIRVOperand *ResTyIDOp =
4975 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4976 Ops.push_back(ResTyIDOp);
4977
4978 uint32_t VectorID = VMap[Call->getArgOperand(0)];
4979 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
4980
4981 VMap[&I] = nextID;
4982
4983 SPIRVInstruction *Inst =
4984 new SPIRVInstruction(4, spv::OpAny, nextID++, Ops);
4985 SPIRVInstList.push_back(Inst);
4986 break;
4987 }
4988
4989 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4990 // Additionally, OpTypeSampledImage is generated.
4991 if (Callee->getName().equals(
4992 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4993 Callee->getName().equals(
4994 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4995 //
4996 // Generate OpSampledImage.
4997 //
4998 // Ops[0] = Result Type ID
4999 // Ops[1] = Image ID
5000 // Ops[2] = Sampler ID
5001 //
5002 SPIRVOperandList Ops;
5003
5004 Value *Image = Call->getArgOperand(0);
5005 Value *Sampler = Call->getArgOperand(1);
5006 Value *Coordinate = Call->getArgOperand(2);
5007
5008 TypeMapType &OpImageTypeMap = getImageTypeMap();
5009 Type *ImageTy = Image->getType()->getPointerElementType();
5010 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
5011 SPIRVOperand *ResTyIDOp =
5012 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageTyID);
5013 Ops.push_back(ResTyIDOp);
5014
5015 uint32_t ImageID = VMap[Image];
5016 SPIRVOperand *ImageIDOp =
5017 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
5018 Ops.push_back(ImageIDOp);
5019
5020 uint32_t SamplerID = VMap[Sampler];
5021 SPIRVOperand *SamplerIDOp =
5022 new SPIRVOperand(SPIRVOperandType::NUMBERID, SamplerID);
5023 Ops.push_back(SamplerIDOp);
5024
5025 uint32_t SampledImageID = nextID;
5026
5027 SPIRVInstruction *Inst =
5028 new SPIRVInstruction(5, spv::OpSampledImage, nextID++, Ops);
5029 SPIRVInstList.push_back(Inst);
5030
5031 //
5032 // Generate OpImageSampleExplicitLod.
5033 //
5034 // Ops[0] = Result Type ID
5035 // Ops[1] = Sampled Image ID
5036 // Ops[2] = Coordinate ID
5037 // Ops[3] = Image Operands Type ID
5038 // Ops[4] ... Ops[n] = Operands ID
5039 //
5040 Ops.clear();
5041
5042 uint32_t RetTyID = lookupType(Call->getType());
5043 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
5044 Ops.push_back(ResTyIDOp);
5045
5046 SPIRVOperand *SampledImageIDOp =
5047 new SPIRVOperand(SPIRVOperandType::NUMBERID, SampledImageID);
5048 Ops.push_back(SampledImageIDOp);
5049
5050 uint32_t CoordinateID = VMap[Coordinate];
5051 SPIRVOperand *CoordinateIDOp =
5052 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
5053 Ops.push_back(CoordinateIDOp);
5054
5055 std::vector<uint32_t> LiteralNum;
5056 LiteralNum.push_back(spv::ImageOperandsLodMask);
5057 SPIRVOperand *ImageOperandTyIDOp =
5058 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
5059 Ops.push_back(ImageOperandTyIDOp);
5060
5061 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
5062 uint32_t OperandID = VMap[CstFP0];
5063 SPIRVOperand *OperandIDOp =
5064 new SPIRVOperand(SPIRVOperandType::NUMBERID, OperandID);
5065 Ops.push_back(OperandIDOp);
5066
5067 VMap[&I] = nextID;
5068
5069 Inst =
5070 new SPIRVInstruction(7, spv::OpImageSampleExplicitLod, nextID++, Ops);
5071 SPIRVInstList.push_back(Inst);
5072 break;
5073 }
5074
5075 // write_imagef is mapped to OpImageWrite.
5076 if (Callee->getName().equals(
5077 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
5078 Callee->getName().equals(
5079 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
5080 //
5081 // Generate OpImageWrite.
5082 //
5083 // Ops[0] = Image ID
5084 // Ops[1] = Coordinate ID
5085 // Ops[2] = Texel ID
5086 // Ops[3] = (Optional) Image Operands Type (Literal Number)
5087 // Ops[4] ... Ops[n] = (Optional) Operands ID
5088 //
5089 SPIRVOperandList Ops;
5090
5091 Value *Image = Call->getArgOperand(0);
5092 Value *Coordinate = Call->getArgOperand(1);
5093 Value *Texel = Call->getArgOperand(2);
5094
5095 uint32_t ImageID = VMap[Image];
5096 SPIRVOperand *ImageIDOp =
5097 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
5098 Ops.push_back(ImageIDOp);
5099
5100 uint32_t CoordinateID = VMap[Coordinate];
5101 SPIRVOperand *CoordinateIDOp =
5102 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
5103 Ops.push_back(CoordinateIDOp);
5104
5105 uint32_t TexelID = VMap[Texel];
5106 SPIRVOperand *TexelIDOp =
5107 new SPIRVOperand(SPIRVOperandType::NUMBERID, TexelID);
5108 Ops.push_back(TexelIDOp);
5109
5110 SPIRVInstruction *Inst =
5111 new SPIRVInstruction(4, spv::OpImageWrite, 0 /* No id */, Ops);
5112 SPIRVInstList.push_back(Inst);
5113 break;
5114 }
5115
5116 // Call instrucion is deferred because it needs function's ID. Record
5117 // slot's location on SPIRVInstructionList.
5118 DeferredInsts.push_back(
5119 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
5120
David Neto3fbb4072017-10-16 11:28:14 -04005121 // Check whether the implementation of this call uses an extended
5122 // instruction plus one more value-producing instruction. If so, then
5123 // reserve the id for the extra value-producing slot.
5124 glsl::ExtInst EInst = getIndirectExtInstEnum(Callee->getName());
5125 if (EInst != kGlslExtInstBad) {
5126 // Reserve a spot for the extra value.
David Neto4d02a532017-09-17 12:57:44 -04005127 // Increase nextID.
David Neto22f144c2017-06-12 14:26:21 -04005128 VMap[&I] = nextID;
5129 nextID++;
5130 }
5131 break;
5132 }
5133 case Instruction::Ret: {
5134 unsigned NumOps = I.getNumOperands();
5135 if (NumOps == 0) {
5136 //
5137 // Generate OpReturn.
5138 //
5139
5140 // Empty Ops
5141 SPIRVOperandList Ops;
5142 SPIRVInstruction *Inst =
5143 new SPIRVInstruction(1, spv::OpReturn, 0 /* No id */, Ops);
5144 SPIRVInstList.push_back(Inst);
5145 } else {
5146 //
5147 // Generate OpReturnValue.
5148 //
5149
5150 // Ops[0] = Return Value ID
5151 SPIRVOperandList Ops;
5152 uint32_t RetValID = VMap[I.getOperand(0)];
5153 SPIRVOperand *RetValIDOp =
5154 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetValID);
5155 Ops.push_back(RetValIDOp);
5156
5157 SPIRVInstruction *Inst =
5158 new SPIRVInstruction(2, spv::OpReturnValue, 0 /* No id */, Ops);
5159 SPIRVInstList.push_back(Inst);
5160 break;
5161 }
5162 break;
5163 }
5164 }
5165}
5166
5167void SPIRVProducerPass::GenerateFuncEpilogue() {
5168 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5169
5170 //
5171 // Generate OpFunctionEnd
5172 //
5173
5174 // Empty Ops
5175 SPIRVOperandList Ops;
5176 SPIRVInstruction *Inst =
5177 new SPIRVInstruction(1, spv::OpFunctionEnd, 0 /* No id */, Ops);
5178 SPIRVInstList.push_back(Inst);
5179}
5180
5181bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
5182 LLVMContext &Context = Ty->getContext();
5183 if (Ty->isVectorTy()) {
5184 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
5185 Ty->getVectorNumElements() == 4) {
5186 return true;
5187 }
5188 }
5189
5190 return false;
5191}
5192
5193void SPIRVProducerPass::HandleDeferredInstruction() {
5194 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5195 ValueMapType &VMap = getValueMap();
5196 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
5197
5198 for (auto DeferredInst = DeferredInsts.rbegin();
5199 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
5200 Value *Inst = std::get<0>(*DeferredInst);
5201 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
5202 if (InsertPoint != SPIRVInstList.end()) {
5203 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
5204 ++InsertPoint;
5205 }
5206 }
5207
5208 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
5209 // Check whether basic block, which has this branch instruction, is loop
5210 // header or not. If it is loop header, generate OpLoopMerge and
5211 // OpBranchConditional.
5212 Function *Func = Br->getParent()->getParent();
5213 DominatorTree &DT =
5214 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
5215 const LoopInfo &LI =
5216 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
5217
5218 BasicBlock *BrBB = Br->getParent();
5219 if (LI.isLoopHeader(BrBB)) {
5220 Value *ContinueBB = nullptr;
5221 Value *MergeBB = nullptr;
5222
5223 Loop *L = LI.getLoopFor(BrBB);
5224 MergeBB = L->getExitBlock();
5225 if (!MergeBB) {
5226 // StructurizeCFG pass converts CFG into triangle shape and the cfg
5227 // has regions with single entry/exit. As a result, loop should not
5228 // have multiple exits.
5229 llvm_unreachable("Loop has multiple exits???");
5230 }
5231
5232 if (L->isLoopLatch(BrBB)) {
5233 ContinueBB = BrBB;
5234 } else {
5235 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
5236 // block.
5237 BasicBlock *Header = L->getHeader();
5238 BasicBlock *Latch = L->getLoopLatch();
5239 for (BasicBlock *BB : L->blocks()) {
5240 if (BB == Header) {
5241 continue;
5242 }
5243
5244 // Check whether block dominates block with back-edge.
5245 if (DT.dominates(BB, Latch)) {
5246 ContinueBB = BB;
5247 }
5248 }
5249
5250 if (!ContinueBB) {
5251 llvm_unreachable("Wrong continue block from loop");
5252 }
5253 }
5254
5255 //
5256 // Generate OpLoopMerge.
5257 //
5258 // Ops[0] = Merge Block ID
5259 // Ops[1] = Continue Target ID
5260 // Ops[2] = Selection Control
5261 SPIRVOperandList Ops;
5262
5263 // StructurizeCFG pass already manipulated CFG. Just use false block of
5264 // branch instruction as merge block.
5265 uint32_t MergeBBID = VMap[MergeBB];
5266 SPIRVOperand *MergeBBIDOp =
5267 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
5268 Ops.push_back(MergeBBIDOp);
5269
5270 uint32_t ContinueBBID = VMap[ContinueBB];
5271 SPIRVOperand *ContinueBBIDOp =
5272 new SPIRVOperand(SPIRVOperandType::NUMBERID, ContinueBBID);
5273 Ops.push_back(ContinueBBIDOp);
5274
5275 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
5276 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
5277 Ops.push_back(SelectionControlOp);
5278
5279 SPIRVInstruction *MergeInst =
5280 new SPIRVInstruction(4, spv::OpLoopMerge, 0 /* No id */, Ops);
5281 SPIRVInstList.insert(InsertPoint, MergeInst);
5282
5283 } else if (Br->isConditional()) {
5284 bool HasBackEdge = false;
5285
5286 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
5287 if (LI.isLoopHeader(Br->getSuccessor(i))) {
5288 HasBackEdge = true;
5289 }
5290 }
5291 if (!HasBackEdge) {
5292 //
5293 // Generate OpSelectionMerge.
5294 //
5295 // Ops[0] = Merge Block ID
5296 // Ops[1] = Selection Control
5297 SPIRVOperandList Ops;
5298
5299 // StructurizeCFG pass already manipulated CFG. Just use false block
5300 // of branch instruction as merge block.
5301 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
5302 SPIRVOperand *MergeBBIDOp =
5303 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
5304 Ops.push_back(MergeBBIDOp);
5305
5306 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
5307 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
5308 Ops.push_back(SelectionControlOp);
5309
5310 SPIRVInstruction *MergeInst = new SPIRVInstruction(
5311 3, spv::OpSelectionMerge, 0 /* No id */, Ops);
5312 SPIRVInstList.insert(InsertPoint, MergeInst);
5313 }
5314 }
5315
5316 if (Br->isConditional()) {
5317 //
5318 // Generate OpBranchConditional.
5319 //
5320 // Ops[0] = Condition ID
5321 // Ops[1] = True Label ID
5322 // Ops[2] = False Label ID
5323 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
5324 SPIRVOperandList Ops;
5325
5326 uint32_t CondID = VMap[Br->getCondition()];
5327 SPIRVOperand *CondIDOp =
5328 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
5329 Ops.push_back(CondIDOp);
5330
5331 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
5332 SPIRVOperand *TrueBBIDOp =
5333 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueBBID);
5334 Ops.push_back(TrueBBIDOp);
5335
5336 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
5337 SPIRVOperand *FalseBBIDOp =
5338 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseBBID);
5339 Ops.push_back(FalseBBIDOp);
5340
5341 SPIRVInstruction *BrInst = new SPIRVInstruction(
5342 4, spv::OpBranchConditional, 0 /* No id */, Ops);
5343 SPIRVInstList.insert(InsertPoint, BrInst);
5344 } else {
5345 //
5346 // Generate OpBranch.
5347 //
5348 // Ops[0] = Target Label ID
5349 SPIRVOperandList Ops;
5350
5351 uint32_t TargetID = VMap[Br->getSuccessor(0)];
5352 SPIRVOperand *TargetIDOp =
5353 new SPIRVOperand(SPIRVOperandType::NUMBERID, TargetID);
5354 Ops.push_back(TargetIDOp);
5355
5356 SPIRVInstList.insert(
5357 InsertPoint,
5358 new SPIRVInstruction(2, spv::OpBranch, 0 /* No id */, Ops));
5359 }
5360 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
5361 //
5362 // Generate OpPhi.
5363 //
5364 // Ops[0] = Result Type ID
5365 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
5366 SPIRVOperandList Ops;
5367
5368 uint32_t ResTyID = lookupType(PHI->getType());
5369 SPIRVOperand *ResTyIDOp =
5370 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5371 Ops.push_back(ResTyIDOp);
5372
5373 uint16_t WordCount = 3;
5374 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
5375 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
5376 SPIRVOperand *VarIDOp =
5377 new SPIRVOperand(SPIRVOperandType::NUMBERID, VarID);
5378 Ops.push_back(VarIDOp);
5379
5380 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
5381 SPIRVOperand *ParentIDOp =
5382 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParentID);
5383 Ops.push_back(ParentIDOp);
5384
5385 WordCount += 2;
5386 }
5387
5388 SPIRVInstList.insert(
5389 InsertPoint, new SPIRVInstruction(WordCount, spv::OpPhi,
5390 std::get<2>(*DeferredInst), Ops));
5391 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
5392 Function *Callee = Call->getCalledFunction();
David Neto3fbb4072017-10-16 11:28:14 -04005393 auto callee_name = Callee->getName();
5394 glsl::ExtInst EInst = getDirectOrIndirectExtInstEnum(callee_name);
David Neto22f144c2017-06-12 14:26:21 -04005395
5396 if (EInst) {
5397 uint32_t &ExtInstImportID = getOpExtInstImportID();
5398
5399 //
5400 // Generate OpExtInst.
5401 //
5402
5403 // Ops[0] = Result Type ID
5404 // Ops[1] = Set ID (OpExtInstImport ID)
5405 // Ops[2] = Instruction Number (Literal Number)
5406 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5407 SPIRVOperandList Ops;
5408
5409 uint32_t ResTyID = lookupType(Call->getType());
5410 SPIRVOperand *ResTyIDOp =
5411 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5412 Ops.push_back(ResTyIDOp);
5413
5414 SPIRVOperand *SetIDOp =
5415 new SPIRVOperand(SPIRVOperandType::NUMBERID, ExtInstImportID);
5416 Ops.push_back(SetIDOp);
5417
5418 std::vector<uint32_t> LiteralNum;
5419 LiteralNum.push_back(EInst);
5420 SPIRVOperand *InstructionOp =
5421 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
5422 Ops.push_back(InstructionOp);
5423
5424 uint16_t WordCount = 5;
5425
5426 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5427 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5428 uint32_t ArgID = VMap[Call->getOperand(i)];
5429 SPIRVOperand *ArgIDOp =
5430 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5431 Ops.push_back(ArgIDOp);
5432 WordCount++;
5433 }
5434
5435 SPIRVInstruction *ExtInst = new SPIRVInstruction(
5436 WordCount, spv::OpExtInst, std::get<2>(*DeferredInst), Ops);
5437 SPIRVInstList.insert(InsertPoint, ExtInst);
5438
David Neto3fbb4072017-10-16 11:28:14 -04005439 const auto IndirectExtInst = getIndirectExtInstEnum(callee_name);
5440 if (IndirectExtInst != kGlslExtInstBad) {
5441 // Generate one more instruction that uses the result of the extended
5442 // instruction. Its result id is one more than the id of the
5443 // extended instruction.
David Neto22f144c2017-06-12 14:26:21 -04005444 LLVMContext &Context =
5445 Call->getParent()->getParent()->getParent()->getContext();
David Neto22f144c2017-06-12 14:26:21 -04005446
David Neto3fbb4072017-10-16 11:28:14 -04005447 auto generate_extra_inst = [this, &Context, &Call, &DeferredInst,
5448 &VMap, &SPIRVInstList, &InsertPoint](
5449 spv::Op opcode, Constant *constant) {
5450 //
5451 // Generate instruction like:
5452 // result = opcode constant <extinst-result>
5453 //
5454 // Ops[0] = Result Type ID
5455 // Ops[1] = Operand 0 ;; the constant, suitably splatted
5456 // Ops[2] = Operand 1 ;; the result of the extended instruction
5457 SPIRVOperandList Ops;
David Neto22f144c2017-06-12 14:26:21 -04005458
David Neto3fbb4072017-10-16 11:28:14 -04005459 Type *resultTy = Call->getType();
5460 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5461 lookupType(resultTy)));
5462
5463 if (auto *vectorTy = dyn_cast<VectorType>(resultTy)) {
5464 constant = ConstantVector::getSplat(
5465 static_cast<unsigned>(vectorTy->getNumElements()), constant);
5466 }
5467 uint32_t Op0ID = VMap[constant];
5468 SPIRVOperand *Op0IDOp =
5469 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
5470 Ops.push_back(Op0IDOp);
5471
5472 SPIRVOperand *Op1IDOp = new SPIRVOperand(
5473 SPIRVOperandType::NUMBERID, std::get<2>(*DeferredInst));
5474 Ops.push_back(Op1IDOp);
5475
5476 SPIRVInstList.insert(
5477 InsertPoint,
5478 new SPIRVInstruction(5, opcode, std::get<2>(*DeferredInst) + 1,
5479 Ops));
5480 };
5481
5482 switch (IndirectExtInst) {
5483 case glsl::ExtInstFindUMsb: // Implementing clz
5484 generate_extra_inst(
5485 spv::OpISub, ConstantInt::get(Type::getInt32Ty(Context), 31));
5486 break;
5487 case glsl::ExtInstAcos: // Implementing acospi
5488 case glsl::ExtInstAsin: // Implementing asinpi
5489 case glsl::ExtInstAtan2: // Implementing atan2pi
5490 generate_extra_inst(
5491 spv::OpFMul,
5492 ConstantFP::get(Type::getFloatTy(Context), kOneOverPi));
5493 break;
5494
5495 default:
5496 assert(false && "internally inconsistent");
David Neto4d02a532017-09-17 12:57:44 -04005497 }
David Neto22f144c2017-06-12 14:26:21 -04005498 }
David Neto3fbb4072017-10-16 11:28:14 -04005499
David Neto22f144c2017-06-12 14:26:21 -04005500 } else if (Callee->getName().equals("_Z8popcounti") ||
5501 Callee->getName().equals("_Z8popcountj") ||
5502 Callee->getName().equals("_Z8popcountDv2_i") ||
5503 Callee->getName().equals("_Z8popcountDv3_i") ||
5504 Callee->getName().equals("_Z8popcountDv4_i") ||
5505 Callee->getName().equals("_Z8popcountDv2_j") ||
5506 Callee->getName().equals("_Z8popcountDv3_j") ||
5507 Callee->getName().equals("_Z8popcountDv4_j")) {
5508 //
5509 // Generate OpBitCount
5510 //
5511 // Ops[0] = Result Type ID
5512 // Ops[1] = Base ID
5513 SPIRVOperand *Ops[2]{new SPIRVOperand(SPIRVOperandType::NUMBERID,
5514 lookupType(Call->getType())),
5515 new SPIRVOperand(SPIRVOperandType::NUMBERID,
5516 VMap[Call->getOperand(0)])};
5517
5518 SPIRVInstList.insert(
5519 InsertPoint, new SPIRVInstruction(4, spv::OpBitCount,
5520 std::get<2>(*DeferredInst), Ops));
David Netoab03f432017-11-03 17:00:44 -04005521
5522 } else if (Callee->getName().startswith(kCompositeConstructFunctionPrefix)) {
5523
5524 // Generate an OpCompositeConstruct
5525 SPIRVOperandList Ops;
5526
5527 // The result type.
5528 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5529 lookupType(Call->getType())));
5530
5531 for (Use &use : Call->arg_operands()) {
5532 Value* val = use.get();
5533 Ops.push_back(
5534 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[use.get()]));
5535 }
5536
5537 SPIRVInstList.insert(
5538 InsertPoint,
5539 new SPIRVInstruction(2 + Ops.size(), spv::OpCompositeConstruct,
5540 std::get<2>(*DeferredInst), Ops));
5541
David Neto22f144c2017-06-12 14:26:21 -04005542 } else {
5543 //
5544 // Generate OpFunctionCall.
5545 //
5546
5547 // Ops[0] = Result Type ID
5548 // Ops[1] = Callee Function ID
5549 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5550 SPIRVOperandList Ops;
5551
5552 uint32_t ResTyID = lookupType(Call->getType());
5553 SPIRVOperand *ResTyIDOp =
5554 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5555 Ops.push_back(ResTyIDOp);
5556
5557 uint32_t CalleeID = VMap[Callee];
David Neto43568eb2017-10-13 18:25:25 -04005558 if (CalleeID == 0) {
5559 errs() << "Can't translate function call. Missing builtin? "
5560 << Callee->getName() << " in: " << *Call << "\n";
5561 // TODO(dneto): Can we error out? Enabling this llvm_unreachable
5562 // causes an infinite loop. Instead, go ahead and generate
5563 // the bad function call. A validator will catch the 0-Id.
5564 // llvm_unreachable("Can't translate function call");
5565 }
David Neto22f144c2017-06-12 14:26:21 -04005566
5567 SPIRVOperand *CalleeIDOp =
5568 new SPIRVOperand(SPIRVOperandType::NUMBERID, CalleeID);
5569 Ops.push_back(CalleeIDOp);
5570
5571 uint16_t WordCount = 4;
5572
5573 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5574 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5575 uint32_t ArgID = VMap[Call->getOperand(i)];
5576 SPIRVOperand *ArgIDOp =
5577 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5578 Ops.push_back(ArgIDOp);
5579 WordCount++;
5580 }
5581
5582 SPIRVInstruction *CallInst = new SPIRVInstruction(
5583 WordCount, spv::OpFunctionCall, std::get<2>(*DeferredInst), Ops);
5584 SPIRVInstList.insert(InsertPoint, CallInst);
5585 }
5586 }
5587 }
5588}
5589
David Neto1a1a0582017-07-07 12:01:44 -04005590void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
5591 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5592 // instructions we generated earlier.
5593 if (getPointerTypesNeedingArrayStride().empty())
5594 return;
5595
5596 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
David Neto1a1a0582017-07-07 12:01:44 -04005597
5598 // Find an iterator pointing just past the last decoration.
5599 bool seen_decorations = false;
5600 auto DecoInsertPoint =
5601 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5602 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5603 const bool is_decoration =
5604 Inst->getOpcode() == spv::OpDecorate ||
5605 Inst->getOpcode() == spv::OpMemberDecorate;
5606 if (is_decoration) {
5607 seen_decorations = true;
5608 return false;
5609 } else {
5610 return seen_decorations;
5611 }
5612 });
5613
5614 for (auto *type : getPointerTypesNeedingArrayStride()) {
5615 auto *ptrType = cast<PointerType>(type);
5616
5617 // Ops[0] = Target ID
5618 // Ops[1] = Decoration (ArrayStride)
5619 // Ops[2] = Stride number (Literal Number)
5620 SPIRVOperandList Ops;
5621
5622 Ops.push_back(
5623 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(ptrType)));
5624 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5625 spv::DecorationArrayStride));
5626 Type *elemTy = ptrType->getElementType();
5627 // Same as DL.getIndexedOfffsetInType( elemTy, { 1 } );
Neil Henning39672102017-09-29 14:33:13 +01005628 const uint32_t stride = static_cast<uint32_t>(DL.getTypeAllocSize(elemTy));
David Neto1a1a0582017-07-07 12:01:44 -04005629 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, stride));
5630
5631 SPIRVInstruction *DecoInst =
5632 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
5633 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5634 }
5635}
5636
David Neto22f144c2017-06-12 14:26:21 -04005637glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5638 return StringSwitch<glsl::ExtInst>(Name)
5639 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5640 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5641 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5642 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5643 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5644 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5645 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5646 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5647 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5648 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5649 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5650 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5651 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5652 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5653 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5654 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
David Neto22f144c2017-06-12 14:26:21 -04005655 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5656 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5657 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5658 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5659 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5660 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5661 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5662 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5663 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5664 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5665 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5666 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5667 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5668 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5669 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5670 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5671 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5672 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5673 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5674 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5675 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5676 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5677 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5678 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5679 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5680 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5681 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5682 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5683 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5684 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5685 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5686 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5687 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5688 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5689 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5690 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5691 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5692 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5693 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5694 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5695 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5696 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5697 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5698 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5699 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5700 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5701 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5702 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5703 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5704 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5705 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5706 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5707 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5708 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5709 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5710 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5711 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5712 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5713 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5714 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5715 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5716 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5717 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5718 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5719 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5720 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5721 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5722 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5723 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5724 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5725 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5726 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5727 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5728 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5729 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5730 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5731 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5732 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5733 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5734 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
David Netoe9a03512017-10-16 10:08:27 -04005735 .StartsWith("_Z4step", glsl::ExtInst::ExtInstStep)
David Neto22f144c2017-06-12 14:26:21 -04005736 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5737 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5738 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5739 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5740 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
David Neto62653202017-10-16 19:05:18 -04005741 .Case("clspv.fract.f", glsl::ExtInst::ExtInstFract)
5742 .Case("clspv.fract.v2f", glsl::ExtInst::ExtInstFract)
5743 .Case("clspv.fract.v3f", glsl::ExtInst::ExtInstFract)
5744 .Case("clspv.fract.v4f", glsl::ExtInst::ExtInstFract)
David Neto3fbb4072017-10-16 11:28:14 -04005745 .Default(kGlslExtInstBad);
5746}
5747
5748glsl::ExtInst SPIRVProducerPass::getIndirectExtInstEnum(StringRef Name) {
5749 // Check indirect cases.
5750 return StringSwitch<glsl::ExtInst>(Name)
5751 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5752 // Use exact match on float arg because these need a multiply
5753 // of a constant of the right floating point type.
5754 .Case("_Z6acospif", glsl::ExtInst::ExtInstAcos)
5755 .Case("_Z6acospiDv2_f", glsl::ExtInst::ExtInstAcos)
5756 .Case("_Z6acospiDv3_f", glsl::ExtInst::ExtInstAcos)
5757 .Case("_Z6acospiDv4_f", glsl::ExtInst::ExtInstAcos)
5758 .Case("_Z6asinpif", glsl::ExtInst::ExtInstAsin)
5759 .Case("_Z6asinpiDv2_f", glsl::ExtInst::ExtInstAsin)
5760 .Case("_Z6asinpiDv3_f", glsl::ExtInst::ExtInstAsin)
5761 .Case("_Z6asinpiDv4_f", glsl::ExtInst::ExtInstAsin)
5762 .Case("_Z7atan2piff", glsl::ExtInst::ExtInstAtan2)
5763 .Case("_Z7atan2piDv2_fS_", glsl::ExtInst::ExtInstAtan2)
5764 .Case("_Z7atan2piDv3_fS_", glsl::ExtInst::ExtInstAtan2)
5765 .Case("_Z7atan2piDv4_fS_", glsl::ExtInst::ExtInstAtan2)
5766 .Default(kGlslExtInstBad);
5767}
5768
5769glsl::ExtInst SPIRVProducerPass::getDirectOrIndirectExtInstEnum(StringRef Name) {
5770 auto direct = getExtInstEnum(Name);
5771 if (direct != kGlslExtInstBad)
5772 return direct;
5773 return getIndirectExtInstEnum(Name);
David Neto22f144c2017-06-12 14:26:21 -04005774}
5775
5776void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5777 out << "%" << Inst->getResultID();
5778}
5779
5780void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5781 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5782 out << "\t" << spv::getOpName(Opcode);
5783}
5784
5785void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5786 SPIRVOperandType OpTy = Op->getType();
5787 switch (OpTy) {
5788 default: {
5789 llvm_unreachable("Unsupported SPIRV Operand Type???");
5790 break;
5791 }
5792 case SPIRVOperandType::NUMBERID: {
5793 out << "%" << Op->getNumID();
5794 break;
5795 }
5796 case SPIRVOperandType::LITERAL_STRING: {
5797 out << "\"" << Op->getLiteralStr() << "\"";
5798 break;
5799 }
5800 case SPIRVOperandType::LITERAL_INTEGER: {
5801 // TODO: Handle LiteralNum carefully.
5802 for (auto Word : Op->getLiteralNum()) {
5803 out << Word;
5804 }
5805 break;
5806 }
5807 case SPIRVOperandType::LITERAL_FLOAT: {
5808 // TODO: Handle LiteralNum carefully.
5809 for (auto Word : Op->getLiteralNum()) {
5810 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5811 SmallString<8> Str;
5812 APF.toString(Str, 6, 2);
5813 out << Str;
5814 }
5815 break;
5816 }
5817 }
5818}
5819
5820void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5821 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5822 out << spv::getCapabilityName(Cap);
5823}
5824
5825void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5826 auto LiteralNum = Op->getLiteralNum();
5827 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5828 out << glsl::getExtInstName(Ext);
5829}
5830
5831void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5832 spv::AddressingModel AddrModel =
5833 static_cast<spv::AddressingModel>(Op->getNumID());
5834 out << spv::getAddressingModelName(AddrModel);
5835}
5836
5837void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5838 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5839 out << spv::getMemoryModelName(MemModel);
5840}
5841
5842void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5843 spv::ExecutionModel ExecModel =
5844 static_cast<spv::ExecutionModel>(Op->getNumID());
5845 out << spv::getExecutionModelName(ExecModel);
5846}
5847
5848void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5849 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5850 out << spv::getExecutionModeName(ExecMode);
5851}
5852
5853void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5854 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5855 out << spv::getSourceLanguageName(SourceLang);
5856}
5857
5858void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5859 spv::FunctionControlMask FuncCtrl =
5860 static_cast<spv::FunctionControlMask>(Op->getNumID());
5861 out << spv::getFunctionControlName(FuncCtrl);
5862}
5863
5864void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5865 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5866 out << getStorageClassName(StClass);
5867}
5868
5869void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5870 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5871 out << getDecorationName(Deco);
5872}
5873
5874void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5875 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5876 out << getBuiltInName(BIn);
5877}
5878
5879void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5880 spv::SelectionControlMask BIn =
5881 static_cast<spv::SelectionControlMask>(Op->getNumID());
5882 out << getSelectionControlName(BIn);
5883}
5884
5885void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5886 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5887 out << getLoopControlName(BIn);
5888}
5889
5890void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5891 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5892 out << getDimName(DIM);
5893}
5894
5895void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5896 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5897 out << getImageFormatName(Format);
5898}
5899
5900void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5901 out << spv::getMemoryAccessName(
5902 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5903}
5904
5905void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5906 auto LiteralNum = Op->getLiteralNum();
5907 spv::ImageOperandsMask Type =
5908 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5909 out << getImageOperandsName(Type);
5910}
5911
5912void SPIRVProducerPass::WriteSPIRVAssembly() {
5913 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5914
5915 for (auto Inst : SPIRVInstList) {
5916 SPIRVOperandList Ops = Inst->getOperands();
5917 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5918
5919 switch (Opcode) {
5920 default: {
5921 llvm_unreachable("Unsupported SPIRV instruction");
5922 break;
5923 }
5924 case spv::OpCapability: {
5925 // Ops[0] = Capability
5926 PrintOpcode(Inst);
5927 out << " ";
5928 PrintCapability(Ops[0]);
5929 out << "\n";
5930 break;
5931 }
5932 case spv::OpMemoryModel: {
5933 // Ops[0] = Addressing Model
5934 // Ops[1] = Memory Model
5935 PrintOpcode(Inst);
5936 out << " ";
5937 PrintAddrModel(Ops[0]);
5938 out << " ";
5939 PrintMemModel(Ops[1]);
5940 out << "\n";
5941 break;
5942 }
5943 case spv::OpEntryPoint: {
5944 // Ops[0] = Execution Model
5945 // Ops[1] = EntryPoint ID
5946 // Ops[2] = Name (Literal String)
5947 // Ops[3] ... Ops[n] = Interface ID
5948 PrintOpcode(Inst);
5949 out << " ";
5950 PrintExecModel(Ops[0]);
5951 for (uint32_t i = 1; i < Ops.size(); i++) {
5952 out << " ";
5953 PrintOperand(Ops[i]);
5954 }
5955 out << "\n";
5956 break;
5957 }
5958 case spv::OpExecutionMode: {
5959 // Ops[0] = Entry Point ID
5960 // Ops[1] = Execution Mode
5961 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5962 PrintOpcode(Inst);
5963 out << " ";
5964 PrintOperand(Ops[0]);
5965 out << " ";
5966 PrintExecMode(Ops[1]);
5967 for (uint32_t i = 2; i < Ops.size(); i++) {
5968 out << " ";
5969 PrintOperand(Ops[i]);
5970 }
5971 out << "\n";
5972 break;
5973 }
5974 case spv::OpSource: {
5975 // Ops[0] = SourceLanguage ID
5976 // Ops[1] = Version (LiteralNum)
5977 PrintOpcode(Inst);
5978 out << " ";
5979 PrintSourceLanguage(Ops[0]);
5980 out << " ";
5981 PrintOperand(Ops[1]);
5982 out << "\n";
5983 break;
5984 }
5985 case spv::OpDecorate: {
5986 // Ops[0] = Target ID
5987 // Ops[1] = Decoration (Block or BufferBlock)
5988 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5989 PrintOpcode(Inst);
5990 out << " ";
5991 PrintOperand(Ops[0]);
5992 out << " ";
5993 PrintDecoration(Ops[1]);
5994 // Handle BuiltIn OpDecorate specially.
5995 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5996 out << " ";
5997 PrintBuiltIn(Ops[2]);
5998 } else {
5999 for (uint32_t i = 2; i < Ops.size(); i++) {
6000 out << " ";
6001 PrintOperand(Ops[i]);
6002 }
6003 }
6004 out << "\n";
6005 break;
6006 }
6007 case spv::OpMemberDecorate: {
6008 // Ops[0] = Structure Type ID
6009 // Ops[1] = Member Index(Literal Number)
6010 // Ops[2] = Decoration
6011 // Ops[3] ... Ops[n] = Optional literals according to Decoration
6012 PrintOpcode(Inst);
6013 out << " ";
6014 PrintOperand(Ops[0]);
6015 out << " ";
6016 PrintOperand(Ops[1]);
6017 out << " ";
6018 PrintDecoration(Ops[2]);
6019 for (uint32_t i = 3; i < Ops.size(); i++) {
6020 out << " ";
6021 PrintOperand(Ops[i]);
6022 }
6023 out << "\n";
6024 break;
6025 }
6026 case spv::OpTypePointer: {
6027 // Ops[0] = Storage Class
6028 // Ops[1] = Element Type ID
6029 PrintResID(Inst);
6030 out << " = ";
6031 PrintOpcode(Inst);
6032 out << " ";
6033 PrintStorageClass(Ops[0]);
6034 out << " ";
6035 PrintOperand(Ops[1]);
6036 out << "\n";
6037 break;
6038 }
6039 case spv::OpTypeImage: {
6040 // Ops[0] = Sampled Type ID
6041 // Ops[1] = Dim ID
6042 // Ops[2] = Depth (Literal Number)
6043 // Ops[3] = Arrayed (Literal Number)
6044 // Ops[4] = MS (Literal Number)
6045 // Ops[5] = Sampled (Literal Number)
6046 // Ops[6] = Image Format ID
6047 PrintResID(Inst);
6048 out << " = ";
6049 PrintOpcode(Inst);
6050 out << " ";
6051 PrintOperand(Ops[0]);
6052 out << " ";
6053 PrintDimensionality(Ops[1]);
6054 out << " ";
6055 PrintOperand(Ops[2]);
6056 out << " ";
6057 PrintOperand(Ops[3]);
6058 out << " ";
6059 PrintOperand(Ops[4]);
6060 out << " ";
6061 PrintOperand(Ops[5]);
6062 out << " ";
6063 PrintImageFormat(Ops[6]);
6064 out << "\n";
6065 break;
6066 }
6067 case spv::OpFunction: {
6068 // Ops[0] : Result Type ID
6069 // Ops[1] : Function Control
6070 // Ops[2] : Function Type ID
6071 PrintResID(Inst);
6072 out << " = ";
6073 PrintOpcode(Inst);
6074 out << " ";
6075 PrintOperand(Ops[0]);
6076 out << " ";
6077 PrintFuncCtrl(Ops[1]);
6078 out << " ";
6079 PrintOperand(Ops[2]);
6080 out << "\n";
6081 break;
6082 }
6083 case spv::OpSelectionMerge: {
6084 // Ops[0] = Merge Block ID
6085 // Ops[1] = Selection Control
6086 PrintOpcode(Inst);
6087 out << " ";
6088 PrintOperand(Ops[0]);
6089 out << " ";
6090 PrintSelectionControl(Ops[1]);
6091 out << "\n";
6092 break;
6093 }
6094 case spv::OpLoopMerge: {
6095 // Ops[0] = Merge Block ID
6096 // Ops[1] = Continue Target ID
6097 // Ops[2] = Selection Control
6098 PrintOpcode(Inst);
6099 out << " ";
6100 PrintOperand(Ops[0]);
6101 out << " ";
6102 PrintOperand(Ops[1]);
6103 out << " ";
6104 PrintLoopControl(Ops[2]);
6105 out << "\n";
6106 break;
6107 }
6108 case spv::OpImageSampleExplicitLod: {
6109 // Ops[0] = Result Type ID
6110 // Ops[1] = Sampled Image ID
6111 // Ops[2] = Coordinate ID
6112 // Ops[3] = Image Operands Type ID
6113 // Ops[4] ... Ops[n] = Operands ID
6114 PrintResID(Inst);
6115 out << " = ";
6116 PrintOpcode(Inst);
6117 for (uint32_t i = 0; i < 3; i++) {
6118 out << " ";
6119 PrintOperand(Ops[i]);
6120 }
6121 out << " ";
6122 PrintImageOperandsType(Ops[3]);
6123 for (uint32_t i = 4; i < Ops.size(); i++) {
6124 out << " ";
6125 PrintOperand(Ops[i]);
6126 }
6127 out << "\n";
6128 break;
6129 }
6130 case spv::OpVariable: {
6131 // Ops[0] : Result Type ID
6132 // Ops[1] : Storage Class
6133 // Ops[2] ... Ops[n] = Initializer IDs
6134 PrintResID(Inst);
6135 out << " = ";
6136 PrintOpcode(Inst);
6137 out << " ";
6138 PrintOperand(Ops[0]);
6139 out << " ";
6140 PrintStorageClass(Ops[1]);
6141 for (uint32_t i = 2; i < Ops.size(); i++) {
6142 out << " ";
6143 PrintOperand(Ops[i]);
6144 }
6145 out << "\n";
6146 break;
6147 }
6148 case spv::OpExtInst: {
6149 // Ops[0] = Result Type ID
6150 // Ops[1] = Set ID (OpExtInstImport ID)
6151 // Ops[2] = Instruction Number (Literal Number)
6152 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
6153 PrintResID(Inst);
6154 out << " = ";
6155 PrintOpcode(Inst);
6156 out << " ";
6157 PrintOperand(Ops[0]);
6158 out << " ";
6159 PrintOperand(Ops[1]);
6160 out << " ";
6161 PrintExtInst(Ops[2]);
6162 for (uint32_t i = 3; i < Ops.size(); i++) {
6163 out << " ";
6164 PrintOperand(Ops[i]);
6165 }
6166 out << "\n";
6167 break;
6168 }
6169 case spv::OpCopyMemory: {
6170 // Ops[0] = Addressing Model
6171 // Ops[1] = Memory Model
6172 PrintOpcode(Inst);
6173 out << " ";
6174 PrintOperand(Ops[0]);
6175 out << " ";
6176 PrintOperand(Ops[1]);
6177 out << " ";
6178 PrintMemoryAccess(Ops[2]);
6179 out << " ";
6180 PrintOperand(Ops[3]);
6181 out << "\n";
6182 break;
6183 }
6184 case spv::OpExtension:
6185 case spv::OpControlBarrier:
6186 case spv::OpMemoryBarrier:
6187 case spv::OpBranch:
6188 case spv::OpBranchConditional:
6189 case spv::OpStore:
6190 case spv::OpImageWrite:
6191 case spv::OpReturnValue:
6192 case spv::OpReturn:
6193 case spv::OpFunctionEnd: {
6194 PrintOpcode(Inst);
6195 for (uint32_t i = 0; i < Ops.size(); i++) {
6196 out << " ";
6197 PrintOperand(Ops[i]);
6198 }
6199 out << "\n";
6200 break;
6201 }
6202 case spv::OpExtInstImport:
6203 case spv::OpTypeRuntimeArray:
6204 case spv::OpTypeStruct:
6205 case spv::OpTypeSampler:
6206 case spv::OpTypeSampledImage:
6207 case spv::OpTypeInt:
6208 case spv::OpTypeFloat:
6209 case spv::OpTypeArray:
6210 case spv::OpTypeVector:
6211 case spv::OpTypeBool:
6212 case spv::OpTypeVoid:
6213 case spv::OpTypeFunction:
6214 case spv::OpFunctionParameter:
6215 case spv::OpLabel:
6216 case spv::OpPhi:
6217 case spv::OpLoad:
6218 case spv::OpSelect:
6219 case spv::OpAccessChain:
6220 case spv::OpPtrAccessChain:
6221 case spv::OpInBoundsAccessChain:
6222 case spv::OpUConvert:
6223 case spv::OpSConvert:
6224 case spv::OpConvertFToU:
6225 case spv::OpConvertFToS:
6226 case spv::OpConvertUToF:
6227 case spv::OpConvertSToF:
6228 case spv::OpFConvert:
6229 case spv::OpConvertPtrToU:
6230 case spv::OpConvertUToPtr:
6231 case spv::OpBitcast:
6232 case spv::OpIAdd:
6233 case spv::OpFAdd:
6234 case spv::OpISub:
6235 case spv::OpFSub:
6236 case spv::OpIMul:
6237 case spv::OpFMul:
6238 case spv::OpUDiv:
6239 case spv::OpSDiv:
6240 case spv::OpFDiv:
6241 case spv::OpUMod:
6242 case spv::OpSRem:
6243 case spv::OpFRem:
6244 case spv::OpBitwiseOr:
6245 case spv::OpBitwiseXor:
6246 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006247 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006248 case spv::OpShiftLeftLogical:
6249 case spv::OpShiftRightLogical:
6250 case spv::OpShiftRightArithmetic:
6251 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006252 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006253 case spv::OpCompositeExtract:
6254 case spv::OpVectorExtractDynamic:
6255 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006256 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006257 case spv::OpVectorInsertDynamic:
6258 case spv::OpVectorShuffle:
6259 case spv::OpIEqual:
6260 case spv::OpINotEqual:
6261 case spv::OpUGreaterThan:
6262 case spv::OpUGreaterThanEqual:
6263 case spv::OpULessThan:
6264 case spv::OpULessThanEqual:
6265 case spv::OpSGreaterThan:
6266 case spv::OpSGreaterThanEqual:
6267 case spv::OpSLessThan:
6268 case spv::OpSLessThanEqual:
6269 case spv::OpFOrdEqual:
6270 case spv::OpFOrdGreaterThan:
6271 case spv::OpFOrdGreaterThanEqual:
6272 case spv::OpFOrdLessThan:
6273 case spv::OpFOrdLessThanEqual:
6274 case spv::OpFOrdNotEqual:
6275 case spv::OpFUnordEqual:
6276 case spv::OpFUnordGreaterThan:
6277 case spv::OpFUnordGreaterThanEqual:
6278 case spv::OpFUnordLessThan:
6279 case spv::OpFUnordLessThanEqual:
6280 case spv::OpFUnordNotEqual:
6281 case spv::OpSampledImage:
6282 case spv::OpFunctionCall:
6283 case spv::OpConstantTrue:
6284 case spv::OpConstantFalse:
6285 case spv::OpConstant:
6286 case spv::OpSpecConstant:
6287 case spv::OpConstantComposite:
6288 case spv::OpSpecConstantComposite:
6289 case spv::OpConstantNull:
6290 case spv::OpLogicalOr:
6291 case spv::OpLogicalAnd:
6292 case spv::OpLogicalNot:
6293 case spv::OpLogicalNotEqual:
6294 case spv::OpUndef:
6295 case spv::OpIsInf:
6296 case spv::OpIsNan:
6297 case spv::OpAny:
6298 case spv::OpAll:
6299 case spv::OpAtomicIAdd:
6300 case spv::OpAtomicISub:
6301 case spv::OpAtomicExchange:
6302 case spv::OpAtomicIIncrement:
6303 case spv::OpAtomicIDecrement:
6304 case spv::OpAtomicCompareExchange:
6305 case spv::OpAtomicUMin:
6306 case spv::OpAtomicSMin:
6307 case spv::OpAtomicUMax:
6308 case spv::OpAtomicSMax:
6309 case spv::OpAtomicAnd:
6310 case spv::OpAtomicOr:
6311 case spv::OpAtomicXor:
6312 case spv::OpDot: {
6313 PrintResID(Inst);
6314 out << " = ";
6315 PrintOpcode(Inst);
6316 for (uint32_t i = 0; i < Ops.size(); i++) {
6317 out << " ";
6318 PrintOperand(Ops[i]);
6319 }
6320 out << "\n";
6321 break;
6322 }
6323 }
6324 }
6325}
6326
6327void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04006328 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04006329}
6330
6331void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
6332 WriteOneWord(Inst->getResultID());
6333}
6334
6335void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
6336 // High 16 bit : Word Count
6337 // Low 16 bit : Opcode
6338 uint32_t Word = Inst->getOpcode();
6339 Word |= Inst->getWordCount() << 16;
6340 WriteOneWord(Word);
6341}
6342
6343void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
6344 SPIRVOperandType OpTy = Op->getType();
6345 switch (OpTy) {
6346 default: {
6347 llvm_unreachable("Unsupported SPIRV Operand Type???");
6348 break;
6349 }
6350 case SPIRVOperandType::NUMBERID: {
6351 WriteOneWord(Op->getNumID());
6352 break;
6353 }
6354 case SPIRVOperandType::LITERAL_STRING: {
6355 std::string Str = Op->getLiteralStr();
6356 const char *Data = Str.c_str();
6357 size_t WordSize = Str.size() / 4;
6358 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
6359 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
6360 }
6361
6362 uint32_t Remainder = Str.size() % 4;
6363 uint32_t LastWord = 0;
6364 if (Remainder) {
6365 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
6366 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
6367 }
6368 }
6369
6370 WriteOneWord(LastWord);
6371 break;
6372 }
6373 case SPIRVOperandType::LITERAL_INTEGER:
6374 case SPIRVOperandType::LITERAL_FLOAT: {
6375 auto LiteralNum = Op->getLiteralNum();
6376 // TODO: Handle LiteranNum carefully.
6377 for (auto Word : LiteralNum) {
6378 WriteOneWord(Word);
6379 }
6380 break;
6381 }
6382 }
6383}
6384
6385void SPIRVProducerPass::WriteSPIRVBinary() {
6386 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
6387
6388 for (auto Inst : SPIRVInstList) {
6389 SPIRVOperandList Ops = Inst->getOperands();
6390 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
6391
6392 switch (Opcode) {
6393 default: {
6394 llvm_unreachable("Unsupported SPIRV instruction");
6395 break;
6396 }
6397 case spv::OpCapability:
6398 case spv::OpExtension:
6399 case spv::OpMemoryModel:
6400 case spv::OpEntryPoint:
6401 case spv::OpExecutionMode:
6402 case spv::OpSource:
6403 case spv::OpDecorate:
6404 case spv::OpMemberDecorate:
6405 case spv::OpBranch:
6406 case spv::OpBranchConditional:
6407 case spv::OpSelectionMerge:
6408 case spv::OpLoopMerge:
6409 case spv::OpStore:
6410 case spv::OpImageWrite:
6411 case spv::OpReturnValue:
6412 case spv::OpControlBarrier:
6413 case spv::OpMemoryBarrier:
6414 case spv::OpReturn:
6415 case spv::OpFunctionEnd:
6416 case spv::OpCopyMemory: {
6417 WriteWordCountAndOpcode(Inst);
6418 for (uint32_t i = 0; i < Ops.size(); i++) {
6419 WriteOperand(Ops[i]);
6420 }
6421 break;
6422 }
6423 case spv::OpTypeBool:
6424 case spv::OpTypeVoid:
6425 case spv::OpTypeSampler:
6426 case spv::OpLabel:
6427 case spv::OpExtInstImport:
6428 case spv::OpTypePointer:
6429 case spv::OpTypeRuntimeArray:
6430 case spv::OpTypeStruct:
6431 case spv::OpTypeImage:
6432 case spv::OpTypeSampledImage:
6433 case spv::OpTypeInt:
6434 case spv::OpTypeFloat:
6435 case spv::OpTypeArray:
6436 case spv::OpTypeVector:
6437 case spv::OpTypeFunction: {
6438 WriteWordCountAndOpcode(Inst);
6439 WriteResultID(Inst);
6440 for (uint32_t i = 0; i < Ops.size(); i++) {
6441 WriteOperand(Ops[i]);
6442 }
6443 break;
6444 }
6445 case spv::OpFunction:
6446 case spv::OpFunctionParameter:
6447 case spv::OpAccessChain:
6448 case spv::OpPtrAccessChain:
6449 case spv::OpInBoundsAccessChain:
6450 case spv::OpUConvert:
6451 case spv::OpSConvert:
6452 case spv::OpConvertFToU:
6453 case spv::OpConvertFToS:
6454 case spv::OpConvertUToF:
6455 case spv::OpConvertSToF:
6456 case spv::OpFConvert:
6457 case spv::OpConvertPtrToU:
6458 case spv::OpConvertUToPtr:
6459 case spv::OpBitcast:
6460 case spv::OpIAdd:
6461 case spv::OpFAdd:
6462 case spv::OpISub:
6463 case spv::OpFSub:
6464 case spv::OpIMul:
6465 case spv::OpFMul:
6466 case spv::OpUDiv:
6467 case spv::OpSDiv:
6468 case spv::OpFDiv:
6469 case spv::OpUMod:
6470 case spv::OpSRem:
6471 case spv::OpFRem:
6472 case spv::OpBitwiseOr:
6473 case spv::OpBitwiseXor:
6474 case spv::OpBitwiseAnd:
David Netoa394f392017-08-26 20:45:29 -04006475 case spv::OpNot:
David Neto22f144c2017-06-12 14:26:21 -04006476 case spv::OpShiftLeftLogical:
6477 case spv::OpShiftRightLogical:
6478 case spv::OpShiftRightArithmetic:
6479 case spv::OpBitCount:
David Netoab03f432017-11-03 17:00:44 -04006480 case spv::OpCompositeConstruct:
David Neto22f144c2017-06-12 14:26:21 -04006481 case spv::OpCompositeExtract:
6482 case spv::OpVectorExtractDynamic:
6483 case spv::OpCompositeInsert:
David Neto0a2f98d2017-09-15 19:38:40 -04006484 case spv::OpCopyObject:
David Neto22f144c2017-06-12 14:26:21 -04006485 case spv::OpVectorInsertDynamic:
6486 case spv::OpVectorShuffle:
6487 case spv::OpIEqual:
6488 case spv::OpINotEqual:
6489 case spv::OpUGreaterThan:
6490 case spv::OpUGreaterThanEqual:
6491 case spv::OpULessThan:
6492 case spv::OpULessThanEqual:
6493 case spv::OpSGreaterThan:
6494 case spv::OpSGreaterThanEqual:
6495 case spv::OpSLessThan:
6496 case spv::OpSLessThanEqual:
6497 case spv::OpFOrdEqual:
6498 case spv::OpFOrdGreaterThan:
6499 case spv::OpFOrdGreaterThanEqual:
6500 case spv::OpFOrdLessThan:
6501 case spv::OpFOrdLessThanEqual:
6502 case spv::OpFOrdNotEqual:
6503 case spv::OpFUnordEqual:
6504 case spv::OpFUnordGreaterThan:
6505 case spv::OpFUnordGreaterThanEqual:
6506 case spv::OpFUnordLessThan:
6507 case spv::OpFUnordLessThanEqual:
6508 case spv::OpFUnordNotEqual:
6509 case spv::OpExtInst:
6510 case spv::OpIsInf:
6511 case spv::OpIsNan:
6512 case spv::OpAny:
6513 case spv::OpAll:
6514 case spv::OpUndef:
6515 case spv::OpConstantNull:
6516 case spv::OpLogicalOr:
6517 case spv::OpLogicalAnd:
6518 case spv::OpLogicalNot:
6519 case spv::OpLogicalNotEqual:
6520 case spv::OpConstantComposite:
6521 case spv::OpSpecConstantComposite:
6522 case spv::OpConstantTrue:
6523 case spv::OpConstantFalse:
6524 case spv::OpConstant:
6525 case spv::OpSpecConstant:
6526 case spv::OpVariable:
6527 case spv::OpFunctionCall:
6528 case spv::OpSampledImage:
6529 case spv::OpImageSampleExplicitLod:
6530 case spv::OpSelect:
6531 case spv::OpPhi:
6532 case spv::OpLoad:
6533 case spv::OpAtomicIAdd:
6534 case spv::OpAtomicISub:
6535 case spv::OpAtomicExchange:
6536 case spv::OpAtomicIIncrement:
6537 case spv::OpAtomicIDecrement:
6538 case spv::OpAtomicCompareExchange:
6539 case spv::OpAtomicUMin:
6540 case spv::OpAtomicSMin:
6541 case spv::OpAtomicUMax:
6542 case spv::OpAtomicSMax:
6543 case spv::OpAtomicAnd:
6544 case spv::OpAtomicOr:
6545 case spv::OpAtomicXor:
6546 case spv::OpDot: {
6547 WriteWordCountAndOpcode(Inst);
6548 WriteOperand(Ops[0]);
6549 WriteResultID(Inst);
6550 for (uint32_t i = 1; i < Ops.size(); i++) {
6551 WriteOperand(Ops[i]);
6552 }
6553 break;
6554 }
6555 }
6556 }
6557}