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