blob: 3d4652e61be791f0c2cf2c6f9382d59696286876 [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.
David Neto391aeb12017-08-26 15:51:58 -04001645 // No matter what LLVM type is requested first, always alias the
1646 // second one's SPIR-V type to be the same as the one we generated
1647 // first.
1648 int aliasToWidth = 0;
David Neto22f144c2017-06-12 14:26:21 -04001649 if (BitWidth == 8) {
David Neto391aeb12017-08-26 15:51:58 -04001650 aliasToWidth = 32;
David Neto22f144c2017-06-12 14:26:21 -04001651 BitWidth = 32;
David Neto391aeb12017-08-26 15:51:58 -04001652 } else if (BitWidth == 32) {
1653 aliasToWidth = 8;
1654 }
1655 if (aliasToWidth) {
1656 Type* otherType = Type::getIntNTy(Ty->getContext(), aliasToWidth);
1657 auto where = TypeMap.find(otherType);
1658 if (where == TypeMap.end()) {
1659 // Go ahead and make it, but also map the other type to it.
1660 TypeMap[otherType] = nextID;
1661 } else {
1662 // Alias this SPIR-V type the existing type.
1663 TypeMap[Ty] = where->second;
1664 break;
1665 }
David Neto22f144c2017-06-12 14:26:21 -04001666 }
1667
1668 SPIRVOperand *Ops[2] = {
1669 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, BitWidth),
1670 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, 0u)};
1671
1672 SPIRVInstList.push_back(
1673 new SPIRVInstruction(4, spv::OpTypeInt, nextID++, Ops));
1674 }
1675 break;
1676 }
1677 case Type::HalfTyID:
1678 case Type::FloatTyID:
1679 case Type::DoubleTyID: {
1680 SPIRVOperand *WidthOp = new SPIRVOperand(
1681 SPIRVOperandType::LITERAL_INTEGER, Ty->getPrimitiveSizeInBits());
1682
1683 SPIRVInstList.push_back(
1684 new SPIRVInstruction(3, spv::OpTypeFloat, nextID++, WidthOp));
1685 break;
1686 }
1687 case Type::ArrayTyID: {
1688 LLVMContext &Context = Ty->getContext();
1689 ArrayType *ArrTy = cast<ArrayType>(Ty);
1690 //
1691 // Generate OpConstant and OpTypeArray.
1692 //
1693
1694 //
1695 // Generate OpConstant for array length.
1696 //
1697 // Ops[0] = Result Type ID
1698 // Ops[1] .. Ops[n] = Values LiteralNumber
1699 SPIRVOperandList Ops;
1700
1701 Type *LengthTy = Type::getInt32Ty(Context);
1702 uint32_t ResTyID = lookupType(LengthTy);
1703 SPIRVOperand *ResTyOp =
1704 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
1705 Ops.push_back(ResTyOp);
1706
1707 uint64_t Length = ArrTy->getArrayNumElements();
1708 assert(Length < UINT32_MAX);
1709 std::vector<uint32_t> LiteralNum;
1710 LiteralNum.push_back(static_cast<uint32_t>(Length));
1711 SPIRVOperand *ValOp =
1712 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1713 Ops.push_back(ValOp);
1714
1715 // Add constant for length to constant list.
1716 Constant *CstLength = ConstantInt::get(LengthTy, Length);
1717 AllocatedVMap[CstLength] = nextID;
1718 VMap[CstLength] = nextID;
1719 uint32_t LengthID = nextID;
1720
1721 SPIRVInstruction *CstInst =
1722 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
1723 SPIRVInstList.push_back(CstInst);
1724
1725 //
1726 // Generate OpTypeArray.
1727 //
1728 // Ops[0] = Element Type ID
1729 // Ops[1] = Array Length Constant ID
1730 Ops.clear();
1731
1732 uint32_t EleTyID = lookupType(ArrTy->getElementType());
1733 SPIRVOperand *EleTyOp =
1734 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleTyID);
1735 Ops.push_back(EleTyOp);
1736
1737 SPIRVOperand *LengthOp =
1738 new SPIRVOperand(SPIRVOperandType::NUMBERID, LengthID);
1739 Ops.push_back(LengthOp);
1740
1741 // Update TypeMap with nextID.
1742 TypeMap[Ty] = nextID;
1743
1744 SPIRVInstruction *ArrayInst =
1745 new SPIRVInstruction(4, spv::OpTypeArray, nextID++, Ops);
1746 SPIRVInstList.push_back(ArrayInst);
1747 break;
1748 }
1749 case Type::VectorTyID: {
1750 // <4 x i8> is changed to i32.
1751 LLVMContext &Context = Ty->getContext();
1752 if (Ty->getVectorElementType() == Type::getInt8Ty(Context)) {
1753 if (Ty->getVectorNumElements() == 4) {
1754 TypeMap[Ty] = lookupType(Ty->getVectorElementType());
1755 break;
1756 } else {
1757 Ty->print(errs());
1758 llvm_unreachable("Support above i8 vector type");
1759 }
1760 }
1761
1762 // Ops[0] = Component Type ID
1763 // Ops[1] = Component Count (Literal Number)
1764 SPIRVOperand *Ops[2] = {
1765 new SPIRVOperand(SPIRVOperandType::NUMBERID,
1766 lookupType(Ty->getVectorElementType())),
1767 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
1768 Ty->getVectorNumElements())};
1769
1770 SPIRVInstList.push_back(
1771 new SPIRVInstruction(4, spv::OpTypeVector, nextID++, Ops));
1772 break;
1773 }
1774 case Type::VoidTyID: {
1775 SPIRVInstruction *Inst =
1776 new SPIRVInstruction(2, spv::OpTypeVoid, nextID++, {});
1777 SPIRVInstList.push_back(Inst);
1778 break;
1779 }
1780 case Type::FunctionTyID: {
1781 // Generate SPIRV instruction for function type.
1782 FunctionType *FTy = cast<FunctionType>(Ty);
1783
1784 // Ops[0] = Return Type ID
1785 // Ops[1] ... Ops[n] = Parameter Type IDs
1786 SPIRVOperandList Ops;
1787
1788 // Find SPIRV instruction for return type
1789 uint32_t RetTyID = lookupType(FTy->getReturnType());
1790
1791 SPIRVOperand *RetTyOp =
1792 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
1793 Ops.push_back(RetTyOp);
1794
1795 // Find SPIRV instructions for parameter types
1796 for (unsigned k = 0; k < FTy->getNumParams(); k++) {
1797 // Find SPIRV instruction for parameter type.
1798 auto ParamTy = FTy->getParamType(k);
1799 if (ParamTy->isPointerTy()) {
1800 auto PointeeTy = ParamTy->getPointerElementType();
1801 if (PointeeTy->isStructTy() &&
1802 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
1803 ParamTy = PointeeTy;
1804 }
1805 }
1806
1807 uint32_t ParamTyID = lookupType(ParamTy);
1808 SPIRVOperand *ParamTyOp =
1809 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
1810 Ops.push_back(ParamTyOp);
1811 }
1812
1813 // Return type id is included in operand list.
1814 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
1815
1816 SPIRVInstruction *Inst =
1817 new SPIRVInstruction(WordCount, spv::OpTypeFunction, nextID++, Ops);
1818 SPIRVInstList.push_back(Inst);
1819 break;
1820 }
1821 }
1822 }
1823
1824 // Generate OpTypeSampledImage.
1825 TypeMapType &OpImageTypeMap = getImageTypeMap();
1826 for (auto &ImageType : OpImageTypeMap) {
1827 //
1828 // Generate OpTypeSampledImage.
1829 //
1830 // Ops[0] = Image Type ID
1831 //
1832 SPIRVOperandList Ops;
1833
1834 Type *ImgTy = ImageType.first;
1835 uint32_t ImgTyID = TypeMap[ImgTy];
1836 SPIRVOperand *ImgTyOp =
1837 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImgTyID);
1838 Ops.push_back(ImgTyOp);
1839
1840 // Update OpImageTypeMap.
1841 ImageType.second = nextID;
1842
1843 SPIRVInstruction *Inst =
1844 new SPIRVInstruction(3, spv::OpTypeSampledImage, nextID++, Ops);
1845 SPIRVInstList.push_back(Inst);
1846 }
1847}
1848
1849void SPIRVProducerPass::GenerateSPIRVConstants() {
1850 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
1851 ValueMapType &VMap = getValueMap();
1852 ValueMapType &AllocatedVMap = getAllocatedValueMap();
1853 ValueList &CstList = getConstantList();
1854
1855 for (uint32_t i = 0; i < CstList.size(); i++) {
David Netofb9a7972017-08-25 17:08:24 -04001856 // UniqueVector ids are 1-based.
1857 Constant *Cst = cast<Constant>(CstList[i+1]);
David Neto22f144c2017-06-12 14:26:21 -04001858
1859 // OpTypeArray's constant was already generated.
David Netofb9a7972017-08-25 17:08:24 -04001860 if (AllocatedVMap.find_as(Cst) != AllocatedVMap.end()) {
David Neto22f144c2017-06-12 14:26:21 -04001861 continue;
1862 }
1863
David Netofb9a7972017-08-25 17:08:24 -04001864 // Set ValueMap with nextID for reference later.
David Neto22f144c2017-06-12 14:26:21 -04001865 VMap[Cst] = nextID;
1866
1867 //
1868 // Generate OpConstant.
1869 //
1870
1871 // Ops[0] = Result Type ID
1872 // Ops[1] .. Ops[n] = Values LiteralNumber
1873 SPIRVOperandList Ops;
1874
1875 uint32_t ResTyID = lookupType(Cst->getType());
1876 SPIRVOperand *ResTyIDOp =
1877 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
1878 Ops.push_back(ResTyIDOp);
1879
1880 std::vector<uint32_t> LiteralNum;
1881 uint16_t WordCount = 0;
1882 spv::Op Opcode = spv::OpNop;
1883
1884 if (isa<UndefValue>(Cst)) {
1885 // Ops[0] = Result Type ID
1886 Opcode = spv::OpUndef;
1887 WordCount = 3;
1888 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(Cst)) {
1889 unsigned BitWidth = CI->getBitWidth();
1890 if (BitWidth == 1) {
1891 // If the bitwidth of constant is 1, generate OpConstantTrue or
1892 // OpConstantFalse.
1893 if (CI->getZExtValue()) {
1894 // Ops[0] = Result Type ID
1895 Opcode = spv::OpConstantTrue;
1896 } else {
1897 // Ops[0] = Result Type ID
1898 Opcode = spv::OpConstantFalse;
1899 }
1900 WordCount = 3;
1901 } else {
1902 auto V = CI->getZExtValue();
1903 LiteralNum.push_back(V & 0xFFFFFFFF);
1904
1905 if (BitWidth > 32) {
1906 LiteralNum.push_back(V >> 32);
1907 }
1908
1909 Opcode = spv::OpConstant;
1910 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
1911
1912 SPIRVOperand *CstValue =
1913 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1914 Ops.push_back(CstValue);
1915 }
1916 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Cst)) {
1917 uint64_t FPVal = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1918 Type *CFPTy = CFP->getType();
1919 if (CFPTy->isFloatTy()) {
1920 LiteralNum.push_back(FPVal & 0xFFFFFFFF);
1921 } else {
1922 CFPTy->print(errs());
1923 llvm_unreachable("Implement this ConstantFP Type");
1924 }
1925
1926 Opcode = spv::OpConstant;
1927 WordCount = static_cast<uint16_t>(3 + LiteralNum.size());
1928
1929 SPIRVOperand *CstValue =
1930 new SPIRVOperand(SPIRVOperandType::LITERAL_FLOAT, LiteralNum);
1931 Ops.push_back(CstValue);
1932 } else if (isa<ConstantDataSequential>(Cst) &&
1933 cast<ConstantDataSequential>(Cst)->isString()) {
1934 Cst->print(errs());
1935 llvm_unreachable("Implement this Constant");
1936
1937 } else if (const ConstantDataSequential *CDS =
1938 dyn_cast<ConstantDataSequential>(Cst)) {
1939 for (unsigned k = 0; k < CDS->getNumElements(); k++) {
1940 Constant *EleCst = CDS->getElementAsConstant(k);
1941 uint32_t EleCstID = VMap[EleCst];
1942 SPIRVOperand *EleCstIDOp =
1943 new SPIRVOperand(SPIRVOperandType::NUMBERID, EleCstID);
1944 Ops.push_back(EleCstIDOp);
1945 }
1946
1947 Opcode = spv::OpConstantComposite;
1948 WordCount = static_cast<uint16_t>(3 + CDS->getNumElements());
1949 } else if (const ConstantAggregate *CA = dyn_cast<ConstantAggregate>(Cst)) {
1950 // Let's convert <4 x i8> constant to int constant specially.
1951 Type *CstTy = Cst->getType();
1952 if (is4xi8vec(CstTy)) {
1953 LLVMContext &Context = CstTy->getContext();
1954
1955 //
1956 // Generate OpConstant with OpTypeInt 32 0.
1957 //
1958 uint64_t IntValue = 0;
1959 uint32_t Idx = 0;
1960 for (User::const_op_iterator I = Cst->op_begin(), E = Cst->op_end();
1961 I != E; ++I) {
1962 uint64_t Val = 0;
1963 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(I)) {
1964 Val = CI2->getZExtValue();
1965 }
1966 IntValue = (IntValue << Idx) | Val;
1967 }
1968
1969 ConstantInt *CstInt =
1970 ConstantInt::get(Type::getInt32Ty(Context), IntValue);
1971 // If this constant is already registered on VMap, use it.
1972 if (VMap.count(CstInt)) {
1973 uint32_t CstID = VMap[CstInt];
1974 VMap[Cst] = CstID;
David Neto19a1bad2017-08-25 15:01:41 -04001975 continue;
David Neto22f144c2017-06-12 14:26:21 -04001976 }
1977
1978 LiteralNum.push_back(IntValue & 0xFFFFFFFF);
1979 SPIRVOperand *CstValue =
1980 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
1981 Ops.push_back(CstValue);
1982
1983 SPIRVInstruction *CstInst =
1984 new SPIRVInstruction(4, spv::OpConstant, nextID++, Ops);
1985 SPIRVInstList.push_back(CstInst);
1986
David Neto19a1bad2017-08-25 15:01:41 -04001987 continue;
David Neto22f144c2017-06-12 14:26:21 -04001988 }
1989
David Neto19a1bad2017-08-25 15:01:41 -04001990 // This is a normal constant aggregate.
1991
David Neto22f144c2017-06-12 14:26:21 -04001992 // We use a constant composite in SPIR-V for our constant aggregate in
1993 // LLVM.
1994 Opcode = spv::OpConstantComposite;
1995 WordCount = static_cast<uint16_t>(3 + CA->getNumOperands());
1996
1997 for (unsigned k = 0; k < CA->getNumOperands(); k++) {
1998 // Look up the ID of the element of this aggregate (which we will
1999 // previously have created a constant for).
2000 uint32_t ElementConstantID = VMap[CA->getAggregateElement(k)];
2001
2002 // And add an operand to the composite we are constructing
2003 Ops.push_back(
2004 new SPIRVOperand(SPIRVOperandType::NUMBERID, ElementConstantID));
2005 }
2006 } else if (Cst->isNullValue()) {
2007 Opcode = spv::OpConstantNull;
2008 WordCount = 3;
2009 } else {
2010 Cst->print(errs());
2011 llvm_unreachable("Unsupported Constant???");
2012 }
2013
2014 SPIRVInstruction *CstInst =
2015 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
2016 SPIRVInstList.push_back(CstInst);
2017 }
2018}
2019
2020void SPIRVProducerPass::GenerateSamplers(Module &M) {
2021 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2022 ValueMapType &VMap = getValueMap();
2023
2024 DenseMap<unsigned, unsigned> SamplerLiteralToIDMap;
2025
2026 unsigned BindingIdx = 0;
2027
2028 // Generate the sampler map.
2029 for (auto SamplerLiteral : getSamplerMap()) {
2030 // Generate OpVariable.
2031 //
2032 // GIDOps[0] : Result Type ID
2033 // GIDOps[1] : Storage Class
2034 SPIRVOperandList Ops;
2035
2036 Ops.push_back(
2037 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(SamplerTy)));
2038
2039 spv::StorageClass StorageClass = spv::StorageClassUniformConstant;
2040 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2041
2042 SPIRVInstruction *Inst = new SPIRVInstruction(
2043 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID, Ops);
2044 SPIRVInstList.push_back(Inst);
2045
David Neto44795152017-07-13 15:45:28 -04002046 SamplerLiteralToIDMap[SamplerLiteral.first] = nextID++;
David Neto22f144c2017-06-12 14:26:21 -04002047
2048 // Find Insert Point for OpDecorate.
2049 auto DecoInsertPoint =
2050 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2051 [](SPIRVInstruction *Inst) -> bool {
2052 return Inst->getOpcode() != spv::OpDecorate &&
2053 Inst->getOpcode() != spv::OpMemberDecorate &&
2054 Inst->getOpcode() != spv::OpExtInstImport;
2055 });
2056
2057 // Ops[0] = Target ID
2058 // Ops[1] = Decoration (DescriptorSet)
2059 // Ops[2] = LiteralNumber according to Decoration
2060 Ops.clear();
2061
David Neto44795152017-07-13 15:45:28 -04002062 SPIRVOperand *ArgIDOp =
2063 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2064 SamplerLiteralToIDMap[SamplerLiteral.first]);
David Neto22f144c2017-06-12 14:26:21 -04002065 Ops.push_back(ArgIDOp);
2066
2067 spv::Decoration Deco = spv::DecorationDescriptorSet;
2068 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2069 Ops.push_back(DecoOp);
2070
David Neto44795152017-07-13 15:45:28 -04002071 descriptorMapOut << "sampler," << SamplerLiteral.first << ",samplerExpr,\""
2072 << SamplerLiteral.second << "\",descriptorSet,0,binding,"
David Netoc2c368d2017-06-30 16:50:17 -04002073 << BindingIdx << "\n";
2074
David Neto22f144c2017-06-12 14:26:21 -04002075 std::vector<uint32_t> LiteralNum;
2076 LiteralNum.push_back(0);
2077 SPIRVOperand *DescSet =
2078 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2079 Ops.push_back(DescSet);
2080
2081 SPIRVInstruction *DescDecoInst =
2082 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2083 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2084
2085 // Ops[0] = Target ID
2086 // Ops[1] = Decoration (Binding)
2087 // Ops[2] = LiteralNumber according to Decoration
2088 Ops.clear();
2089
2090 Ops.push_back(ArgIDOp);
2091
2092 Deco = spv::DecorationBinding;
2093 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2094 Ops.push_back(DecoOp);
2095
2096 LiteralNum.clear();
2097 LiteralNum.push_back(BindingIdx++);
2098 SPIRVOperand *Binding =
2099 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2100 Ops.push_back(Binding);
2101
2102 SPIRVInstruction *BindDecoInst =
2103 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2104 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2105 }
2106
2107 const char *TranslateSamplerFunctionName = "__translate_sampler_initializer";
2108
2109 auto SamplerFunction = M.getFunction(TranslateSamplerFunctionName);
2110
2111 // If there are no uses of the sampler function, no work to do!
2112 if (!SamplerFunction) {
2113 return;
2114 }
2115
2116 // Iterate through the users of the sampler function.
2117 for (auto User : SamplerFunction->users()) {
2118 if (auto CI = dyn_cast<CallInst>(User)) {
2119 // Get the literal used to initialize the sampler.
2120 auto Constant = dyn_cast<ConstantInt>(CI->getArgOperand(0));
2121
2122 if (!Constant) {
2123 CI->getArgOperand(0)->print(errs());
2124 llvm_unreachable("Argument of sampler initializer was non-constant!");
2125 }
2126
2127 auto SamplerLiteral = static_cast<unsigned>(Constant->getZExtValue());
2128
2129 if (0 == SamplerLiteralToIDMap.count(SamplerLiteral)) {
2130 Constant->print(errs());
2131 llvm_unreachable("Sampler literal was not found in sampler map!");
2132 }
2133
2134 // Calls to the sampler literal function to initialize a sampler are
2135 // re-routed to the global variables declared for the sampler.
2136 VMap[CI] = SamplerLiteralToIDMap[SamplerLiteral];
2137 }
2138 }
2139}
2140
2141void SPIRVProducerPass::GenerateGlobalVar(GlobalVariable &GV) {
2142 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2143 ValueMapType &VMap = getValueMap();
2144 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2145
2146 const spv::BuiltIn BuiltinType = GetBuiltin(GV.getName());
2147 Type *Ty = GV.getType();
2148 PointerType *PTy = cast<PointerType>(Ty);
2149
2150 uint32_t InitializerID = 0;
2151
2152 // Workgroup size is handled differently (it goes into a constant)
2153 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2154 std::vector<bool> HasMDVec;
2155 uint32_t PrevXDimCst = 0xFFFFFFFF;
2156 uint32_t PrevYDimCst = 0xFFFFFFFF;
2157 uint32_t PrevZDimCst = 0xFFFFFFFF;
2158 for (Function &Func : *GV.getParent()) {
2159 if (Func.isDeclaration()) {
2160 continue;
2161 }
2162
2163 // We only need to check kernels.
2164 if (Func.getCallingConv() != CallingConv::SPIR_KERNEL) {
2165 continue;
2166 }
2167
2168 if (const MDNode *MD =
2169 dyn_cast<Function>(&Func)->getMetadata("reqd_work_group_size")) {
2170 uint32_t CurXDimCst = static_cast<uint32_t>(
2171 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2172 uint32_t CurYDimCst = static_cast<uint32_t>(
2173 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2174 uint32_t CurZDimCst = static_cast<uint32_t>(
2175 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2176
2177 if (PrevXDimCst == 0xFFFFFFFF && PrevYDimCst == 0xFFFFFFFF &&
2178 PrevZDimCst == 0xFFFFFFFF) {
2179 PrevXDimCst = CurXDimCst;
2180 PrevYDimCst = CurYDimCst;
2181 PrevZDimCst = CurZDimCst;
2182 } else if (CurXDimCst != PrevXDimCst || CurYDimCst != PrevYDimCst ||
2183 CurZDimCst != PrevZDimCst) {
2184 llvm_unreachable(
2185 "reqd_work_group_size must be the same across all kernels");
2186 } else {
2187 continue;
2188 }
2189
2190 //
2191 // Generate OpConstantComposite.
2192 //
2193 // Ops[0] : Result Type ID
2194 // Ops[1] : Constant size for x dimension.
2195 // Ops[2] : Constant size for y dimension.
2196 // Ops[3] : Constant size for z dimension.
2197 SPIRVOperandList Ops;
2198
2199 uint32_t XDimCstID =
2200 VMap[mdconst::extract<ConstantInt>(MD->getOperand(0))];
2201 uint32_t YDimCstID =
2202 VMap[mdconst::extract<ConstantInt>(MD->getOperand(1))];
2203 uint32_t ZDimCstID =
2204 VMap[mdconst::extract<ConstantInt>(MD->getOperand(2))];
2205
2206 InitializerID = nextID;
2207
2208 Ops.push_back(
2209 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2210 lookupType(Ty->getPointerElementType())));
2211
2212 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2213 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2214 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2215
2216 SPIRVInstruction *Inst =
2217 new SPIRVInstruction(6, spv::OpConstantComposite, nextID++, Ops);
2218 SPIRVInstList.push_back(Inst);
2219
2220 HasMDVec.push_back(true);
2221 } else {
2222 HasMDVec.push_back(false);
2223 }
2224 }
2225
2226 // Check all kernels have same definitions for work_group_size.
2227 bool HasMD = false;
2228 if (!HasMDVec.empty()) {
2229 HasMD = HasMDVec[0];
2230 for (uint32_t i = 1; i < HasMDVec.size(); i++) {
2231 if (HasMD != HasMDVec[i]) {
2232 llvm_unreachable(
2233 "Kernels should have consistent work group size definition");
2234 }
2235 }
2236 }
2237
2238 // If all kernels do not have metadata for reqd_work_group_size, generate
2239 // OpSpecConstants for x/y/z dimension.
2240 if (!HasMD) {
2241 //
2242 // Generate OpSpecConstants for x/y/z dimension.
2243 //
2244 // Ops[0] : Result Type ID
2245 // Ops[1] : Constant size for x/y/z dimension (Literal Number).
2246 uint32_t XDimCstID = 0;
2247 uint32_t YDimCstID = 0;
2248 uint32_t ZDimCstID = 0;
2249
2250 // X Dimension
2251 SPIRVOperandList Ops;
2252
2253 Ops.push_back(new SPIRVOperand(
2254 SPIRVOperandType::NUMBERID,
2255 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2256
2257 std::vector<uint32_t> LiteralNum;
2258 LiteralNum.push_back(1);
2259 SPIRVOperand *XDim =
2260 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2261 Ops.push_back(XDim);
2262
2263 XDimCstID = nextID;
2264 BuiltinDimVec.push_back(XDimCstID);
2265
2266 SPIRVInstruction *XDimCstInst =
2267 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2268 SPIRVInstList.push_back(XDimCstInst);
2269
2270 // Y Dimension
2271 Ops.clear();
2272
2273 Ops.push_back(new SPIRVOperand(
2274 SPIRVOperandType::NUMBERID,
2275 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2276
2277 LiteralNum.clear();
2278 LiteralNum.push_back(1);
2279 SPIRVOperand *YDim =
2280 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2281 Ops.push_back(YDim);
2282
2283 YDimCstID = nextID;
2284 BuiltinDimVec.push_back(YDimCstID);
2285
2286 SPIRVInstruction *YDimCstInst =
2287 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2288 SPIRVInstList.push_back(YDimCstInst);
2289
2290 // Z Dimension
2291 Ops.clear();
2292
2293 Ops.push_back(new SPIRVOperand(
2294 SPIRVOperandType::NUMBERID,
2295 lookupType(Ty->getPointerElementType()->getSequentialElementType())));
2296
2297 LiteralNum.clear();
2298 LiteralNum.push_back(1);
2299 SPIRVOperand *ZDim =
2300 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2301 Ops.push_back(ZDim);
2302
2303 ZDimCstID = nextID;
2304 BuiltinDimVec.push_back(ZDimCstID);
2305
2306 SPIRVInstruction *ZDimCstInst =
2307 new SPIRVInstruction(4, spv::OpSpecConstant, nextID++, Ops);
2308 SPIRVInstList.push_back(ZDimCstInst);
2309
2310 //
2311 // Generate OpSpecConstantComposite.
2312 //
2313 // Ops[0] : Result Type ID
2314 // Ops[1] : Constant size for x dimension.
2315 // Ops[2] : Constant size for y dimension.
2316 // Ops[3] : Constant size for z dimension.
2317 InitializerID = nextID;
2318
2319 Ops.clear();
2320
2321 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
2322 lookupType(Ty->getPointerElementType())));
2323
2324 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XDimCstID));
2325 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, YDimCstID));
2326 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ZDimCstID));
2327
2328 SPIRVInstruction *Inst =
2329 new SPIRVInstruction(6, spv::OpSpecConstantComposite, nextID++, Ops);
2330 SPIRVInstList.push_back(Inst);
2331 }
2332 }
2333
2334 if (GV.hasInitializer()) {
2335 InitializerID = VMap[GV.getInitializer()];
2336 }
2337
2338 VMap[&GV] = nextID;
2339
2340 //
2341 // Generate OpVariable.
2342 //
2343 // GIDOps[0] : Result Type ID
2344 // GIDOps[1] : Storage Class
2345 SPIRVOperandList Ops;
2346
2347 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(Ty)));
2348
2349 spv::StorageClass StorageClass = GetStorageClass(PTy->getAddressSpace());
2350 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass));
2351
2352 if (0 != InitializerID) {
2353 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, InitializerID));
2354 }
2355
2356 SPIRVInstruction *Inst = new SPIRVInstruction(
2357 static_cast<uint16_t>(2 + Ops.size()), spv::OpVariable, nextID++, Ops);
2358 SPIRVInstList.push_back(Inst);
2359
2360 // If we have a builtin.
2361 if (spv::BuiltInMax != BuiltinType) {
2362 // Find Insert Point for OpDecorate.
2363 auto DecoInsertPoint =
2364 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2365 [](SPIRVInstruction *Inst) -> bool {
2366 return Inst->getOpcode() != spv::OpDecorate &&
2367 Inst->getOpcode() != spv::OpMemberDecorate &&
2368 Inst->getOpcode() != spv::OpExtInstImport;
2369 });
2370 //
2371 // Generate OpDecorate.
2372 //
2373 // DOps[0] = Target ID
2374 // DOps[1] = Decoration (Builtin)
2375 // DOps[2] = BuiltIn ID
2376 uint32_t ResultID;
2377
2378 // WorkgroupSize is different, we decorate the constant composite that has
2379 // its value, rather than the variable that we use to access the value.
2380 if (spv::BuiltInWorkgroupSize == BuiltinType) {
2381 ResultID = InitializerID;
2382 } else {
2383 ResultID = VMap[&GV];
2384 }
2385
2386 SPIRVOperandList DOps;
2387 SPIRVOperand *ResultIDOp =
2388 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResultID);
2389 DOps.push_back(ResultIDOp);
2390
2391 spv::Decoration Deco = spv::DecorationBuiltIn;
2392 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2393 DOps.push_back(DecoOp);
2394
2395 SPIRVOperand *Builtin =
2396 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinType);
2397 DOps.push_back(Builtin);
2398
2399 SPIRVInstruction *DescDecoInst =
2400 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, DOps);
2401 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2402 }
2403}
2404
2405void SPIRVProducerPass::GenerateFuncPrologue(Function &F) {
2406 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2407 ValueMapType &VMap = getValueMap();
2408 EntryPointVecType &EntryPoints = getEntryPointVec();
2409 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
2410 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
2411 auto &GlobalConstFuncTyMap = getGlobalConstFuncTypeMap();
2412 auto &GlobalConstArgSet = getGlobalConstArgSet();
David Netoc2c368d2017-06-30 16:50:17 -04002413 const DataLayout& dataLayout(F.getParent()->getDataLayout());
David Neto22f144c2017-06-12 14:26:21 -04002414
2415 FunctionType *FTy = F.getFunctionType();
2416
2417 //
2418 // Generate OpVariable and OpDecorate for kernel function with arguments.
2419 //
2420 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2421
2422 // Find Insert Point for OpDecorate.
2423 auto DecoInsertPoint =
2424 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
2425 [](SPIRVInstruction *Inst) -> bool {
2426 return Inst->getOpcode() != spv::OpDecorate &&
2427 Inst->getOpcode() != spv::OpMemberDecorate &&
2428 Inst->getOpcode() != spv::OpExtInstImport;
2429 });
2430
2431 uint32_t DescriptorSetIdx = (0 < getSamplerMap().size()) ? 1u : 0u;
2432 for (Function &Func : *F.getParent()) {
2433 if (Func.isDeclaration()) {
2434 continue;
2435 }
2436
2437 if (Func.getCallingConv() == CallingConv::SPIR_KERNEL) {
2438 if (&Func == &F) {
2439 break;
2440 }
2441 DescriptorSetIdx++;
2442 }
2443 }
2444
David Neto156783e2017-07-05 15:39:41 -04002445 const auto *ArgMap = F.getMetadata("kernel_arg_map");
2446 // Emit descriptor map entries, if there was explicit metadata
2447 // attached.
2448 if (ArgMap) {
2449 for (const auto &arg : ArgMap->operands()) {
2450 const MDNode *arg_node = dyn_cast<MDNode>(arg.get());
2451 assert(arg_node->getNumOperands() == 4);
2452 const auto name =
2453 dyn_cast<MDString>(arg_node->getOperand(0))->getString();
2454 const auto old_index =
2455 dyn_extract<ConstantInt>(arg_node->getOperand(1))->getZExtValue();
2456 const auto new_index =
2457 dyn_extract<ConstantInt>(arg_node->getOperand(2))->getZExtValue();
2458 const auto offset =
2459 dyn_extract<ConstantInt>(arg_node->getOperand(3))->getZExtValue();
2460 descriptorMapOut << "kernel," << F.getName() << ",arg," << name
2461 << ",argOrdinal," << old_index << ",descriptorSet,"
2462 << DescriptorSetIdx << ",binding," << new_index
2463 << ",offset," << offset << "\n";
2464 }
2465 }
2466
David Neto22f144c2017-06-12 14:26:21 -04002467 uint32_t BindingIdx = 0;
2468 for (auto &Arg : F.args()) {
2469 Value *NewGV = ArgGVMap[&Arg];
2470 VMap[&Arg] = VMap[NewGV];
2471 ArgGVIDMap[&Arg] = VMap[&Arg];
2472
David Neto156783e2017-07-05 15:39:41 -04002473 // Emit a descriptor map entry for this arg, in case there was no explicit
2474 // kernel arg mapping metadata.
2475 if (!ArgMap) {
2476 descriptorMapOut << "kernel," << F.getName() << ",arg," << Arg.getName()
2477 << ",argOrdinal," << BindingIdx << ",descriptorSet,"
2478 << DescriptorSetIdx << ",binding," << BindingIdx
2479 << ",offset,0\n";
David Netoc2c368d2017-06-30 16:50:17 -04002480 }
2481
David Neto22f144c2017-06-12 14:26:21 -04002482 // Ops[0] = Target ID
2483 // Ops[1] = Decoration (DescriptorSet)
2484 // Ops[2] = LiteralNumber according to Decoration
2485 SPIRVOperandList Ops;
2486
2487 SPIRVOperand *ArgIDOp =
2488 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2489 Ops.push_back(ArgIDOp);
2490
2491 spv::Decoration Deco = spv::DecorationDescriptorSet;
2492 SPIRVOperand *DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2493 Ops.push_back(DecoOp);
2494
2495 std::vector<uint32_t> LiteralNum;
2496 LiteralNum.push_back(DescriptorSetIdx);
2497 SPIRVOperand *DescSet =
2498 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2499 Ops.push_back(DescSet);
2500
2501 SPIRVInstruction *DescDecoInst =
2502 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2503 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2504
2505 // Ops[0] = Target ID
2506 // Ops[1] = Decoration (Binding)
2507 // Ops[2] = LiteralNumber according to Decoration
2508 Ops.clear();
2509
2510 Ops.push_back(ArgIDOp);
2511
2512 Deco = spv::DecorationBinding;
2513 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2514 Ops.push_back(DecoOp);
2515
2516 LiteralNum.clear();
2517 LiteralNum.push_back(BindingIdx++);
2518 SPIRVOperand *Binding =
2519 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2520 Ops.push_back(Binding);
2521
2522 SPIRVInstruction *BindDecoInst =
2523 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2524 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2525
2526 // Handle image type argument.
2527 bool HasReadOnlyImageType = false;
2528 bool HasWriteOnlyImageType = false;
2529 if (PointerType *ArgPTy = dyn_cast<PointerType>(Arg.getType())) {
2530 if (StructType *STy = dyn_cast<StructType>(ArgPTy->getElementType())) {
2531 if (STy->isOpaque()) {
2532 if (STy->getName().equals("opencl.image2d_ro_t") ||
2533 STy->getName().equals("opencl.image3d_ro_t")) {
2534 HasReadOnlyImageType = true;
2535 } else if (STy->getName().equals("opencl.image2d_wo_t") ||
2536 STy->getName().equals("opencl.image3d_wo_t")) {
2537 HasWriteOnlyImageType = true;
2538 }
2539 }
2540 }
2541 }
2542
2543 if (HasReadOnlyImageType || HasWriteOnlyImageType) {
2544 // Ops[0] = Target ID
2545 // Ops[1] = Decoration (NonReadable or NonWritable)
2546 Ops.clear();
2547
2548 ArgIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[&Arg]);
2549 Ops.push_back(ArgIDOp);
2550
2551 Deco = spv::DecorationNonReadable;
2552 if (HasReadOnlyImageType) {
2553 Deco = spv::DecorationNonWritable;
2554 }
2555 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2556 Ops.push_back(DecoOp);
2557
2558 DescDecoInst =
2559 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2560 SPIRVInstList.insert(DecoInsertPoint, DescDecoInst);
2561 }
2562
2563 // Handle const address space.
2564 if (NewGV->getType()->getPointerAddressSpace() ==
2565 AddressSpace::Constant) {
2566 // Ops[0] = Target ID
2567 // Ops[1] = Decoration (NonWriteable)
2568 Ops.clear();
2569
2570 Ops.push_back(ArgIDOp);
2571
2572 Deco = spv::DecorationNonWritable;
2573 DecoOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Deco);
2574 Ops.push_back(DecoOp);
2575
2576 BindDecoInst =
2577 new SPIRVInstruction(3, spv::OpDecorate, 0 /* No id */, Ops);
2578 SPIRVInstList.insert(DecoInsertPoint, BindDecoInst);
2579 }
2580 }
2581 }
2582
2583 //
2584 // Generate OPFunction.
2585 //
2586
2587 // FOps[0] : Result Type ID
2588 // FOps[1] : Function Control
2589 // FOps[2] : Function Type ID
2590 SPIRVOperandList FOps;
2591
2592 // Find SPIRV instruction for return type.
2593 uint32_t RetTyID = lookupType(FTy->getReturnType());
2594 SPIRVOperand *RetTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
2595 FOps.push_back(RetTyOp);
2596
2597 // Check function attributes for SPIRV Function Control.
2598 uint32_t FuncControl = spv::FunctionControlMaskNone;
2599 if (F.hasFnAttribute(Attribute::AlwaysInline)) {
2600 FuncControl |= spv::FunctionControlInlineMask;
2601 }
2602 if (F.hasFnAttribute(Attribute::NoInline)) {
2603 FuncControl |= spv::FunctionControlDontInlineMask;
2604 }
2605 // TODO: Check llvm attribute for Function Control Pure.
2606 if (F.hasFnAttribute(Attribute::ReadOnly)) {
2607 FuncControl |= spv::FunctionControlPureMask;
2608 }
2609 // TODO: Check llvm attribute for Function Control Const.
2610 if (F.hasFnAttribute(Attribute::ReadNone)) {
2611 FuncControl |= spv::FunctionControlConstMask;
2612 }
2613
2614 SPIRVOperand *FunctionControlOp =
2615 new SPIRVOperand(SPIRVOperandType::NUMBERID, FuncControl);
2616 FOps.push_back(FunctionControlOp);
2617
2618 uint32_t FTyID;
2619 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2620 SmallVector<Type *, 4> NewFuncParamTys;
2621 FunctionType *NewFTy =
2622 FunctionType::get(FTy->getReturnType(), NewFuncParamTys, false);
2623 FTyID = lookupType(NewFTy);
2624 } else {
2625 // Handle function with global constant parameters.
2626 if (GlobalConstFuncTyMap.count(FTy)) {
2627 FTyID = lookupType(GlobalConstFuncTyMap[FTy].first);
2628 } else {
2629 FTyID = lookupType(FTy);
2630 }
2631 }
2632
2633 SPIRVOperand *FTyOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, FTyID);
2634 FOps.push_back(FTyOp);
2635
2636 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
2637 EntryPoints.push_back(std::make_pair(&F, nextID));
2638 }
2639
2640 VMap[&F] = nextID;
2641
2642 // Generate SPIRV instruction for function.
2643 SPIRVInstruction *FuncInst =
2644 new SPIRVInstruction(5, spv::OpFunction, nextID++, FOps);
2645 SPIRVInstList.push_back(FuncInst);
2646
2647 //
2648 // Generate OpFunctionParameter for Normal function.
2649 //
2650
2651 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2652 // Iterate Argument for name instead of param type from function type.
2653 unsigned ArgIdx = 0;
2654 for (Argument &Arg : F.args()) {
2655 VMap[&Arg] = nextID;
2656
2657 // ParamOps[0] : Result Type ID
2658 SPIRVOperandList ParamOps;
2659
2660 // Find SPIRV instruction for parameter type.
2661 uint32_t ParamTyID = lookupType(Arg.getType());
2662 if (PointerType *PTy = dyn_cast<PointerType>(Arg.getType())) {
2663 if (GlobalConstFuncTyMap.count(FTy)) {
2664 if (ArgIdx == GlobalConstFuncTyMap[FTy].second) {
2665 Type *EleTy = PTy->getPointerElementType();
2666 Type *ArgTy =
2667 PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
2668 ParamTyID = lookupType(ArgTy);
2669 GlobalConstArgSet.insert(&Arg);
2670 }
2671 }
2672 }
2673 SPIRVOperand *ParamTyOp =
2674 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParamTyID);
2675 ParamOps.push_back(ParamTyOp);
2676
2677 // Generate SPIRV instruction for parameter.
2678 SPIRVInstruction *ParamInst =
2679 new SPIRVInstruction(3, spv::OpFunctionParameter, nextID++, ParamOps);
2680 SPIRVInstList.push_back(ParamInst);
2681
2682 ArgIdx++;
2683 }
2684 }
2685}
2686
2687void SPIRVProducerPass::GenerateModuleInfo() {
2688 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
2689 EntryPointVecType &EntryPoints = getEntryPointVec();
2690 ValueMapType &VMap = getValueMap();
2691 ValueList &EntryPointInterfaces = getEntryPointInterfacesVec();
2692 uint32_t &ExtInstImportID = getOpExtInstImportID();
2693 std::vector<uint32_t> &BuiltinDimVec = getBuiltinDimVec();
2694
2695 // Set up insert point.
2696 auto InsertPoint = SPIRVInstList.begin();
2697
2698 //
2699 // Generate OpCapability
2700 //
2701 // TODO: Which llvm information is mapped to SPIRV Capapbility?
2702
2703 // Ops[0] = Capability
2704 SPIRVOperandList Ops;
2705
2706 SPIRVInstruction *CapInst = new SPIRVInstruction(
2707 2, spv::OpCapability, 0 /* No id */,
2708 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::CapabilityShader));
2709 SPIRVInstList.insert(InsertPoint, CapInst);
2710
2711 for (Type *Ty : getTypeList()) {
2712 // Find the i16 type.
2713 if (Ty->isIntegerTy(16)) {
2714 // Generate OpCapability for i16 type.
2715 SPIRVInstList.insert(
2716 InsertPoint,
2717 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2718 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2719 spv::CapabilityInt16)));
2720 } else if (Ty->isIntegerTy(64)) {
2721 // Generate OpCapability for i64 type.
2722 SPIRVInstList.insert(
2723 InsertPoint,
2724 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2725 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2726 spv::CapabilityInt64)));
2727 } else if (Ty->isHalfTy()) {
2728 // Generate OpCapability for half type.
2729 SPIRVInstList.insert(
2730 InsertPoint,
2731 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2732 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2733 spv::CapabilityFloat16)));
2734 } else if (Ty->isDoubleTy()) {
2735 // Generate OpCapability for double type.
2736 SPIRVInstList.insert(
2737 InsertPoint,
2738 new SPIRVInstruction(2, spv::OpCapability, 0 /* No id */,
2739 new SPIRVOperand(SPIRVOperandType::NUMBERID,
2740 spv::CapabilityFloat64)));
2741 } else if (auto *STy = dyn_cast<StructType>(Ty)) {
2742 if (STy->isOpaque()) {
David Neto565571c2017-08-21 12:00:05 -04002743 if (STy->getName().equals("opencl.image2d_wo_t") ||
2744 STy->getName().equals("opencl.image3d_wo_t")) {
David Neto22f144c2017-06-12 14:26:21 -04002745 // Generate OpCapability for write only image type.
2746 SPIRVInstList.insert(
2747 InsertPoint,
2748 new SPIRVInstruction(
2749 2, spv::OpCapability, 0 /* No id */,
2750 new SPIRVOperand(
2751 SPIRVOperandType::NUMBERID,
2752 spv::CapabilityStorageImageWriteWithoutFormat)));
2753 }
2754 }
2755 }
2756 }
2757
2758 if (hasVariablePointers()) {
2759 //
2760 // Generate OpCapability and OpExtension
2761 //
2762
2763 //
2764 // Generate OpCapability.
2765 //
2766 // Ops[0] = Capability
2767 //
2768 Ops.clear();
2769
2770 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
2771 spv::CapabilityVariablePointers));
2772
2773 SPIRVInstList.insert(InsertPoint, new SPIRVInstruction(2, spv::OpCapability,
2774 0 /* No id */, Ops));
2775
2776 //
2777 // Generate OpExtension.
2778 //
2779 // Ops[0] = Name (Literal String)
2780 //
David Netoa772fd12017-08-04 14:17:33 -04002781 for (auto extension : {"SPV_KHR_storage_buffer_storage_class",
2782 "SPV_KHR_variable_pointers"}) {
2783 Ops.clear();
David Neto22f144c2017-06-12 14:26:21 -04002784
David Netoa772fd12017-08-04 14:17:33 -04002785 SPIRVOperand *Name =
2786 new SPIRVOperand(SPIRVOperandType::LITERAL_STRING, extension);
2787 Ops.push_back(Name);
David Neto22f144c2017-06-12 14:26:21 -04002788
David Netoa772fd12017-08-04 14:17:33 -04002789 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
2790 if ((Name->getLiteralStr().size() + 1) % 4) {
2791 NameWordSize += 1;
2792 }
2793
2794 assert((NameWordSize + 1) < UINT16_MAX);
2795 uint16_t WordCount = static_cast<uint16_t>(1 + NameWordSize);
2796
2797 SPIRVInstruction *ExtensionInst =
2798 new SPIRVInstruction(WordCount, spv::OpExtension, 0 /* No id */, Ops);
2799 SPIRVInstList.insert(InsertPoint, ExtensionInst);
David Neto22f144c2017-06-12 14:26:21 -04002800 }
David Neto22f144c2017-06-12 14:26:21 -04002801 }
2802
2803 if (ExtInstImportID) {
2804 ++InsertPoint;
2805 }
2806
2807 //
2808 // Generate OpMemoryModel
2809 //
2810 // Memory model for Vulkan will always be GLSL450.
2811
2812 // Ops[0] = Addressing Model
2813 // Ops[1] = Memory Model
2814 Ops.clear();
2815 SPIRVOperand *AddrModel =
2816 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::AddressingModelLogical);
2817 Ops.push_back(AddrModel);
2818
2819 SPIRVOperand *MemModel =
2820 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::MemoryModelGLSL450);
2821 Ops.push_back(MemModel);
2822
2823 SPIRVInstruction *MemModelInst =
2824 new SPIRVInstruction(3, spv::OpMemoryModel, 0 /* No id */, Ops);
2825 SPIRVInstList.insert(InsertPoint, MemModelInst);
2826
2827 //
2828 // Generate OpEntryPoint
2829 //
2830 for (auto EntryPoint : EntryPoints) {
2831 // Ops[0] = Execution Model
2832 // Ops[1] = EntryPoint ID
2833 // Ops[2] = Name (Literal String)
2834 // ...
2835 //
2836 // TODO: Do we need to consider Interface ID for forward references???
2837 Ops.clear();
2838 SPIRVOperand *ExecModel = new SPIRVOperand(SPIRVOperandType::NUMBERID,
2839 spv::ExecutionModelGLCompute);
2840 Ops.push_back(ExecModel);
2841
2842 SPIRVOperand *EntryPointID =
2843 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
2844 Ops.push_back(EntryPointID);
2845
2846 SPIRVOperand *Name = new SPIRVOperand(SPIRVOperandType::LITERAL_STRING,
2847 EntryPoint.first->getName());
2848 Ops.push_back(Name);
2849
2850 size_t NameWordSize = (Name->getLiteralStr().size() + 1) / 4;
2851 if ((Name->getLiteralStr().size() + 1) % 4) {
2852 NameWordSize += 1;
2853 }
2854
2855 assert((3 + NameWordSize) < UINT16_MAX);
2856 uint16_t WordCount = static_cast<uint16_t>(3 + NameWordSize);
2857
2858 for (Value *Interface : EntryPointInterfaces) {
2859 SPIRVOperand *GIDOp =
2860 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[Interface]);
2861 Ops.push_back(GIDOp);
2862 WordCount++;
2863 }
2864
2865 SPIRVInstruction *EntryPointInst =
2866 new SPIRVInstruction(WordCount, spv::OpEntryPoint, 0 /* No id */, Ops);
2867 SPIRVInstList.insert(InsertPoint, EntryPointInst);
2868 }
2869
2870 for (auto EntryPoint : EntryPoints) {
2871 if (const MDNode *MD = dyn_cast<Function>(EntryPoint.first)
2872 ->getMetadata("reqd_work_group_size")) {
2873
2874 if (!BuiltinDimVec.empty()) {
2875 llvm_unreachable(
2876 "Kernels should have consistent work group size definition");
2877 }
2878
2879 //
2880 // Generate OpExecutionMode
2881 //
2882
2883 // Ops[0] = Entry Point ID
2884 // Ops[1] = Execution Mode
2885 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
2886 Ops.clear();
2887 SPIRVOperand *EntryPointID =
2888 new SPIRVOperand(SPIRVOperandType::NUMBERID, EntryPoint.second);
2889 Ops.push_back(EntryPointID);
2890
2891 SPIRVOperand *ExecMode = new SPIRVOperand(SPIRVOperandType::NUMBERID,
2892 spv::ExecutionModeLocalSize);
2893 Ops.push_back(ExecMode);
2894
2895 uint32_t XDim = static_cast<uint32_t>(
2896 mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue());
2897 uint32_t YDim = static_cast<uint32_t>(
2898 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue());
2899 uint32_t ZDim = static_cast<uint32_t>(
2900 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue());
2901
2902 std::vector<uint32_t> LiteralNum;
2903 LiteralNum.push_back(XDim);
2904 SPIRVOperand *XDimOp =
2905 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2906 Ops.push_back(XDimOp);
2907
2908 LiteralNum.clear();
2909 LiteralNum.push_back(YDim);
2910 SPIRVOperand *YDimOp =
2911 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2912 Ops.push_back(YDimOp);
2913
2914 LiteralNum.clear();
2915 LiteralNum.push_back(ZDim);
2916 SPIRVOperand *ZDimOp =
2917 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2918 Ops.push_back(ZDimOp);
2919
2920 SPIRVInstruction *ExecModeInst =
2921 new SPIRVInstruction(static_cast<uint16_t>(1 + Ops.size()),
2922 spv::OpExecutionMode, 0 /* No id */, Ops);
2923 SPIRVInstList.insert(InsertPoint, ExecModeInst);
2924 }
2925 }
2926
2927 //
2928 // Generate OpSource.
2929 //
2930 // Ops[0] = SourceLanguage ID
2931 // Ops[1] = Version (LiteralNum)
2932 //
2933 Ops.clear();
2934 SPIRVOperand *SourceLanguage =
2935 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::SourceLanguageOpenCL_C);
2936 Ops.push_back(SourceLanguage);
2937
2938 std::vector<uint32_t> LiteralNum;
2939 LiteralNum.push_back(120);
2940 SPIRVOperand *Version =
2941 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2942 Ops.push_back(Version);
2943
2944 SPIRVInstruction *OpenSourceInst =
2945 new SPIRVInstruction(3, spv::OpSource, 0 /* No id */, Ops);
2946 SPIRVInstList.insert(InsertPoint, OpenSourceInst);
2947
2948 if (!BuiltinDimVec.empty()) {
2949 //
2950 // Generate OpDecorates for x/y/z dimension.
2951 //
2952 // Ops[0] = Target ID
2953 // Ops[1] = Decoration (SpecId)
2954 // Ops[2] = Specialization Cosntant ID (Literal Number)
2955
2956 // X Dimension
2957 Ops.clear();
2958
2959 SPIRVOperand *TargetID =
2960 new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[0]);
2961 Ops.push_back(TargetID);
2962
2963 SPIRVOperand *DecoOp =
2964 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
2965 Ops.push_back(DecoOp);
2966
2967 LiteralNum.clear();
2968 LiteralNum.push_back(0);
2969 SPIRVOperand *XDim =
2970 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2971 Ops.push_back(XDim);
2972
2973 SPIRVInstruction *XDimDecoInst =
2974 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2975 SPIRVInstList.insert(InsertPoint, XDimDecoInst);
2976
2977 // Y Dimension
2978 Ops.clear();
2979
2980 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[1]);
2981 Ops.push_back(TargetID);
2982
2983 DecoOp =
2984 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
2985 Ops.push_back(DecoOp);
2986
2987 LiteralNum.clear();
2988 LiteralNum.push_back(1);
2989 SPIRVOperand *YDim =
2990 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
2991 Ops.push_back(YDim);
2992
2993 SPIRVInstruction *YDimDecoInst =
2994 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
2995 SPIRVInstList.insert(InsertPoint, YDimDecoInst);
2996
2997 // Z Dimension
2998 Ops.clear();
2999
3000 TargetID = new SPIRVOperand(SPIRVOperandType::NUMBERID, BuiltinDimVec[2]);
3001 Ops.push_back(TargetID);
3002
3003 DecoOp =
3004 new SPIRVOperand(SPIRVOperandType::NUMBERID, spv::DecorationSpecId);
3005 Ops.push_back(DecoOp);
3006
3007 LiteralNum.clear();
3008 LiteralNum.push_back(2);
3009 SPIRVOperand *ZDim =
3010 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3011 Ops.push_back(ZDim);
3012
3013 SPIRVInstruction *ZDimDecoInst =
3014 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
3015 SPIRVInstList.insert(InsertPoint, ZDimDecoInst);
3016 }
3017}
3018
3019void SPIRVProducerPass::GenerateInstForArg(Function &F) {
3020 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3021 ValueMapType &VMap = getValueMap();
3022 Module *Module = F.getParent();
3023 LLVMContext &Context = Module->getContext();
3024 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3025
3026 for (Argument &Arg : F.args()) {
3027 if (Arg.use_empty()) {
3028 continue;
3029 }
3030
3031 // Check the type of users of arguments.
3032 bool HasOnlyGEPUse = true;
3033 for (auto *U : Arg.users()) {
3034 if (!isa<GetElementPtrInst>(U) && isa<Instruction>(U)) {
3035 HasOnlyGEPUse = false;
3036 break;
3037 }
3038 }
3039
3040 Type *ArgTy = Arg.getType();
3041
3042 if (PointerType *PTy = dyn_cast<PointerType>(ArgTy)) {
3043 if (StructType *STy = dyn_cast<StructType>(PTy->getElementType())) {
3044 if (STy->isOpaque()) {
3045 // Generate OpLoad for sampler and image types.
3046 if (STy->getName().equals("opencl.sampler_t") ||
3047 STy->getName().equals("opencl.image2d_ro_t") ||
3048 STy->getName().equals("opencl.image2d_wo_t") ||
3049 STy->getName().equals("opencl.image3d_ro_t") ||
3050 STy->getName().equals("opencl.image3d_wo_t")) {
3051 //
3052 // Generate OpLoad.
3053 //
3054 // Ops[0] = Result Type ID
3055 // Ops[1] = Pointer ID
3056 // Ops[2] ... Ops[n] = Optional Memory Access
3057 //
3058 // TODO: Do we need to implement Optional Memory Access???
3059 SPIRVOperandList Ops;
3060
3061 // Use type with address space modified.
3062 ArgTy = ArgGVMap[&Arg]->getType()->getPointerElementType();
3063
3064 uint32_t ResTyID = lookupType(ArgTy);
3065 SPIRVOperand *ResTyIDOp =
3066 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3067 Ops.push_back(ResTyIDOp);
3068
3069 uint32_t PointerID = VMap[&Arg];
3070 SPIRVOperand *PointerIDOp =
3071 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3072 Ops.push_back(PointerIDOp);
3073
3074 VMap[&Arg] = nextID;
3075 SPIRVInstruction *Inst =
3076 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3077 SPIRVInstList.push_back(Inst);
3078 continue;
3079 }
3080 }
3081 }
3082
3083 if (!HasOnlyGEPUse) {
3084 //
3085 // Generate OpAccessChain.
3086 //
3087 // Ops[0] = Result Type ID
3088 // Ops[1] = Base ID
3089 // Ops[2] ... Ops[n] = Indexes ID
3090 SPIRVOperandList Ops;
3091
3092 uint32_t ResTyID = lookupType(ArgTy);
3093 if (!isa<PointerType>(ArgTy)) {
3094 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3095 }
3096 SPIRVOperand *ResTyOp =
3097 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3098 Ops.push_back(ResTyOp);
3099
3100 uint32_t BaseID = VMap[&Arg];
3101 SPIRVOperand *BaseOp =
3102 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3103 Ops.push_back(BaseOp);
3104
3105 Type *IdxTy = Type::getInt32Ty(Context);
3106 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3107 SPIRVOperand *IndexIDOp =
3108 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3109 Ops.push_back(IndexIDOp);
3110 Ops.push_back(IndexIDOp);
3111
3112 // Generate SPIRV instruction for argument.
3113 VMap[&Arg] = nextID;
3114 SPIRVInstruction *ArgInst =
3115 new SPIRVInstruction(6, spv::OpAccessChain, nextID++, Ops);
3116 SPIRVInstList.push_back(ArgInst);
3117 } else {
3118 // For GEP uses, generate OpAccessChain with folding GEP ahead of GEP.
3119 // Nothing to do here.
3120 }
3121 } else {
3122 //
3123 // Generate OpAccessChain and OpLoad for non-pointer type argument.
3124 //
3125
3126 //
3127 // Generate OpAccessChain.
3128 //
3129 // Ops[0] = Result Type ID
3130 // Ops[1] = Base ID
3131 // Ops[2] ... Ops[n] = Indexes ID
3132 SPIRVOperandList Ops;
3133
3134 uint32_t ResTyID = lookupType(ArgTy);
3135 if (!isa<PointerType>(ArgTy)) {
3136 ResTyID = lookupType(PointerType::get(ArgTy, AddressSpace::Global));
3137 }
3138 SPIRVOperand *ResTyIDOp =
3139 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3140 Ops.push_back(ResTyIDOp);
3141
3142 uint32_t BaseID = VMap[&Arg];
3143 SPIRVOperand *BaseOp =
3144 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3145 Ops.push_back(BaseOp);
3146
3147 Type *IdxTy = Type::getInt32Ty(Context);
3148 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3149 SPIRVOperand *IndexIDOp =
3150 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3151 Ops.push_back(IndexIDOp);
3152
3153 // Generate SPIRV instruction for argument.
3154 uint32_t PointerID = nextID;
3155 VMap[&Arg] = nextID;
3156 SPIRVInstruction *ArgInst =
3157 new SPIRVInstruction(5, spv::OpAccessChain, nextID++, Ops);
3158 SPIRVInstList.push_back(ArgInst);
3159
3160 //
3161 // Generate OpLoad.
3162 //
3163
3164 // Ops[0] = Result Type ID
3165 // Ops[1] = Pointer ID
3166 // Ops[2] ... Ops[n] = Optional Memory Access
3167 //
3168 // TODO: Do we need to implement Optional Memory Access???
3169 Ops.clear();
3170
3171 ResTyID = lookupType(ArgTy);
3172 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3173 Ops.push_back(ResTyIDOp);
3174
3175 SPIRVOperand *PointerIDOp =
3176 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
3177 Ops.push_back(PointerIDOp);
3178
3179 VMap[&Arg] = nextID;
3180 SPIRVInstruction *Inst =
3181 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
3182 SPIRVInstList.push_back(Inst);
3183 }
3184 }
3185}
3186
3187void SPIRVProducerPass::GenerateFuncBody(Function &F) {
3188 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3189 ValueMapType &VMap = getValueMap();
3190
3191 bool IsKernel = false;
3192 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
3193 IsKernel = true;
3194 }
3195
3196 for (BasicBlock &BB : F) {
3197 // Register BasicBlock to ValueMap.
3198 VMap[&BB] = nextID;
3199
3200 //
3201 // Generate OpLabel for Basic Block.
3202 //
3203 SPIRVOperandList Ops;
3204 SPIRVInstruction *Inst =
3205 new SPIRVInstruction(2, spv::OpLabel, nextID++, Ops);
3206 SPIRVInstList.push_back(Inst);
3207
David Neto6dcd4712017-06-23 11:06:47 -04003208 // OpVariable instructions must come first.
3209 for (Instruction &I : BB) {
3210 if (isa<AllocaInst>(I)) {
3211 GenerateInstruction(I);
3212 }
3213 }
3214
David Neto22f144c2017-06-12 14:26:21 -04003215 if (&BB == &F.getEntryBlock() && IsKernel) {
3216 GenerateInstForArg(F);
3217 }
3218
3219 for (Instruction &I : BB) {
David Neto6dcd4712017-06-23 11:06:47 -04003220 if (!isa<AllocaInst>(I)) {
3221 GenerateInstruction(I);
3222 }
David Neto22f144c2017-06-12 14:26:21 -04003223 }
3224 }
3225}
3226
3227spv::Op SPIRVProducerPass::GetSPIRVCmpOpcode(CmpInst *I) {
3228 const std::map<CmpInst::Predicate, spv::Op> Map = {
3229 {CmpInst::ICMP_EQ, spv::OpIEqual},
3230 {CmpInst::ICMP_NE, spv::OpINotEqual},
3231 {CmpInst::ICMP_UGT, spv::OpUGreaterThan},
3232 {CmpInst::ICMP_UGE, spv::OpUGreaterThanEqual},
3233 {CmpInst::ICMP_ULT, spv::OpULessThan},
3234 {CmpInst::ICMP_ULE, spv::OpULessThanEqual},
3235 {CmpInst::ICMP_SGT, spv::OpSGreaterThan},
3236 {CmpInst::ICMP_SGE, spv::OpSGreaterThanEqual},
3237 {CmpInst::ICMP_SLT, spv::OpSLessThan},
3238 {CmpInst::ICMP_SLE, spv::OpSLessThanEqual},
3239 {CmpInst::FCMP_OEQ, spv::OpFOrdEqual},
3240 {CmpInst::FCMP_OGT, spv::OpFOrdGreaterThan},
3241 {CmpInst::FCMP_OGE, spv::OpFOrdGreaterThanEqual},
3242 {CmpInst::FCMP_OLT, spv::OpFOrdLessThan},
3243 {CmpInst::FCMP_OLE, spv::OpFOrdLessThanEqual},
3244 {CmpInst::FCMP_ONE, spv::OpFOrdNotEqual},
3245 {CmpInst::FCMP_UEQ, spv::OpFUnordEqual},
3246 {CmpInst::FCMP_UGT, spv::OpFUnordGreaterThan},
3247 {CmpInst::FCMP_UGE, spv::OpFUnordGreaterThanEqual},
3248 {CmpInst::FCMP_ULT, spv::OpFUnordLessThan},
3249 {CmpInst::FCMP_ULE, spv::OpFUnordLessThanEqual},
3250 {CmpInst::FCMP_UNE, spv::OpFUnordNotEqual}};
3251
3252 assert(0 != Map.count(I->getPredicate()));
3253
3254 return Map.at(I->getPredicate());
3255}
3256
3257spv::Op SPIRVProducerPass::GetSPIRVCastOpcode(Instruction &I) {
3258 const std::map<unsigned, spv::Op> Map{
3259 {Instruction::Trunc, spv::OpUConvert},
3260 {Instruction::ZExt, spv::OpUConvert},
3261 {Instruction::SExt, spv::OpSConvert},
3262 {Instruction::FPToUI, spv::OpConvertFToU},
3263 {Instruction::FPToSI, spv::OpConvertFToS},
3264 {Instruction::UIToFP, spv::OpConvertUToF},
3265 {Instruction::SIToFP, spv::OpConvertSToF},
3266 {Instruction::FPTrunc, spv::OpFConvert},
3267 {Instruction::FPExt, spv::OpFConvert},
3268 {Instruction::BitCast, spv::OpBitcast}};
3269
3270 assert(0 != Map.count(I.getOpcode()));
3271
3272 return Map.at(I.getOpcode());
3273}
3274
3275spv::Op SPIRVProducerPass::GetSPIRVBinaryOpcode(Instruction &I) {
3276 if (I.getType()->isIntegerTy(1)) {
3277 switch (I.getOpcode()) {
3278 default:
3279 break;
3280 case Instruction::Or:
3281 return spv::OpLogicalOr;
3282 case Instruction::And:
3283 return spv::OpLogicalAnd;
3284 case Instruction::Xor:
3285 return spv::OpLogicalNotEqual;
3286 }
3287 }
3288
3289 const std::map<unsigned, spv::Op> Map {
3290 {Instruction::Add, spv::OpIAdd},
3291 {Instruction::FAdd, spv::OpFAdd},
3292 {Instruction::Sub, spv::OpISub},
3293 {Instruction::FSub, spv::OpFSub},
3294 {Instruction::Mul, spv::OpIMul},
3295 {Instruction::FMul, spv::OpFMul},
3296 {Instruction::UDiv, spv::OpUDiv},
3297 {Instruction::SDiv, spv::OpSDiv},
3298 {Instruction::FDiv, spv::OpFDiv},
3299 {Instruction::URem, spv::OpUMod},
3300 {Instruction::SRem, spv::OpSRem},
3301 {Instruction::FRem, spv::OpFRem},
3302 {Instruction::Or, spv::OpBitwiseOr},
3303 {Instruction::Xor, spv::OpBitwiseXor},
3304 {Instruction::And, spv::OpBitwiseAnd},
3305 {Instruction::Shl, spv::OpShiftLeftLogical},
3306 {Instruction::LShr, spv::OpShiftRightLogical},
3307 {Instruction::AShr, spv::OpShiftRightArithmetic}};
3308
3309 assert(0 != Map.count(I.getOpcode()));
3310
3311 return Map.at(I.getOpcode());
3312}
3313
3314void SPIRVProducerPass::GenerateInstruction(Instruction &I) {
3315 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
3316 ValueMapType &VMap = getValueMap();
3317 ValueToValueMapTy &ArgGVMap = getArgumentGVMap();
3318 ValueMapType &ArgGVIDMap = getArgumentGVIDMap();
3319 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
3320 LLVMContext &Context = I.getParent()->getParent()->getParent()->getContext();
3321
3322 // Register Instruction to ValueMap.
3323 if (0 == VMap[&I]) {
3324 VMap[&I] = nextID;
3325 }
3326
3327 switch (I.getOpcode()) {
3328 default: {
3329 if (Instruction::isCast(I.getOpcode())) {
3330 //
3331 // Generate SPIRV instructions for cast operators.
3332 //
3333
3334 auto OpTy = I.getOperand(0)->getType();
3335 // Handle zext, sext and uitofp with i1 type specially.
3336 if ((I.getOpcode() == Instruction::ZExt ||
3337 I.getOpcode() == Instruction::SExt ||
3338 I.getOpcode() == Instruction::UIToFP) &&
3339 (OpTy->isIntegerTy(1) ||
3340 (OpTy->isVectorTy() &&
3341 OpTy->getVectorElementType()->isIntegerTy(1)))) {
3342 //
3343 // Generate OpSelect.
3344 //
3345
3346 // Ops[0] = Result Type ID
3347 // Ops[1] = Condition ID
3348 // Ops[2] = True Constant ID
3349 // Ops[3] = False Constant ID
3350 SPIRVOperandList Ops;
3351
3352 uint32_t ResTyID = lookupType(I.getType());
3353 SPIRVOperand *ResTyIDOp =
3354 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3355 Ops.push_back(ResTyIDOp);
3356
3357 // TODO: zext's first operand should be compare instructions???
3358 uint32_t CondID = VMap[I.getOperand(0)];
3359 SPIRVOperand *CondIDOp =
3360 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3361 Ops.push_back(CondIDOp);
3362
3363 uint32_t TrueID = 0;
3364 if (I.getOpcode() == Instruction::ZExt) {
3365 APInt One(32, 1);
3366 TrueID = VMap[Constant::getIntegerValue(I.getType(), One)];
3367 } else if (I.getOpcode() == Instruction::SExt) {
3368 APInt MinusOne(32, UINT64_MAX, true);
3369 TrueID = VMap[Constant::getIntegerValue(I.getType(), MinusOne)];
3370 } else {
3371 TrueID = VMap[ConstantFP::get(Context, APFloat(1.0f))];
3372 }
3373 SPIRVOperand *TrueIDOp =
3374 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3375 Ops.push_back(TrueIDOp);
3376
3377 uint32_t FalseID = 0;
3378 if (I.getOpcode() == Instruction::ZExt) {
3379 FalseID = VMap[Constant::getNullValue(I.getType())];
3380 } else if (I.getOpcode() == Instruction::SExt) {
3381 FalseID = VMap[Constant::getNullValue(I.getType())];
3382 } else {
3383 FalseID = VMap[ConstantFP::get(Context, APFloat(0.0f))];
3384 }
3385 SPIRVOperand *FalseIDOp =
3386 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3387 Ops.push_back(FalseIDOp);
3388
3389 SPIRVInstruction *Inst =
3390 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3391 SPIRVInstList.push_back(Inst);
3392 } else {
3393 // Ops[0] = Result Type ID
3394 // Ops[1] = Source Value ID
3395 SPIRVOperandList Ops;
3396
3397 uint32_t ResTyID = lookupType(I.getType());
3398 SPIRVOperand *ResTyIDOp =
3399 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3400 Ops.push_back(ResTyIDOp);
3401
3402 uint32_t SrcID = VMap[I.getOperand(0)];
3403 SPIRVOperand *SrcIDOp =
3404 new SPIRVOperand(SPIRVOperandType::NUMBERID, SrcID);
3405 Ops.push_back(SrcIDOp);
3406
3407 SPIRVInstruction *Inst =
3408 new SPIRVInstruction(4, GetSPIRVCastOpcode(I), nextID++, Ops);
3409 SPIRVInstList.push_back(Inst);
3410 }
3411 } else if (isa<BinaryOperator>(I)) {
3412 //
3413 // Generate SPIRV instructions for binary operators.
3414 //
3415
3416 // Handle xor with i1 type specially.
3417 if (I.getOpcode() == Instruction::Xor &&
3418 I.getType() == Type::getInt1Ty(Context) &&
3419 (isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
3420 //
3421 // Generate OpLogicalNot.
3422 //
3423 // Ops[0] = Result Type ID
3424 // Ops[1] = Operand
3425 SPIRVOperandList Ops;
3426
3427 uint32_t ResTyID = lookupType(I.getType());
3428 SPIRVOperand *ResTyIDOp =
3429 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3430 Ops.push_back(ResTyIDOp);
3431
3432 Value *CondV = I.getOperand(0);
3433 if (isa<Constant>(I.getOperand(0))) {
3434 CondV = I.getOperand(1);
3435 }
3436 uint32_t CondID = VMap[CondV];
3437 SPIRVOperand *CondIDOp =
3438 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3439 Ops.push_back(CondIDOp);
3440
3441 SPIRVInstruction *Inst =
3442 new SPIRVInstruction(4, spv::OpLogicalNot, nextID++, Ops);
3443 SPIRVInstList.push_back(Inst);
3444 } else {
3445 // Ops[0] = Result Type ID
3446 // Ops[1] = Operand 0
3447 // Ops[2] = Operand 1
3448 SPIRVOperandList Ops;
3449
3450 uint32_t ResTyID = lookupType(I.getType());
3451 SPIRVOperand *ResTyIDOp =
3452 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3453 Ops.push_back(ResTyIDOp);
3454
3455 uint32_t Op0ID = VMap[I.getOperand(0)];
3456 SPIRVOperand *Op0IDOp =
3457 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3458 Ops.push_back(Op0IDOp);
3459
3460 uint32_t Op1ID = VMap[I.getOperand(1)];
3461 SPIRVOperand *Op1IDOp =
3462 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3463 Ops.push_back(Op1IDOp);
3464
3465 SPIRVInstruction *Inst =
3466 new SPIRVInstruction(5, GetSPIRVBinaryOpcode(I), nextID++, Ops);
3467 SPIRVInstList.push_back(Inst);
3468 }
3469 } else {
3470 I.print(errs());
3471 llvm_unreachable("Unsupported instruction???");
3472 }
3473 break;
3474 }
3475 case Instruction::GetElementPtr: {
3476 auto &GlobalConstArgSet = getGlobalConstArgSet();
3477
3478 //
3479 // Generate OpAccessChain.
3480 //
3481 GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
3482
3483 //
3484 // Generate OpAccessChain.
3485 //
3486
3487 // Ops[0] = Result Type ID
3488 // Ops[1] = Base ID
3489 // Ops[2] ... Ops[n] = Indexes ID
3490 SPIRVOperandList Ops;
3491
David Neto1a1a0582017-07-07 12:01:44 -04003492 PointerType* ResultType = cast<PointerType>(GEP->getType());
David Neto22f144c2017-06-12 14:26:21 -04003493 if (GEP->getPointerAddressSpace() == AddressSpace::ModuleScopePrivate ||
3494 GlobalConstArgSet.count(GEP->getPointerOperand())) {
3495 // Use pointer type with private address space for global constant.
3496 Type *EleTy = I.getType()->getPointerElementType();
David Neto1a1a0582017-07-07 12:01:44 -04003497 ResultType = PointerType::get(EleTy, AddressSpace::ModuleScopePrivate);
David Neto22f144c2017-06-12 14:26:21 -04003498 }
David Neto1a1a0582017-07-07 12:01:44 -04003499 const uint32_t ResTyID = lookupType(ResultType);
David Neto22f144c2017-06-12 14:26:21 -04003500 SPIRVOperand *ResTyIDOp =
3501 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3502 Ops.push_back(ResTyIDOp);
3503
3504 // Check whether GEP's pointer operand is pointer argument.
3505 bool HasArgBasePointer = false;
3506 for (auto ArgGV : ArgGVMap) {
3507 if (ArgGV.first == GEP->getPointerOperand()) {
3508 if (isa<PointerType>(ArgGV.first->getType())) {
3509 HasArgBasePointer = true;
3510 } else {
3511 llvm_unreachable(
3512 "GEP's pointer operand is argument of non-poninter type???");
3513 }
3514 }
3515 }
3516
3517 uint32_t BaseID;
3518 if (HasArgBasePointer) {
3519 // Point to global variable for argument directly.
3520 BaseID = ArgGVIDMap[GEP->getPointerOperand()];
3521 } else {
3522 BaseID = VMap[GEP->getPointerOperand()];
3523 }
3524
3525 SPIRVOperand *BaseIDOp =
3526 new SPIRVOperand(SPIRVOperandType::NUMBERID, BaseID);
3527 Ops.push_back(BaseIDOp);
3528
3529 uint16_t WordCount = 4;
3530
3531 if (HasArgBasePointer) {
3532 // If GEP's pointer operand is argument, add one more index for struct
3533 // type to wrap up argument type.
3534 Type *IdxTy = Type::getInt32Ty(Context);
3535 uint32_t IndexID = VMap[ConstantInt::get(IdxTy, 0)];
3536 SPIRVOperand *IndexIDOp =
3537 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3538 Ops.push_back(IndexIDOp);
3539
3540 WordCount++;
3541 }
3542
3543 //
3544 // Follows below rules for gep.
3545 //
3546 // 1. If gep's first index is 0 and gep's base is not kernel function's
3547 // argument, generate OpAccessChain and ignore gep's first index.
3548 // 2. If gep's first index is not 0, generate OpPtrAccessChain and use gep's
3549 // first index.
3550 // 3. If gep's first index is not constant, generate OpPtrAccessChain and
3551 // use gep's first index.
3552 // 4. If it is not above case 1, 2 and 3, generate OpAccessChain and use
3553 // gep's first index.
3554 //
3555 spv::Op Opcode = spv::OpAccessChain;
3556 unsigned offset = 0;
3557 if (ConstantInt *CstInt = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
3558 if (CstInt->getZExtValue() == 0 && !HasArgBasePointer) {
3559 offset = 1;
3560 } else if (CstInt->getZExtValue() != 0 && !HasArgBasePointer) {
3561 Opcode = spv::OpPtrAccessChain;
David Neto22f144c2017-06-12 14:26:21 -04003562 }
3563 } else if (!HasArgBasePointer) {
3564 Opcode = spv::OpPtrAccessChain;
David Neto1a1a0582017-07-07 12:01:44 -04003565 }
3566
3567 if (Opcode == spv::OpPtrAccessChain) {
David Neto22f144c2017-06-12 14:26:21 -04003568 setVariablePointers(true);
David Neto1a1a0582017-07-07 12:01:44 -04003569 // Do we need to generate ArrayStride? Check against the GEP result type
3570 // rather than the pointer type of the base because when indexing into
3571 // an OpenCL program-scope constant, we'll swap out the LLVM base pointer
3572 // for something else in the SPIR-V.
3573 // E.g. see test/PointerAccessChain/pointer_index_is_constant_1.cl
3574 if (GetStorageClass(ResultType->getAddressSpace()) ==
3575 spv::StorageClassStorageBuffer) {
3576 // Save the need to generate an ArrayStride decoration. But defer
3577 // generation until later, so we only make one decoration.
3578 getPointerTypesNeedingArrayStride().insert(ResultType);
3579 }
David Neto22f144c2017-06-12 14:26:21 -04003580 }
3581
3582 for (auto II = GEP->idx_begin() + offset; II != GEP->idx_end(); II++) {
3583 uint32_t IndexID = VMap[*II];
3584 SPIRVOperand *IndexIDOp =
3585 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3586 Ops.push_back(IndexIDOp);
3587
3588 WordCount++;
3589 }
3590
3591 SPIRVInstruction *Inst =
3592 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3593 SPIRVInstList.push_back(Inst);
3594 break;
3595 }
3596 case Instruction::ExtractValue: {
3597 ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
3598 // Ops[0] = Result Type ID
3599 // Ops[1] = Composite ID
3600 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3601 SPIRVOperandList Ops;
3602
3603 uint32_t ResTyID = lookupType(I.getType());
3604 SPIRVOperand *ResTyIDOp =
3605 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3606 Ops.push_back(ResTyIDOp);
3607
3608 uint32_t CompositeID = VMap[EVI->getAggregateOperand()];
3609 SPIRVOperand *CompositeIDOp =
3610 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
3611 Ops.push_back(CompositeIDOp);
3612
3613 for (auto &Index : EVI->indices()) {
3614 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3615 }
3616
3617 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3618 SPIRVInstruction *Inst =
3619 new SPIRVInstruction(WordCount, spv::OpCompositeExtract, nextID++, Ops);
3620 SPIRVInstList.push_back(Inst);
3621 break;
3622 }
3623 case Instruction::InsertValue: {
3624 InsertValueInst *IVI = cast<InsertValueInst>(&I);
3625 // Ops[0] = Result Type ID
3626 // Ops[1] = Object ID
3627 // Ops[2] = Composite ID
3628 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3629 SPIRVOperandList Ops;
3630
3631 uint32_t ResTyID = lookupType(I.getType());
3632 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID));
3633
3634 uint32_t ObjectID = VMap[IVI->getInsertedValueOperand()];
3635 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID));
3636
3637 uint32_t CompositeID = VMap[IVI->getAggregateOperand()];
3638 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID));
3639
3640 for (auto &Index : IVI->indices()) {
3641 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, Index));
3642 }
3643
3644 uint16_t WordCount = static_cast<uint16_t>(2 + Ops.size());
3645 SPIRVInstruction *Inst =
3646 new SPIRVInstruction(WordCount, spv::OpCompositeInsert, nextID++, Ops);
3647 SPIRVInstList.push_back(Inst);
3648 break;
3649 }
3650 case Instruction::Select: {
3651 //
3652 // Generate OpSelect.
3653 //
3654
3655 // Ops[0] = Result Type ID
3656 // Ops[1] = Condition ID
3657 // Ops[2] = True Constant ID
3658 // Ops[3] = False Constant ID
3659 SPIRVOperandList Ops;
3660
3661 // Find SPIRV instruction for parameter type.
3662 auto Ty = I.getType();
3663 if (Ty->isPointerTy()) {
3664 auto PointeeTy = Ty->getPointerElementType();
3665 if (PointeeTy->isStructTy() &&
3666 dyn_cast<StructType>(PointeeTy)->isOpaque()) {
3667 Ty = PointeeTy;
3668 }
3669 }
3670
3671 uint32_t ResTyID = lookupType(Ty);
3672 SPIRVOperand *ResTyIDOp =
3673 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3674 Ops.push_back(ResTyIDOp);
3675
3676 uint32_t CondID = VMap[I.getOperand(0)];
3677 SPIRVOperand *CondIDOp =
3678 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
3679 Ops.push_back(CondIDOp);
3680
3681 uint32_t TrueID = VMap[I.getOperand(1)];
3682 SPIRVOperand *TrueIDOp =
3683 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueID);
3684 Ops.push_back(TrueIDOp);
3685
3686 uint32_t FalseID = VMap[I.getOperand(2)];
3687 SPIRVOperand *FalseIDOp =
3688 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseID);
3689 Ops.push_back(FalseIDOp);
3690
3691 SPIRVInstruction *Inst =
3692 new SPIRVInstruction(6, spv::OpSelect, nextID++, Ops);
3693 SPIRVInstList.push_back(Inst);
3694 break;
3695 }
3696 case Instruction::ExtractElement: {
3697 // Handle <4 x i8> type manually.
3698 Type *CompositeTy = I.getOperand(0)->getType();
3699 if (is4xi8vec(CompositeTy)) {
3700 //
3701 // Generate OpShiftRightLogical and OpBitwiseAnd for extractelement with
3702 // <4 x i8>.
3703 //
3704
3705 //
3706 // Generate OpShiftRightLogical
3707 //
3708 // Ops[0] = Result Type ID
3709 // Ops[1] = Operand 0
3710 // Ops[2] = Operand 1
3711 //
3712 SPIRVOperandList Ops;
3713
3714 uint32_t ResTyID = lookupType(CompositeTy);
3715 SPIRVOperand *ResTyIDOp =
3716 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3717 Ops.push_back(ResTyIDOp);
3718
3719 uint32_t Op0ID = VMap[I.getOperand(0)];
3720 SPIRVOperand *Op0IDOp =
3721 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3722 Ops.push_back(Op0IDOp);
3723
3724 uint32_t Op1ID = 0;
3725 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3726 // Handle constant index.
3727 uint64_t Idx = CI->getZExtValue();
3728 Value *ShiftAmount =
3729 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3730 Op1ID = VMap[ShiftAmount];
3731 } else {
3732 // Handle variable index.
3733 SPIRVOperandList TmpOps;
3734
3735 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
3736 SPIRVOperand *TmpResTyIDOp =
3737 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
3738 TmpOps.push_back(TmpResTyIDOp);
3739
3740 uint32_t IdxID = VMap[I.getOperand(1)];
3741 SPIRVOperand *TmpOp0IDOp =
3742 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
3743 TmpOps.push_back(TmpOp0IDOp);
3744
3745 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
3746 uint32_t Cst8ID = VMap[Cst8];
3747 SPIRVOperand *TmpOp1IDOp =
3748 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
3749 TmpOps.push_back(TmpOp1IDOp);
3750
3751 Op1ID = nextID;
3752
3753 SPIRVInstruction *TmpInst =
3754 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
3755 SPIRVInstList.push_back(TmpInst);
3756 }
3757 SPIRVOperand *Op1IDOp =
3758 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3759 Ops.push_back(Op1IDOp);
3760
3761 uint32_t ShiftID = nextID;
3762
3763 SPIRVInstruction *Inst =
3764 new SPIRVInstruction(5, spv::OpShiftRightLogical, nextID++, Ops);
3765 SPIRVInstList.push_back(Inst);
3766
3767 //
3768 // Generate OpBitwiseAnd
3769 //
3770 // Ops[0] = Result Type ID
3771 // Ops[1] = Operand 0
3772 // Ops[2] = Operand 1
3773 //
3774 Ops.clear();
3775
3776 ResTyID = lookupType(CompositeTy);
3777 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3778 Ops.push_back(ResTyIDOp);
3779
3780 Op0ID = ShiftID;
3781 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3782 Ops.push_back(Op0IDOp);
3783
3784 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3785 Op1ID = VMap[CstFF];
3786 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3787 Ops.push_back(Op1IDOp);
3788
3789 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3790 SPIRVInstList.push_back(Inst);
3791 break;
3792 }
3793
3794 // Ops[0] = Result Type ID
3795 // Ops[1] = Composite ID
3796 // Ops[2] ... Ops[n] = Indexes (Literal Number)
3797 SPIRVOperandList Ops;
3798
3799 uint32_t ResTyID = lookupType(I.getType());
3800 SPIRVOperand *ResTyIDOp =
3801 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3802 Ops.push_back(ResTyIDOp);
3803
3804 uint32_t CompositeID = VMap[I.getOperand(0)];
3805 SPIRVOperand *CompositeIDOp =
3806 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
3807 Ops.push_back(CompositeIDOp);
3808
3809 spv::Op Opcode = spv::OpCompositeExtract;
3810 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
3811 std::vector<uint32_t> LiteralNum;
3812 assert(CI->getZExtValue() < UINT32_MAX);
3813 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
3814 SPIRVOperand *Indexes =
3815 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3816 Ops.push_back(Indexes);
3817 } else {
3818 uint32_t IndexID = VMap[I.getOperand(1)];
3819 SPIRVOperand *IndexIDOp =
3820 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
3821 Ops.push_back(IndexIDOp);
3822 Opcode = spv::OpVectorExtractDynamic;
3823 }
3824
3825 uint16_t WordCount = 5;
3826 SPIRVInstruction *Inst =
3827 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
3828 SPIRVInstList.push_back(Inst);
3829 break;
3830 }
3831 case Instruction::InsertElement: {
3832 // Handle <4 x i8> type manually.
3833 Type *CompositeTy = I.getOperand(0)->getType();
3834 if (is4xi8vec(CompositeTy)) {
3835 Constant *CstFF = ConstantInt::get(Type::getInt32Ty(Context), 0xFF);
3836 uint32_t CstFFID = VMap[CstFF];
3837
3838 uint32_t ShiftAmountID = 0;
3839 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3840 // Handle constant index.
3841 uint64_t Idx = CI->getZExtValue();
3842 Value *ShiftAmount =
3843 ConstantInt::get(Type::getInt32Ty(Context), Idx * 8);
3844 ShiftAmountID = VMap[ShiftAmount];
3845 } else {
3846 // Handle variable index.
3847 SPIRVOperandList TmpOps;
3848
3849 uint32_t TmpResTyID = lookupType(Type::getInt32Ty(Context));
3850 SPIRVOperand *TmpResTyIDOp =
3851 new SPIRVOperand(SPIRVOperandType::NUMBERID, TmpResTyID);
3852 TmpOps.push_back(TmpResTyIDOp);
3853
3854 uint32_t IdxID = VMap[I.getOperand(2)];
3855 SPIRVOperand *TmpOp0IDOp =
3856 new SPIRVOperand(SPIRVOperandType::NUMBERID, IdxID);
3857 TmpOps.push_back(TmpOp0IDOp);
3858
3859 ConstantInt *Cst8 = ConstantInt::get(Type::getInt32Ty(Context), 8);
3860 uint32_t Cst8ID = VMap[Cst8];
3861 SPIRVOperand *TmpOp1IDOp =
3862 new SPIRVOperand(SPIRVOperandType::NUMBERID, Cst8ID);
3863 TmpOps.push_back(TmpOp1IDOp);
3864
3865 ShiftAmountID = nextID;
3866
3867 SPIRVInstruction *TmpInst =
3868 new SPIRVInstruction(5, spv::OpIMul, nextID++, TmpOps);
3869 SPIRVInstList.push_back(TmpInst);
3870 }
3871
3872 //
3873 // Generate mask operations.
3874 //
3875
3876 // ShiftLeft mask according to index of insertelement.
3877 SPIRVOperandList Ops;
3878
3879 uint32_t ResTyID = lookupType(CompositeTy);
3880 SPIRVOperand *ResTyIDOp =
3881 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3882 Ops.push_back(ResTyIDOp);
3883
3884 uint32_t Op0ID = CstFFID;
3885 SPIRVOperand *Op0IDOp =
3886 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3887 Ops.push_back(Op0IDOp);
3888
3889 uint32_t Op1ID = ShiftAmountID;
3890 SPIRVOperand *Op1IDOp =
3891 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3892 Ops.push_back(Op1IDOp);
3893
3894 uint32_t MaskID = nextID;
3895
3896 SPIRVInstruction *Inst =
3897 new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
3898 SPIRVInstList.push_back(Inst);
3899
3900 // Inverse mask.
3901 Ops.clear();
3902
3903 Ops.push_back(ResTyIDOp);
3904
3905 Op0ID = MaskID;
3906 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3907 Ops.push_back(Op0IDOp);
3908
3909 uint32_t InvMaskID = nextID;
3910
3911 Inst = new SPIRVInstruction(4, spv::OpLogicalNot, nextID++, Ops);
3912 SPIRVInstList.push_back(Inst);
3913
3914 // Apply mask.
3915 Ops.clear();
3916
3917 Ops.push_back(ResTyIDOp);
3918
3919 Op0ID = VMap[I.getOperand(0)];
3920 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3921 Ops.push_back(Op0IDOp);
3922
3923 Op1ID = InvMaskID;
3924 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3925 Ops.push_back(Op1IDOp);
3926
3927 uint32_t OrgValID = nextID;
3928
3929 Inst = new SPIRVInstruction(5, spv::OpBitwiseAnd, nextID++, Ops);
3930 SPIRVInstList.push_back(Inst);
3931
3932 // Create correct value according to index of insertelement.
3933 Ops.clear();
3934
3935 Ops.push_back(ResTyIDOp);
3936
3937 Op0ID = VMap[I.getOperand(1)];
3938 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3939 Ops.push_back(Op0IDOp);
3940
3941 Op1ID = ShiftAmountID;
3942 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3943 Ops.push_back(Op1IDOp);
3944
3945 uint32_t InsertValID = nextID;
3946
3947 Inst = new SPIRVInstruction(5, spv::OpShiftLeftLogical, nextID++, Ops);
3948 SPIRVInstList.push_back(Inst);
3949
3950 // Insert value to original value.
3951 Ops.clear();
3952
3953 Ops.push_back(ResTyIDOp);
3954
3955 Op0ID = OrgValID;
3956 Op0IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
3957 Ops.push_back(Op0IDOp);
3958
3959 Op1ID = InsertValID;
3960 Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
3961 Ops.push_back(Op1IDOp);
3962
3963 Inst = new SPIRVInstruction(5, spv::OpBitwiseOr, nextID++, Ops);
3964 SPIRVInstList.push_back(Inst);
3965
3966 break;
3967 }
3968
3969 // Ops[0] = Result Type ID
3970 // Ops[1] = Object ID
3971 // Ops[2] = Composite ID
3972 // Ops[3] ... Ops[n] = Indexes (Literal Number)
3973 SPIRVOperandList Ops;
3974
3975 uint32_t ResTyID = lookupType(I.getType());
3976 SPIRVOperand *ResTyIDOp =
3977 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
3978 Ops.push_back(ResTyIDOp);
3979
3980 uint32_t ObjectID = VMap[I.getOperand(1)];
3981 SPIRVOperand *ObjectIDOp =
3982 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
3983 Ops.push_back(ObjectIDOp);
3984
3985 uint32_t CompositeID = VMap[I.getOperand(0)];
3986 SPIRVOperand *CompositeIDOp =
3987 new SPIRVOperand(SPIRVOperandType::NUMBERID, CompositeID);
3988 Ops.push_back(CompositeIDOp);
3989
3990 spv::Op Opcode = spv::OpCompositeInsert;
3991 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2))) {
3992 std::vector<uint32_t> LiteralNum;
3993 assert(CI->getZExtValue() < UINT32_MAX);
3994 LiteralNum.push_back(static_cast<uint32_t>(CI->getZExtValue()));
3995 SPIRVOperand *Indexes =
3996 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
3997 Ops.push_back(Indexes);
3998 } else {
3999 uint32_t IndexID = VMap[I.getOperand(1)];
4000 SPIRVOperand *IndexIDOp =
4001 new SPIRVOperand(SPIRVOperandType::NUMBERID, IndexID);
4002 Ops.push_back(IndexIDOp);
4003 Opcode = spv::OpVectorInsertDynamic;
4004 }
4005
4006 uint16_t WordCount = 6;
4007 SPIRVInstruction *Inst =
4008 new SPIRVInstruction(WordCount, Opcode, nextID++, Ops);
4009 SPIRVInstList.push_back(Inst);
4010 break;
4011 }
4012 case Instruction::ShuffleVector: {
4013 // Ops[0] = Result Type ID
4014 // Ops[1] = Vector 1 ID
4015 // Ops[2] = Vector 2 ID
4016 // Ops[3] ... Ops[n] = Components (Literal Number)
4017 SPIRVOperandList Ops;
4018
4019 uint32_t ResTyID = lookupType(I.getType());
4020 SPIRVOperand *ResTyIDOp =
4021 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4022 Ops.push_back(ResTyIDOp);
4023
4024 uint32_t Vec1ID = VMap[I.getOperand(0)];
4025 SPIRVOperand *Vec1IDOp =
4026 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec1ID);
4027 Ops.push_back(Vec1IDOp);
4028
4029 uint32_t Vec2ID = VMap[I.getOperand(1)];
4030 SPIRVOperand *Vec2IDOp =
4031 new SPIRVOperand(SPIRVOperandType::NUMBERID, Vec2ID);
4032 Ops.push_back(Vec2IDOp);
4033
4034 uint64_t NumElements = 0;
4035 if (Constant *Cst = dyn_cast<Constant>(I.getOperand(2))) {
4036 NumElements = cast<VectorType>(Cst->getType())->getNumElements();
4037
4038 if (Cst->isNullValue()) {
4039 for (unsigned i = 0; i < NumElements; i++) {
4040 std::vector<uint32_t> LiteralNum;
4041 LiteralNum.push_back(0);
4042 SPIRVOperand *Component =
4043 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4044 Ops.push_back(Component);
4045 }
4046 } else if (const ConstantDataSequential *CDS =
4047 dyn_cast<ConstantDataSequential>(Cst)) {
4048 for (unsigned i = 0; i < CDS->getNumElements(); i++) {
4049 std::vector<uint32_t> LiteralNum;
4050 assert(CDS->getElementAsInteger(i) < UINT32_MAX);
4051 LiteralNum.push_back(
4052 static_cast<uint32_t>(CDS->getElementAsInteger(i)));
4053 SPIRVOperand *Component =
4054 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4055 Ops.push_back(Component);
4056 }
4057 } else if (const ConstantVector *CV = dyn_cast<ConstantVector>(Cst)) {
4058 for (unsigned i = 0; i < CV->getNumOperands(); i++) {
4059 auto Op = CV->getOperand(i);
4060
4061 uint32_t literal = 0;
4062
4063 if (auto CI = dyn_cast<ConstantInt>(Op)) {
4064 literal = static_cast<uint32_t>(CI->getZExtValue());
4065 } else if (auto UI = dyn_cast<UndefValue>(Op)) {
4066 literal = 0xFFFFFFFFu;
4067 } else {
4068 Op->print(errs());
4069 llvm_unreachable("Unsupported element in ConstantVector!");
4070 }
4071
4072 std::vector<uint32_t> LiteralNum;
4073 LiteralNum.push_back(literal);
4074 SPIRVOperand *Component =
4075 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4076 Ops.push_back(Component);
4077 }
4078 } else {
4079 Cst->print(errs());
4080 llvm_unreachable("Unsupported constant mask in ShuffleVector!");
4081 }
4082 }
4083
4084 uint16_t WordCount = static_cast<uint16_t>(5 + NumElements);
4085 SPIRVInstruction *Inst =
4086 new SPIRVInstruction(WordCount, spv::OpVectorShuffle, nextID++, Ops);
4087 SPIRVInstList.push_back(Inst);
4088 break;
4089 }
4090 case Instruction::ICmp:
4091 case Instruction::FCmp: {
4092 CmpInst *CmpI = cast<CmpInst>(&I);
4093
4094 // Ops[0] = Result Type ID
4095 // Ops[1] = Operand 1 ID
4096 // Ops[2] = Operand 2 ID
4097 SPIRVOperandList Ops;
4098
4099 uint32_t ResTyID = lookupType(CmpI->getType());
4100 SPIRVOperand *ResTyIDOp =
4101 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4102 Ops.push_back(ResTyIDOp);
4103
David Netod4ca2e62017-07-06 18:47:35 -04004104 // Pointer equality is invalid.
4105 Type* ArgTy = CmpI->getOperand(0)->getType();
4106 if (isa<PointerType>(ArgTy)) {
4107 CmpI->print(errs());
4108 std::string name = I.getParent()->getParent()->getName();
4109 errs()
4110 << "\nPointer equality test is not supported by SPIR-V for Vulkan, "
4111 << "in function " << name << "\n";
4112 llvm_unreachable("Pointer equality check is invalid");
4113 break;
4114 }
4115
David Neto22f144c2017-06-12 14:26:21 -04004116 uint32_t Op1ID = VMap[CmpI->getOperand(0)];
4117 SPIRVOperand *Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op1ID);
4118 Ops.push_back(Op1IDOp);
4119
4120 uint32_t Op2ID = VMap[CmpI->getOperand(1)];
4121 SPIRVOperand *Op2IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, Op2ID);
4122 Ops.push_back(Op2IDOp);
4123
4124 spv::Op Opcode = GetSPIRVCmpOpcode(CmpI);
4125 SPIRVInstruction *Inst = new SPIRVInstruction(5, Opcode, nextID++, Ops);
4126 SPIRVInstList.push_back(Inst);
4127 break;
4128 }
4129 case Instruction::Br: {
4130 // Branch instrucion is deferred because it needs label's ID. Record slot's
4131 // location on SPIRVInstructionList.
4132 DeferredInsts.push_back(
4133 std::make_tuple(&I, --SPIRVInstList.end(), 0 /* No id */));
4134 break;
4135 }
4136 case Instruction::Switch: {
4137 I.print(errs());
4138 llvm_unreachable("Unsupported instruction???");
4139 break;
4140 }
4141 case Instruction::IndirectBr: {
4142 I.print(errs());
4143 llvm_unreachable("Unsupported instruction???");
4144 break;
4145 }
4146 case Instruction::PHI: {
4147 // Branch instrucion is deferred because it needs label's ID. Record slot's
4148 // location on SPIRVInstructionList.
4149 DeferredInsts.push_back(
4150 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4151 break;
4152 }
4153 case Instruction::Alloca: {
4154 //
4155 // Generate OpVariable.
4156 //
4157 // Ops[0] : Result Type ID
4158 // Ops[1] : Storage Class
4159 SPIRVOperandList Ops;
4160
4161 Type *ResTy = I.getType();
4162 uint32_t ResTyID = lookupType(ResTy);
4163 SPIRVOperand *ResTyOp =
4164 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4165 Ops.push_back(ResTyOp);
4166
4167 spv::StorageClass StorageClass = spv::StorageClassFunction;
4168 SPIRVOperand *StorageClassOp =
4169 new SPIRVOperand(SPIRVOperandType::NUMBERID, StorageClass);
4170 Ops.push_back(StorageClassOp);
4171
4172 SPIRVInstruction *Inst =
4173 new SPIRVInstruction(4, spv::OpVariable, nextID++, Ops);
4174 SPIRVInstList.push_back(Inst);
4175 break;
4176 }
4177 case Instruction::Load: {
4178 LoadInst *LD = cast<LoadInst>(&I);
4179 //
4180 // Generate OpLoad.
4181 //
4182
4183 // Ops[0] = Result Type ID
4184 // Ops[1] = Pointer ID
4185 // Ops[2] ... Ops[n] = Optional Memory Access
4186 //
4187 // TODO: Do we need to implement Optional Memory Access???
4188 SPIRVOperandList Ops;
4189
4190 uint32_t ResTyID = lookupType(LD->getType());
4191 SPIRVOperand *ResTyIDOp =
4192 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4193 Ops.push_back(ResTyIDOp);
4194
4195 uint32_t PointerID = VMap[LD->getPointerOperand()];
4196 SPIRVOperand *PointerIDOp =
4197 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4198 Ops.push_back(PointerIDOp);
4199
4200 SPIRVInstruction *Inst =
4201 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4202 SPIRVInstList.push_back(Inst);
4203 break;
4204 }
4205 case Instruction::Store: {
4206 StoreInst *ST = cast<StoreInst>(&I);
4207 //
4208 // Generate OpStore.
4209 //
4210
4211 // Ops[0] = Pointer ID
4212 // Ops[1] = Object ID
4213 // Ops[2] ... Ops[n] = Optional Memory Access (later???)
4214 //
4215 // TODO: Do we need to implement Optional Memory Access???
4216 SPIRVOperand *Ops[2] = {new SPIRVOperand(SPIRVOperandType::NUMBERID,
4217 VMap[ST->getPointerOperand()]),
4218 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4219 VMap[ST->getValueOperand()])};
4220
4221 SPIRVInstruction *Inst =
4222 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4223 SPIRVInstList.push_back(Inst);
4224 break;
4225 }
4226 case Instruction::AtomicCmpXchg: {
4227 I.print(errs());
4228 llvm_unreachable("Unsupported instruction???");
4229 break;
4230 }
4231 case Instruction::AtomicRMW: {
4232 I.print(errs());
4233 llvm_unreachable("Unsupported instruction???");
4234 break;
4235 }
4236 case Instruction::Fence: {
4237 I.print(errs());
4238 llvm_unreachable("Unsupported instruction???");
4239 break;
4240 }
4241 case Instruction::Call: {
4242 CallInst *Call = dyn_cast<CallInst>(&I);
4243 Function *Callee = Call->getCalledFunction();
4244
4245 // Sampler initializers become a load of the corresponding sampler.
4246 if (Callee->getName().equals("__translate_sampler_initializer")) {
4247 // Check that the sampler map was definitely used though.
4248 if (0 == getSamplerMap().size()) {
4249 llvm_unreachable("Sampler literal in source without sampler map!");
4250 }
4251
4252 SPIRVOperandList Ops;
4253
4254 uint32_t ResTyID = lookupType(SamplerTy->getPointerElementType());
4255 SPIRVOperand *ResTyIDOp =
4256 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4257 Ops.push_back(ResTyIDOp);
4258
4259 uint32_t PointerID = VMap[Call];
4260 SPIRVOperand *PointerIDOp =
4261 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4262 Ops.push_back(PointerIDOp);
4263
4264 VMap[Call] = nextID;
4265 SPIRVInstruction *Inst =
4266 new SPIRVInstruction(4, spv::OpLoad, nextID++, Ops);
4267 SPIRVInstList.push_back(Inst);
4268
4269 break;
4270 }
4271
4272 if (Callee->getName().startswith("spirv.atomic")) {
4273 spv::Op opcode = StringSwitch<spv::Op>(Callee->getName())
4274 .Case("spirv.atomic_add", spv::OpAtomicIAdd)
4275 .Case("spirv.atomic_sub", spv::OpAtomicISub)
4276 .Case("spirv.atomic_exchange", spv::OpAtomicExchange)
4277 .Case("spirv.atomic_inc", spv::OpAtomicIIncrement)
4278 .Case("spirv.atomic_dec", spv::OpAtomicIDecrement)
4279 .Case("spirv.atomic_compare_exchange",
4280 spv::OpAtomicCompareExchange)
4281 .Case("spirv.atomic_umin", spv::OpAtomicUMin)
4282 .Case("spirv.atomic_smin", spv::OpAtomicSMin)
4283 .Case("spirv.atomic_umax", spv::OpAtomicUMax)
4284 .Case("spirv.atomic_smax", spv::OpAtomicSMax)
4285 .Case("spirv.atomic_and", spv::OpAtomicAnd)
4286 .Case("spirv.atomic_or", spv::OpAtomicOr)
4287 .Case("spirv.atomic_xor", spv::OpAtomicXor)
4288 .Default(spv::OpNop);
4289
4290 //
4291 // Generate OpAtomic*.
4292 //
4293 SPIRVOperandList Ops;
4294
4295 uint32_t TyID = lookupType(I.getType());
4296 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4297
4298 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4299 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4300 VMap[Call->getArgOperand(i)]));
4301 }
4302
4303 VMap[&I] = nextID;
4304
4305 SPIRVInstruction *Inst = new SPIRVInstruction(
4306 static_cast<uint16_t>(2 + Ops.size()), opcode, nextID++, Ops);
4307 SPIRVInstList.push_back(Inst);
4308 break;
4309 }
4310
4311 if (Callee->getName().startswith("_Z3dot")) {
4312 // If the argument is a vector type, generate OpDot
4313 if (Call->getArgOperand(0)->getType()->isVectorTy()) {
4314 //
4315 // Generate OpDot.
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::OpDot, nextID++, Ops);
4331 SPIRVInstList.push_back(Inst);
4332 } else {
4333 //
4334 // Generate OpFMul.
4335 //
4336 SPIRVOperandList Ops;
4337
4338 uint32_t TyID = lookupType(I.getType());
4339 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID));
4340
4341 for (unsigned i = 0; i < Call->getNumArgOperands(); i++) {
4342 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
4343 VMap[Call->getArgOperand(i)]));
4344 }
4345
4346 VMap[&I] = nextID;
4347
4348 SPIRVInstruction *Inst = new SPIRVInstruction(
4349 static_cast<uint16_t>(2 + Ops.size()), spv::OpFMul, nextID++, Ops);
4350 SPIRVInstList.push_back(Inst);
4351 }
4352 break;
4353 }
4354
4355 // spirv.store_null.* intrinsics become OpStore's.
4356 if (Callee->getName().startswith("spirv.store_null")) {
4357 //
4358 // Generate OpStore.
4359 //
4360
4361 // Ops[0] = Pointer ID
4362 // Ops[1] = Object ID
4363 // Ops[2] ... Ops[n]
4364 SPIRVOperandList Ops;
4365
4366 uint32_t PointerID = VMap[Call->getArgOperand(0)];
4367 SPIRVOperand *PointerIDOp =
4368 new SPIRVOperand(SPIRVOperandType::NUMBERID, PointerID);
4369 Ops.push_back(PointerIDOp);
4370
4371 uint32_t ObjectID = VMap[Call->getArgOperand(1)];
4372 SPIRVOperand *ObjectIDOp =
4373 new SPIRVOperand(SPIRVOperandType::NUMBERID, ObjectID);
4374 Ops.push_back(ObjectIDOp);
4375
4376 SPIRVInstruction *Inst =
4377 new SPIRVInstruction(3, spv::OpStore, 0 /* No id */, Ops);
4378 SPIRVInstList.push_back(Inst);
4379
4380 break;
4381 }
4382
4383 // spirv.copy_memory.* intrinsics become OpMemoryMemory's.
4384 if (Callee->getName().startswith("spirv.copy_memory")) {
4385 //
4386 // Generate OpCopyMemory.
4387 //
4388
4389 // Ops[0] = Dst ID
4390 // Ops[1] = Src ID
4391 // Ops[2] = Memory Access
4392 // Ops[3] = Alignment
4393
4394 auto IsVolatile =
4395 dyn_cast<ConstantInt>(Call->getArgOperand(3))->getZExtValue() != 0;
4396
4397 auto VolatileMemoryAccess = (IsVolatile) ? spv::MemoryAccessVolatileMask
4398 : spv::MemoryAccessMaskNone;
4399
4400 auto MemoryAccess = VolatileMemoryAccess | spv::MemoryAccessAlignedMask;
4401
4402 auto Alignment =
4403 dyn_cast<ConstantInt>(Call->getArgOperand(2))->getZExtValue();
4404
4405 SPIRVOperand *Ops[4] = {
4406 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4407 VMap[Call->getArgOperand(0)]),
4408 new SPIRVOperand(SPIRVOperandType::NUMBERID,
4409 VMap[Call->getArgOperand(1)]),
4410 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, MemoryAccess),
4411 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER,
4412 static_cast<uint32_t>(Alignment))};
4413
4414 SPIRVInstruction *Inst =
4415 new SPIRVInstruction(5, spv::OpCopyMemory, 0 /* No id */, Ops);
4416
4417 SPIRVInstList.push_back(Inst);
4418
4419 break;
4420 }
4421
4422 // Nothing to do for abs with uint. Map abs's operand ID to VMap for abs
4423 // with unit.
4424 if (Callee->getName().equals("_Z3absj") ||
4425 Callee->getName().equals("_Z3absDv2_j") ||
4426 Callee->getName().equals("_Z3absDv3_j") ||
4427 Callee->getName().equals("_Z3absDv4_j")) {
4428 VMap[&I] = VMap[Call->getOperand(0)];
4429 break;
4430 }
4431
4432 // barrier is converted to OpControlBarrier
4433 if (Callee->getName().equals("__spirv_control_barrier")) {
4434 //
4435 // Generate OpControlBarrier.
4436 //
4437 // Ops[0] = Execution Scope ID
4438 // Ops[1] = Memory Scope ID
4439 // Ops[2] = Memory Semantics ID
4440 //
4441 Value *ExecutionScope = Call->getArgOperand(0);
4442 Value *MemoryScope = Call->getArgOperand(1);
4443 Value *MemorySemantics = Call->getArgOperand(2);
4444
4445 SPIRVOperand *Ops[3] = {
4446 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[ExecutionScope]),
4447 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemoryScope]),
4448 new SPIRVOperand(SPIRVOperandType::NUMBERID, VMap[MemorySemantics])};
4449
4450 SPIRVInstList.push_back(
4451 new SPIRVInstruction(4, spv::OpControlBarrier, 0 /* No id */, Ops));
4452 break;
4453 }
4454
4455 // memory barrier is converted to OpMemoryBarrier
4456 if (Callee->getName().equals("__spirv_memory_barrier")) {
4457 //
4458 // Generate OpMemoryBarrier.
4459 //
4460 // Ops[0] = Memory Scope ID
4461 // Ops[1] = Memory Semantics ID
4462 //
4463 SPIRVOperandList Ops;
4464
4465 Value *MemoryScope = Call->getArgOperand(0);
4466 Value *MemorySemantics = Call->getArgOperand(1);
4467
4468 uint32_t MemoryScopeID = VMap[MemoryScope];
4469 Ops.push_back(
4470 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemoryScopeID));
4471
4472 uint32_t MemorySemanticsID = VMap[MemorySemantics];
4473 Ops.push_back(
4474 new SPIRVOperand(SPIRVOperandType::NUMBERID, MemorySemanticsID));
4475
4476 SPIRVInstruction *Inst =
4477 new SPIRVInstruction(3, spv::OpMemoryBarrier, 0 /* No id */, Ops);
4478 SPIRVInstList.push_back(Inst);
4479 break;
4480 }
4481
4482 // isinf is converted to OpIsInf
4483 if (Callee->getName().equals("__spirv_isinff") ||
4484 Callee->getName().equals("__spirv_isinfDv2_f") ||
4485 Callee->getName().equals("__spirv_isinfDv3_f") ||
4486 Callee->getName().equals("__spirv_isinfDv4_f")) {
4487 //
4488 // Generate OpIsInf.
4489 //
4490 // Ops[0] = Result Type ID
4491 // Ops[1] = X ID
4492 //
4493 SPIRVOperandList Ops;
4494
4495 uint32_t TyID = lookupType(I.getType());
4496 SPIRVOperand *ResTyIDOp =
4497 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4498 Ops.push_back(ResTyIDOp);
4499
4500 uint32_t XID = VMap[Call->getArgOperand(0)];
4501 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4502
4503 VMap[&I] = nextID;
4504
4505 SPIRVInstruction *Inst =
4506 new SPIRVInstruction(4, spv::OpIsInf, nextID++, Ops);
4507 SPIRVInstList.push_back(Inst);
4508 break;
4509 }
4510
4511 // isnan is converted to OpIsNan
4512 if (Callee->getName().equals("__spirv_isnanf") ||
4513 Callee->getName().equals("__spirv_isnanDv2_f") ||
4514 Callee->getName().equals("__spirv_isnanDv3_f") ||
4515 Callee->getName().equals("__spirv_isnanDv4_f")) {
4516 //
4517 // Generate OpIsInf.
4518 //
4519 // Ops[0] = Result Type ID
4520 // Ops[1] = X ID
4521 //
4522 SPIRVOperandList Ops;
4523
4524 uint32_t TyID = lookupType(I.getType());
4525 SPIRVOperand *ResTyIDOp =
4526 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4527 Ops.push_back(ResTyIDOp);
4528
4529 uint32_t XID = VMap[Call->getArgOperand(0)];
4530 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, XID));
4531
4532 VMap[&I] = nextID;
4533
4534 SPIRVInstruction *Inst =
4535 new SPIRVInstruction(4, spv::OpIsNan, nextID++, Ops);
4536 SPIRVInstList.push_back(Inst);
4537 break;
4538 }
4539
4540 // all is converted to OpAll
4541 if (Callee->getName().equals("__spirv_allDv2_i") ||
4542 Callee->getName().equals("__spirv_allDv3_i") ||
4543 Callee->getName().equals("__spirv_allDv4_i")) {
4544 //
4545 // Generate OpAll.
4546 //
4547 // Ops[0] = Result Type ID
4548 // Ops[1] = Vector ID
4549 //
4550 SPIRVOperandList Ops;
4551
4552 uint32_t TyID = lookupType(I.getType());
4553 SPIRVOperand *ResTyIDOp =
4554 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4555 Ops.push_back(ResTyIDOp);
4556
4557 uint32_t VectorID = VMap[Call->getArgOperand(0)];
4558 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
4559
4560 VMap[&I] = nextID;
4561
4562 SPIRVInstruction *Inst =
4563 new SPIRVInstruction(4, spv::OpAll, nextID++, Ops);
4564 SPIRVInstList.push_back(Inst);
4565 break;
4566 }
4567
4568 // any is converted to OpAny
4569 if (Callee->getName().equals("__spirv_anyDv2_i") ||
4570 Callee->getName().equals("__spirv_anyDv3_i") ||
4571 Callee->getName().equals("__spirv_anyDv4_i")) {
4572 //
4573 // Generate OpAny.
4574 //
4575 // Ops[0] = Result Type ID
4576 // Ops[1] = Vector ID
4577 //
4578 SPIRVOperandList Ops;
4579
4580 uint32_t TyID = lookupType(I.getType());
4581 SPIRVOperand *ResTyIDOp =
4582 new SPIRVOperand(SPIRVOperandType::NUMBERID, TyID);
4583 Ops.push_back(ResTyIDOp);
4584
4585 uint32_t VectorID = VMap[Call->getArgOperand(0)];
4586 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID, VectorID));
4587
4588 VMap[&I] = nextID;
4589
4590 SPIRVInstruction *Inst =
4591 new SPIRVInstruction(4, spv::OpAny, nextID++, Ops);
4592 SPIRVInstList.push_back(Inst);
4593 break;
4594 }
4595
4596 // read_image is converted to OpSampledImage and OpImageSampleExplicitLod.
4597 // Additionally, OpTypeSampledImage is generated.
4598 if (Callee->getName().equals(
4599 "_Z11read_imagef14ocl_image2d_ro11ocl_samplerDv2_f") ||
4600 Callee->getName().equals(
4601 "_Z11read_imagef14ocl_image3d_ro11ocl_samplerDv4_f")) {
4602 //
4603 // Generate OpSampledImage.
4604 //
4605 // Ops[0] = Result Type ID
4606 // Ops[1] = Image ID
4607 // Ops[2] = Sampler ID
4608 //
4609 SPIRVOperandList Ops;
4610
4611 Value *Image = Call->getArgOperand(0);
4612 Value *Sampler = Call->getArgOperand(1);
4613 Value *Coordinate = Call->getArgOperand(2);
4614
4615 TypeMapType &OpImageTypeMap = getImageTypeMap();
4616 Type *ImageTy = Image->getType()->getPointerElementType();
4617 uint32_t ImageTyID = OpImageTypeMap[ImageTy];
4618 SPIRVOperand *ResTyIDOp =
4619 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageTyID);
4620 Ops.push_back(ResTyIDOp);
4621
4622 uint32_t ImageID = VMap[Image];
4623 SPIRVOperand *ImageIDOp =
4624 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
4625 Ops.push_back(ImageIDOp);
4626
4627 uint32_t SamplerID = VMap[Sampler];
4628 SPIRVOperand *SamplerIDOp =
4629 new SPIRVOperand(SPIRVOperandType::NUMBERID, SamplerID);
4630 Ops.push_back(SamplerIDOp);
4631
4632 uint32_t SampledImageID = nextID;
4633
4634 SPIRVInstruction *Inst =
4635 new SPIRVInstruction(5, spv::OpSampledImage, nextID++, Ops);
4636 SPIRVInstList.push_back(Inst);
4637
4638 //
4639 // Generate OpImageSampleExplicitLod.
4640 //
4641 // Ops[0] = Result Type ID
4642 // Ops[1] = Sampled Image ID
4643 // Ops[2] = Coordinate ID
4644 // Ops[3] = Image Operands Type ID
4645 // Ops[4] ... Ops[n] = Operands ID
4646 //
4647 Ops.clear();
4648
4649 uint32_t RetTyID = lookupType(Call->getType());
4650 ResTyIDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID, RetTyID);
4651 Ops.push_back(ResTyIDOp);
4652
4653 SPIRVOperand *SampledImageIDOp =
4654 new SPIRVOperand(SPIRVOperandType::NUMBERID, SampledImageID);
4655 Ops.push_back(SampledImageIDOp);
4656
4657 uint32_t CoordinateID = VMap[Coordinate];
4658 SPIRVOperand *CoordinateIDOp =
4659 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
4660 Ops.push_back(CoordinateIDOp);
4661
4662 std::vector<uint32_t> LiteralNum;
4663 LiteralNum.push_back(spv::ImageOperandsLodMask);
4664 SPIRVOperand *ImageOperandTyIDOp =
4665 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
4666 Ops.push_back(ImageOperandTyIDOp);
4667
4668 Constant *CstFP0 = ConstantFP::get(Context, APFloat(0.0f));
4669 uint32_t OperandID = VMap[CstFP0];
4670 SPIRVOperand *OperandIDOp =
4671 new SPIRVOperand(SPIRVOperandType::NUMBERID, OperandID);
4672 Ops.push_back(OperandIDOp);
4673
4674 VMap[&I] = nextID;
4675
4676 Inst =
4677 new SPIRVInstruction(7, spv::OpImageSampleExplicitLod, nextID++, Ops);
4678 SPIRVInstList.push_back(Inst);
4679 break;
4680 }
4681
4682 // write_imagef is mapped to OpImageWrite.
4683 if (Callee->getName().equals(
4684 "_Z12write_imagef14ocl_image2d_woDv2_iDv4_f") ||
4685 Callee->getName().equals(
4686 "_Z12write_imagef14ocl_image3d_woDv4_iDv4_f")) {
4687 //
4688 // Generate OpImageWrite.
4689 //
4690 // Ops[0] = Image ID
4691 // Ops[1] = Coordinate ID
4692 // Ops[2] = Texel ID
4693 // Ops[3] = (Optional) Image Operands Type (Literal Number)
4694 // Ops[4] ... Ops[n] = (Optional) Operands ID
4695 //
4696 SPIRVOperandList Ops;
4697
4698 Value *Image = Call->getArgOperand(0);
4699 Value *Coordinate = Call->getArgOperand(1);
4700 Value *Texel = Call->getArgOperand(2);
4701
4702 uint32_t ImageID = VMap[Image];
4703 SPIRVOperand *ImageIDOp =
4704 new SPIRVOperand(SPIRVOperandType::NUMBERID, ImageID);
4705 Ops.push_back(ImageIDOp);
4706
4707 uint32_t CoordinateID = VMap[Coordinate];
4708 SPIRVOperand *CoordinateIDOp =
4709 new SPIRVOperand(SPIRVOperandType::NUMBERID, CoordinateID);
4710 Ops.push_back(CoordinateIDOp);
4711
4712 uint32_t TexelID = VMap[Texel];
4713 SPIRVOperand *TexelIDOp =
4714 new SPIRVOperand(SPIRVOperandType::NUMBERID, TexelID);
4715 Ops.push_back(TexelIDOp);
4716
4717 SPIRVInstruction *Inst =
4718 new SPIRVInstruction(4, spv::OpImageWrite, 0 /* No id */, Ops);
4719 SPIRVInstList.push_back(Inst);
4720 break;
4721 }
4722
4723 // Call instrucion is deferred because it needs function's ID. Record
4724 // slot's location on SPIRVInstructionList.
4725 DeferredInsts.push_back(
4726 std::make_tuple(&I, --SPIRVInstList.end(), nextID++));
4727
4728 // Check whether this call is for extend instructions.
4729 glsl::ExtInst EInst = getExtInstEnum(Callee->getName());
4730 if (EInst == glsl::ExtInstFindUMsb) {
4731 // clz needs OpExtInst and OpISub with constant 31. Increase nextID.
4732 VMap[&I] = nextID;
4733 nextID++;
4734 }
4735 break;
4736 }
4737 case Instruction::Ret: {
4738 unsigned NumOps = I.getNumOperands();
4739 if (NumOps == 0) {
4740 //
4741 // Generate OpReturn.
4742 //
4743
4744 // Empty Ops
4745 SPIRVOperandList Ops;
4746 SPIRVInstruction *Inst =
4747 new SPIRVInstruction(1, spv::OpReturn, 0 /* No id */, Ops);
4748 SPIRVInstList.push_back(Inst);
4749 } else {
4750 //
4751 // Generate OpReturnValue.
4752 //
4753
4754 // Ops[0] = Return Value ID
4755 SPIRVOperandList Ops;
4756 uint32_t RetValID = VMap[I.getOperand(0)];
4757 SPIRVOperand *RetValIDOp =
4758 new SPIRVOperand(SPIRVOperandType::NUMBERID, RetValID);
4759 Ops.push_back(RetValIDOp);
4760
4761 SPIRVInstruction *Inst =
4762 new SPIRVInstruction(2, spv::OpReturnValue, 0 /* No id */, Ops);
4763 SPIRVInstList.push_back(Inst);
4764 break;
4765 }
4766 break;
4767 }
4768 }
4769}
4770
4771void SPIRVProducerPass::GenerateFuncEpilogue() {
4772 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4773
4774 //
4775 // Generate OpFunctionEnd
4776 //
4777
4778 // Empty Ops
4779 SPIRVOperandList Ops;
4780 SPIRVInstruction *Inst =
4781 new SPIRVInstruction(1, spv::OpFunctionEnd, 0 /* No id */, Ops);
4782 SPIRVInstList.push_back(Inst);
4783}
4784
4785bool SPIRVProducerPass::is4xi8vec(Type *Ty) const {
4786 LLVMContext &Context = Ty->getContext();
4787 if (Ty->isVectorTy()) {
4788 if (Ty->getVectorElementType() == Type::getInt8Ty(Context) &&
4789 Ty->getVectorNumElements() == 4) {
4790 return true;
4791 }
4792 }
4793
4794 return false;
4795}
4796
4797void SPIRVProducerPass::HandleDeferredInstruction() {
4798 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
4799 ValueMapType &VMap = getValueMap();
4800 DeferredInstVecType &DeferredInsts = getDeferredInstVec();
4801
4802 for (auto DeferredInst = DeferredInsts.rbegin();
4803 DeferredInst != DeferredInsts.rend(); ++DeferredInst) {
4804 Value *Inst = std::get<0>(*DeferredInst);
4805 SPIRVInstructionList::iterator InsertPoint = ++std::get<1>(*DeferredInst);
4806 if (InsertPoint != SPIRVInstList.end()) {
4807 while ((*InsertPoint)->getOpcode() == spv::OpPhi) {
4808 ++InsertPoint;
4809 }
4810 }
4811
4812 if (BranchInst *Br = dyn_cast<BranchInst>(Inst)) {
4813 // Check whether basic block, which has this branch instruction, is loop
4814 // header or not. If it is loop header, generate OpLoopMerge and
4815 // OpBranchConditional.
4816 Function *Func = Br->getParent()->getParent();
4817 DominatorTree &DT =
4818 getAnalysis<DominatorTreeWrapperPass>(*Func).getDomTree();
4819 const LoopInfo &LI =
4820 getAnalysis<LoopInfoWrapperPass>(*Func).getLoopInfo();
4821
4822 BasicBlock *BrBB = Br->getParent();
4823 if (LI.isLoopHeader(BrBB)) {
4824 Value *ContinueBB = nullptr;
4825 Value *MergeBB = nullptr;
4826
4827 Loop *L = LI.getLoopFor(BrBB);
4828 MergeBB = L->getExitBlock();
4829 if (!MergeBB) {
4830 // StructurizeCFG pass converts CFG into triangle shape and the cfg
4831 // has regions with single entry/exit. As a result, loop should not
4832 // have multiple exits.
4833 llvm_unreachable("Loop has multiple exits???");
4834 }
4835
4836 if (L->isLoopLatch(BrBB)) {
4837 ContinueBB = BrBB;
4838 } else {
4839 // From SPIR-V spec 2.11, Continue Target must dominate that back-edge
4840 // block.
4841 BasicBlock *Header = L->getHeader();
4842 BasicBlock *Latch = L->getLoopLatch();
4843 for (BasicBlock *BB : L->blocks()) {
4844 if (BB == Header) {
4845 continue;
4846 }
4847
4848 // Check whether block dominates block with back-edge.
4849 if (DT.dominates(BB, Latch)) {
4850 ContinueBB = BB;
4851 }
4852 }
4853
4854 if (!ContinueBB) {
4855 llvm_unreachable("Wrong continue block from loop");
4856 }
4857 }
4858
4859 //
4860 // Generate OpLoopMerge.
4861 //
4862 // Ops[0] = Merge Block ID
4863 // Ops[1] = Continue Target ID
4864 // Ops[2] = Selection Control
4865 SPIRVOperandList Ops;
4866
4867 // StructurizeCFG pass already manipulated CFG. Just use false block of
4868 // branch instruction as merge block.
4869 uint32_t MergeBBID = VMap[MergeBB];
4870 SPIRVOperand *MergeBBIDOp =
4871 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
4872 Ops.push_back(MergeBBIDOp);
4873
4874 uint32_t ContinueBBID = VMap[ContinueBB];
4875 SPIRVOperand *ContinueBBIDOp =
4876 new SPIRVOperand(SPIRVOperandType::NUMBERID, ContinueBBID);
4877 Ops.push_back(ContinueBBIDOp);
4878
4879 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
4880 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
4881 Ops.push_back(SelectionControlOp);
4882
4883 SPIRVInstruction *MergeInst =
4884 new SPIRVInstruction(4, spv::OpLoopMerge, 0 /* No id */, Ops);
4885 SPIRVInstList.insert(InsertPoint, MergeInst);
4886
4887 } else if (Br->isConditional()) {
4888 bool HasBackEdge = false;
4889
4890 for (unsigned i = 0; i < Br->getNumSuccessors(); i++) {
4891 if (LI.isLoopHeader(Br->getSuccessor(i))) {
4892 HasBackEdge = true;
4893 }
4894 }
4895 if (!HasBackEdge) {
4896 //
4897 // Generate OpSelectionMerge.
4898 //
4899 // Ops[0] = Merge Block ID
4900 // Ops[1] = Selection Control
4901 SPIRVOperandList Ops;
4902
4903 // StructurizeCFG pass already manipulated CFG. Just use false block
4904 // of branch instruction as merge block.
4905 uint32_t MergeBBID = VMap[Br->getSuccessor(1)];
4906 SPIRVOperand *MergeBBIDOp =
4907 new SPIRVOperand(SPIRVOperandType::NUMBERID, MergeBBID);
4908 Ops.push_back(MergeBBIDOp);
4909
4910 SPIRVOperand *SelectionControlOp = new SPIRVOperand(
4911 SPIRVOperandType::NUMBERID, spv::SelectionControlMaskNone);
4912 Ops.push_back(SelectionControlOp);
4913
4914 SPIRVInstruction *MergeInst = new SPIRVInstruction(
4915 3, spv::OpSelectionMerge, 0 /* No id */, Ops);
4916 SPIRVInstList.insert(InsertPoint, MergeInst);
4917 }
4918 }
4919
4920 if (Br->isConditional()) {
4921 //
4922 // Generate OpBranchConditional.
4923 //
4924 // Ops[0] = Condition ID
4925 // Ops[1] = True Label ID
4926 // Ops[2] = False Label ID
4927 // Ops[3] ... Ops[n] = Branch weights (Literal Number)
4928 SPIRVOperandList Ops;
4929
4930 uint32_t CondID = VMap[Br->getCondition()];
4931 SPIRVOperand *CondIDOp =
4932 new SPIRVOperand(SPIRVOperandType::NUMBERID, CondID);
4933 Ops.push_back(CondIDOp);
4934
4935 uint32_t TrueBBID = VMap[Br->getSuccessor(0)];
4936 SPIRVOperand *TrueBBIDOp =
4937 new SPIRVOperand(SPIRVOperandType::NUMBERID, TrueBBID);
4938 Ops.push_back(TrueBBIDOp);
4939
4940 uint32_t FalseBBID = VMap[Br->getSuccessor(1)];
4941 SPIRVOperand *FalseBBIDOp =
4942 new SPIRVOperand(SPIRVOperandType::NUMBERID, FalseBBID);
4943 Ops.push_back(FalseBBIDOp);
4944
4945 SPIRVInstruction *BrInst = new SPIRVInstruction(
4946 4, spv::OpBranchConditional, 0 /* No id */, Ops);
4947 SPIRVInstList.insert(InsertPoint, BrInst);
4948 } else {
4949 //
4950 // Generate OpBranch.
4951 //
4952 // Ops[0] = Target Label ID
4953 SPIRVOperandList Ops;
4954
4955 uint32_t TargetID = VMap[Br->getSuccessor(0)];
4956 SPIRVOperand *TargetIDOp =
4957 new SPIRVOperand(SPIRVOperandType::NUMBERID, TargetID);
4958 Ops.push_back(TargetIDOp);
4959
4960 SPIRVInstList.insert(
4961 InsertPoint,
4962 new SPIRVInstruction(2, spv::OpBranch, 0 /* No id */, Ops));
4963 }
4964 } else if (PHINode *PHI = dyn_cast<PHINode>(Inst)) {
4965 //
4966 // Generate OpPhi.
4967 //
4968 // Ops[0] = Result Type ID
4969 // Ops[1] ... Ops[n] = (Variable ID, Parent ID) pairs
4970 SPIRVOperandList Ops;
4971
4972 uint32_t ResTyID = lookupType(PHI->getType());
4973 SPIRVOperand *ResTyIDOp =
4974 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
4975 Ops.push_back(ResTyIDOp);
4976
4977 uint16_t WordCount = 3;
4978 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
4979 uint32_t VarID = VMap[PHI->getIncomingValue(i)];
4980 SPIRVOperand *VarIDOp =
4981 new SPIRVOperand(SPIRVOperandType::NUMBERID, VarID);
4982 Ops.push_back(VarIDOp);
4983
4984 uint32_t ParentID = VMap[PHI->getIncomingBlock(i)];
4985 SPIRVOperand *ParentIDOp =
4986 new SPIRVOperand(SPIRVOperandType::NUMBERID, ParentID);
4987 Ops.push_back(ParentIDOp);
4988
4989 WordCount += 2;
4990 }
4991
4992 SPIRVInstList.insert(
4993 InsertPoint, new SPIRVInstruction(WordCount, spv::OpPhi,
4994 std::get<2>(*DeferredInst), Ops));
4995 } else if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
4996 Function *Callee = Call->getCalledFunction();
4997 glsl::ExtInst EInst = getExtInstEnum(Callee->getName());
4998
4999 if (EInst) {
5000 uint32_t &ExtInstImportID = getOpExtInstImportID();
5001
5002 //
5003 // Generate OpExtInst.
5004 //
5005
5006 // Ops[0] = Result Type ID
5007 // Ops[1] = Set ID (OpExtInstImport ID)
5008 // Ops[2] = Instruction Number (Literal Number)
5009 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5010 SPIRVOperandList Ops;
5011
5012 uint32_t ResTyID = lookupType(Call->getType());
5013 SPIRVOperand *ResTyIDOp =
5014 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5015 Ops.push_back(ResTyIDOp);
5016
5017 SPIRVOperand *SetIDOp =
5018 new SPIRVOperand(SPIRVOperandType::NUMBERID, ExtInstImportID);
5019 Ops.push_back(SetIDOp);
5020
5021 std::vector<uint32_t> LiteralNum;
5022 LiteralNum.push_back(EInst);
5023 SPIRVOperand *InstructionOp =
5024 new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, LiteralNum);
5025 Ops.push_back(InstructionOp);
5026
5027 uint16_t WordCount = 5;
5028
5029 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5030 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5031 uint32_t ArgID = VMap[Call->getOperand(i)];
5032 SPIRVOperand *ArgIDOp =
5033 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5034 Ops.push_back(ArgIDOp);
5035 WordCount++;
5036 }
5037
5038 SPIRVInstruction *ExtInst = new SPIRVInstruction(
5039 WordCount, spv::OpExtInst, std::get<2>(*DeferredInst), Ops);
5040 SPIRVInstList.insert(InsertPoint, ExtInst);
5041
5042 // clz needs OpExtInst and OpISub with constant 31.
5043 if (EInst == glsl::ExtInstFindUMsb) {
5044 LLVMContext &Context =
5045 Call->getParent()->getParent()->getParent()->getContext();
5046 //
5047 // Generate OpISub with constant 31.
5048 //
5049 // Ops[0] = Result Type ID
5050 // Ops[1] = Operand 0
5051 // Ops[2] = Operand 1
5052 Ops.clear();
5053
5054 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5055 lookupType(Call->getType())));
5056
5057 Type *IdxTy = Type::getInt32Ty(Context);
5058 Constant *Cst31 = ConstantInt::get(IdxTy, 31);
5059 uint32_t Op0ID = VMap[Cst31];
5060 SPIRVOperand *Op0IDOp =
5061 new SPIRVOperand(SPIRVOperandType::NUMBERID, Op0ID);
5062 Ops.push_back(Op0IDOp);
5063
5064 SPIRVOperand *Op1IDOp = new SPIRVOperand(SPIRVOperandType::NUMBERID,
5065 std::get<2>(*DeferredInst));
5066 Ops.push_back(Op1IDOp);
5067
5068 SPIRVInstList.insert(
5069 InsertPoint,
5070 new SPIRVInstruction(5, spv::OpISub,
5071 std::get<2>(*DeferredInst) + 1, Ops));
5072 }
5073 } else if (Callee->getName().equals("_Z8popcounti") ||
5074 Callee->getName().equals("_Z8popcountj") ||
5075 Callee->getName().equals("_Z8popcountDv2_i") ||
5076 Callee->getName().equals("_Z8popcountDv3_i") ||
5077 Callee->getName().equals("_Z8popcountDv4_i") ||
5078 Callee->getName().equals("_Z8popcountDv2_j") ||
5079 Callee->getName().equals("_Z8popcountDv3_j") ||
5080 Callee->getName().equals("_Z8popcountDv4_j")) {
5081 //
5082 // Generate OpBitCount
5083 //
5084 // Ops[0] = Result Type ID
5085 // Ops[1] = Base ID
5086 SPIRVOperand *Ops[2]{new SPIRVOperand(SPIRVOperandType::NUMBERID,
5087 lookupType(Call->getType())),
5088 new SPIRVOperand(SPIRVOperandType::NUMBERID,
5089 VMap[Call->getOperand(0)])};
5090
5091 SPIRVInstList.insert(
5092 InsertPoint, new SPIRVInstruction(4, spv::OpBitCount,
5093 std::get<2>(*DeferredInst), Ops));
5094 } else {
5095 //
5096 // Generate OpFunctionCall.
5097 //
5098
5099 // Ops[0] = Result Type ID
5100 // Ops[1] = Callee Function ID
5101 // Ops[2] ... Ops[n] = Argument 0, ... , Argument n
5102 SPIRVOperandList Ops;
5103
5104 uint32_t ResTyID = lookupType(Call->getType());
5105 SPIRVOperand *ResTyIDOp =
5106 new SPIRVOperand(SPIRVOperandType::NUMBERID, ResTyID);
5107 Ops.push_back(ResTyIDOp);
5108
5109 uint32_t CalleeID = VMap[Callee];
5110
5111 SPIRVOperand *CalleeIDOp =
5112 new SPIRVOperand(SPIRVOperandType::NUMBERID, CalleeID);
5113 Ops.push_back(CalleeIDOp);
5114
5115 uint16_t WordCount = 4;
5116
5117 FunctionType *CalleeFTy = cast<FunctionType>(Call->getFunctionType());
5118 for (unsigned i = 0; i < CalleeFTy->getNumParams(); i++) {
5119 uint32_t ArgID = VMap[Call->getOperand(i)];
5120 SPIRVOperand *ArgIDOp =
5121 new SPIRVOperand(SPIRVOperandType::NUMBERID, ArgID);
5122 Ops.push_back(ArgIDOp);
5123 WordCount++;
5124 }
5125
5126 SPIRVInstruction *CallInst = new SPIRVInstruction(
5127 WordCount, spv::OpFunctionCall, std::get<2>(*DeferredInst), Ops);
5128 SPIRVInstList.insert(InsertPoint, CallInst);
5129 }
5130 }
5131 }
5132}
5133
David Neto1a1a0582017-07-07 12:01:44 -04005134void SPIRVProducerPass::HandleDeferredDecorations(const DataLayout &DL) {
5135 // Insert ArrayStride decorations on pointer types, due to OpPtrAccessChain
5136 // instructions we generated earlier.
5137 if (getPointerTypesNeedingArrayStride().empty())
5138 return;
5139
5140 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5141 ValueMapType &VMap = getValueMap();
5142
5143 // Find an iterator pointing just past the last decoration.
5144 bool seen_decorations = false;
5145 auto DecoInsertPoint =
5146 std::find_if(SPIRVInstList.begin(), SPIRVInstList.end(),
5147 [&seen_decorations](SPIRVInstruction *Inst) -> bool {
5148 const bool is_decoration =
5149 Inst->getOpcode() == spv::OpDecorate ||
5150 Inst->getOpcode() == spv::OpMemberDecorate;
5151 if (is_decoration) {
5152 seen_decorations = true;
5153 return false;
5154 } else {
5155 return seen_decorations;
5156 }
5157 });
5158
5159 for (auto *type : getPointerTypesNeedingArrayStride()) {
5160 auto *ptrType = cast<PointerType>(type);
5161
5162 // Ops[0] = Target ID
5163 // Ops[1] = Decoration (ArrayStride)
5164 // Ops[2] = Stride number (Literal Number)
5165 SPIRVOperandList Ops;
5166
5167 Ops.push_back(
5168 new SPIRVOperand(SPIRVOperandType::NUMBERID, lookupType(ptrType)));
5169 Ops.push_back(new SPIRVOperand(SPIRVOperandType::NUMBERID,
5170 spv::DecorationArrayStride));
5171 Type *elemTy = ptrType->getElementType();
5172 // Same as DL.getIndexedOfffsetInType( elemTy, { 1 } );
5173 const unsigned stride = DL.getTypeAllocSize(elemTy);
5174 Ops.push_back(new SPIRVOperand(SPIRVOperandType::LITERAL_INTEGER, stride));
5175
5176 SPIRVInstruction *DecoInst =
5177 new SPIRVInstruction(4, spv::OpDecorate, 0 /* No id */, Ops);
5178 SPIRVInstList.insert(DecoInsertPoint, DecoInst);
5179 }
5180}
5181
David Neto22f144c2017-06-12 14:26:21 -04005182glsl::ExtInst SPIRVProducerPass::getExtInstEnum(StringRef Name) {
5183 return StringSwitch<glsl::ExtInst>(Name)
5184 .Case("_Z3absi", glsl::ExtInst::ExtInstSAbs)
5185 .Case("_Z3absDv2_i", glsl::ExtInst::ExtInstSAbs)
5186 .Case("_Z3absDv3_i", glsl::ExtInst::ExtInstSAbs)
5187 .Case("_Z3absDv4_i", glsl::ExtInst::ExtInstSAbs)
5188 .Case("_Z5clampiii", glsl::ExtInst::ExtInstSClamp)
5189 .Case("_Z5clampDv2_iS_S_", glsl::ExtInst::ExtInstSClamp)
5190 .Case("_Z5clampDv3_iS_S_", glsl::ExtInst::ExtInstSClamp)
5191 .Case("_Z5clampDv4_iS_S_", glsl::ExtInst::ExtInstSClamp)
5192 .Case("_Z5clampjjj", glsl::ExtInst::ExtInstUClamp)
5193 .Case("_Z5clampDv2_jS_S_", glsl::ExtInst::ExtInstUClamp)
5194 .Case("_Z5clampDv3_jS_S_", glsl::ExtInst::ExtInstUClamp)
5195 .Case("_Z5clampDv4_jS_S_", glsl::ExtInst::ExtInstUClamp)
5196 .Case("_Z5clampfff", glsl::ExtInst::ExtInstFClamp)
5197 .Case("_Z5clampDv2_fS_S_", glsl::ExtInst::ExtInstFClamp)
5198 .Case("_Z5clampDv3_fS_S_", glsl::ExtInst::ExtInstFClamp)
5199 .Case("_Z5clampDv4_fS_S_", glsl::ExtInst::ExtInstFClamp)
5200 .StartsWith("_Z3clz", glsl::ExtInst::ExtInstFindUMsb)
5201 .Case("_Z3maxii", glsl::ExtInst::ExtInstSMax)
5202 .Case("_Z3maxDv2_iS_", glsl::ExtInst::ExtInstSMax)
5203 .Case("_Z3maxDv3_iS_", glsl::ExtInst::ExtInstSMax)
5204 .Case("_Z3maxDv4_iS_", glsl::ExtInst::ExtInstSMax)
5205 .Case("_Z3maxjj", glsl::ExtInst::ExtInstUMax)
5206 .Case("_Z3maxDv2_jS_", glsl::ExtInst::ExtInstUMax)
5207 .Case("_Z3maxDv3_jS_", glsl::ExtInst::ExtInstUMax)
5208 .Case("_Z3maxDv4_jS_", glsl::ExtInst::ExtInstUMax)
5209 .Case("_Z3maxff", glsl::ExtInst::ExtInstFMax)
5210 .Case("_Z3maxDv2_fS_", glsl::ExtInst::ExtInstFMax)
5211 .Case("_Z3maxDv3_fS_", glsl::ExtInst::ExtInstFMax)
5212 .Case("_Z3maxDv4_fS_", glsl::ExtInst::ExtInstFMax)
5213 .StartsWith("_Z4fmax", glsl::ExtInst::ExtInstFMax)
5214 .Case("_Z3minii", glsl::ExtInst::ExtInstSMin)
5215 .Case("_Z3minDv2_iS_", glsl::ExtInst::ExtInstSMin)
5216 .Case("_Z3minDv3_iS_", glsl::ExtInst::ExtInstSMin)
5217 .Case("_Z3minDv4_iS_", glsl::ExtInst::ExtInstSMin)
5218 .Case("_Z3minjj", glsl::ExtInst::ExtInstUMin)
5219 .Case("_Z3minDv2_jS_", glsl::ExtInst::ExtInstUMin)
5220 .Case("_Z3minDv3_jS_", glsl::ExtInst::ExtInstUMin)
5221 .Case("_Z3minDv4_jS_", glsl::ExtInst::ExtInstUMin)
5222 .Case("_Z3minff", glsl::ExtInst::ExtInstFMin)
5223 .Case("_Z3minDv2_fS_", glsl::ExtInst::ExtInstFMin)
5224 .Case("_Z3minDv3_fS_", glsl::ExtInst::ExtInstFMin)
5225 .Case("_Z3minDv4_fS_", glsl::ExtInst::ExtInstFMin)
5226 .StartsWith("_Z4fmin", glsl::ExtInst::ExtInstFMin)
5227 .StartsWith("_Z7degrees", glsl::ExtInst::ExtInstDegrees)
5228 .StartsWith("_Z7radians", glsl::ExtInst::ExtInstRadians)
5229 .StartsWith("_Z3mix", glsl::ExtInst::ExtInstFMix)
5230 .StartsWith("_Z4acos", glsl::ExtInst::ExtInstAcos)
5231 .StartsWith("_Z5acosh", glsl::ExtInst::ExtInstAcosh)
5232 .StartsWith("_Z4asin", glsl::ExtInst::ExtInstAsin)
5233 .StartsWith("_Z5asinh", glsl::ExtInst::ExtInstAsinh)
5234 .StartsWith("_Z4atan", glsl::ExtInst::ExtInstAtan)
5235 .StartsWith("_Z5atan2", glsl::ExtInst::ExtInstAtan2)
5236 .StartsWith("_Z5atanh", glsl::ExtInst::ExtInstAtanh)
5237 .StartsWith("_Z4ceil", glsl::ExtInst::ExtInstCeil)
5238 .StartsWith("_Z3sin", glsl::ExtInst::ExtInstSin)
5239 .StartsWith("_Z4sinh", glsl::ExtInst::ExtInstSinh)
5240 .StartsWith("_Z8half_sin", glsl::ExtInst::ExtInstSin)
5241 .StartsWith("_Z10native_sin", glsl::ExtInst::ExtInstSin)
5242 .StartsWith("_Z3cos", glsl::ExtInst::ExtInstCos)
5243 .StartsWith("_Z4cosh", glsl::ExtInst::ExtInstCosh)
5244 .StartsWith("_Z8half_cos", glsl::ExtInst::ExtInstCos)
5245 .StartsWith("_Z10native_cos", glsl::ExtInst::ExtInstCos)
5246 .StartsWith("_Z3tan", glsl::ExtInst::ExtInstTan)
5247 .StartsWith("_Z4tanh", glsl::ExtInst::ExtInstTanh)
5248 .StartsWith("_Z8half_tan", glsl::ExtInst::ExtInstTan)
5249 .StartsWith("_Z10native_tan", glsl::ExtInst::ExtInstTan)
5250 .StartsWith("_Z3exp", glsl::ExtInst::ExtInstExp)
5251 .StartsWith("_Z8half_exp", glsl::ExtInst::ExtInstExp)
5252 .StartsWith("_Z10native_exp", glsl::ExtInst::ExtInstExp)
5253 .StartsWith("_Z4exp2", glsl::ExtInst::ExtInstExp2)
5254 .StartsWith("_Z9half_exp2", glsl::ExtInst::ExtInstExp2)
5255 .StartsWith("_Z11native_exp2", glsl::ExtInst::ExtInstExp2)
5256 .StartsWith("_Z3log", glsl::ExtInst::ExtInstLog)
5257 .StartsWith("_Z8half_log", glsl::ExtInst::ExtInstLog)
5258 .StartsWith("_Z10native_log", glsl::ExtInst::ExtInstLog)
5259 .StartsWith("_Z4log2", glsl::ExtInst::ExtInstLog2)
5260 .StartsWith("_Z9half_log2", glsl::ExtInst::ExtInstLog2)
5261 .StartsWith("_Z11native_log2", glsl::ExtInst::ExtInstLog2)
5262 .StartsWith("_Z4fabs", glsl::ExtInst::ExtInstFAbs)
5263 .StartsWith("_Z5floor", glsl::ExtInst::ExtInstFloor)
5264 .StartsWith("_Z5ldexp", glsl::ExtInst::ExtInstLdexp)
5265 .StartsWith("_Z3pow", glsl::ExtInst::ExtInstPow)
5266 .StartsWith("_Z4powr", glsl::ExtInst::ExtInstPow)
5267 .StartsWith("_Z9half_powr", glsl::ExtInst::ExtInstPow)
5268 .StartsWith("_Z11native_powr", glsl::ExtInst::ExtInstPow)
5269 .StartsWith("_Z5round", glsl::ExtInst::ExtInstRound)
5270 .StartsWith("_Z4sqrt", glsl::ExtInst::ExtInstSqrt)
5271 .StartsWith("_Z9half_sqrt", glsl::ExtInst::ExtInstSqrt)
5272 .StartsWith("_Z11native_sqrt", glsl::ExtInst::ExtInstSqrt)
5273 .StartsWith("_Z5rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5274 .StartsWith("_Z10half_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5275 .StartsWith("_Z12native_rsqrt", glsl::ExtInst::ExtInstInverseSqrt)
5276 .StartsWith("_Z5trunc", glsl::ExtInst::ExtInstTrunc)
5277 .StartsWith("_Z5frexp", glsl::ExtInst::ExtInstFrexp)
5278 .StartsWith("_Z4sign", glsl::ExtInst::ExtInstFSign)
5279 .StartsWith("_Z6length", glsl::ExtInst::ExtInstLength)
5280 .StartsWith("_Z8distance", glsl::ExtInst::ExtInstDistance)
5281 .Case("_Z5crossDv3_fS_", glsl::ExtInst::ExtInstCross)
5282 .StartsWith("_Z9normalize", glsl::ExtInst::ExtInstNormalize)
5283 .StartsWith("llvm.fmuladd.", glsl::ExtInst::ExtInstFma)
5284 .Case("spirv.unpack.v2f16", glsl::ExtInst::ExtInstUnpackHalf2x16)
5285 .Case("spirv.pack.v2f16", glsl::ExtInst::ExtInstPackHalf2x16)
5286 .Default(static_cast<glsl::ExtInst>(0));
5287}
5288
5289void SPIRVProducerPass::PrintResID(SPIRVInstruction *Inst) {
5290 out << "%" << Inst->getResultID();
5291}
5292
5293void SPIRVProducerPass::PrintOpcode(SPIRVInstruction *Inst) {
5294 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5295 out << "\t" << spv::getOpName(Opcode);
5296}
5297
5298void SPIRVProducerPass::PrintOperand(SPIRVOperand *Op) {
5299 SPIRVOperandType OpTy = Op->getType();
5300 switch (OpTy) {
5301 default: {
5302 llvm_unreachable("Unsupported SPIRV Operand Type???");
5303 break;
5304 }
5305 case SPIRVOperandType::NUMBERID: {
5306 out << "%" << Op->getNumID();
5307 break;
5308 }
5309 case SPIRVOperandType::LITERAL_STRING: {
5310 out << "\"" << Op->getLiteralStr() << "\"";
5311 break;
5312 }
5313 case SPIRVOperandType::LITERAL_INTEGER: {
5314 // TODO: Handle LiteralNum carefully.
5315 for (auto Word : Op->getLiteralNum()) {
5316 out << Word;
5317 }
5318 break;
5319 }
5320 case SPIRVOperandType::LITERAL_FLOAT: {
5321 // TODO: Handle LiteralNum carefully.
5322 for (auto Word : Op->getLiteralNum()) {
5323 APFloat APF = APFloat(APFloat::IEEEsingle(), APInt(32, Word));
5324 SmallString<8> Str;
5325 APF.toString(Str, 6, 2);
5326 out << Str;
5327 }
5328 break;
5329 }
5330 }
5331}
5332
5333void SPIRVProducerPass::PrintCapability(SPIRVOperand *Op) {
5334 spv::Capability Cap = static_cast<spv::Capability>(Op->getNumID());
5335 out << spv::getCapabilityName(Cap);
5336}
5337
5338void SPIRVProducerPass::PrintExtInst(SPIRVOperand *Op) {
5339 auto LiteralNum = Op->getLiteralNum();
5340 glsl::ExtInst Ext = static_cast<glsl::ExtInst>(LiteralNum[0]);
5341 out << glsl::getExtInstName(Ext);
5342}
5343
5344void SPIRVProducerPass::PrintAddrModel(SPIRVOperand *Op) {
5345 spv::AddressingModel AddrModel =
5346 static_cast<spv::AddressingModel>(Op->getNumID());
5347 out << spv::getAddressingModelName(AddrModel);
5348}
5349
5350void SPIRVProducerPass::PrintMemModel(SPIRVOperand *Op) {
5351 spv::MemoryModel MemModel = static_cast<spv::MemoryModel>(Op->getNumID());
5352 out << spv::getMemoryModelName(MemModel);
5353}
5354
5355void SPIRVProducerPass::PrintExecModel(SPIRVOperand *Op) {
5356 spv::ExecutionModel ExecModel =
5357 static_cast<spv::ExecutionModel>(Op->getNumID());
5358 out << spv::getExecutionModelName(ExecModel);
5359}
5360
5361void SPIRVProducerPass::PrintExecMode(SPIRVOperand *Op) {
5362 spv::ExecutionMode ExecMode = static_cast<spv::ExecutionMode>(Op->getNumID());
5363 out << spv::getExecutionModeName(ExecMode);
5364}
5365
5366void SPIRVProducerPass::PrintSourceLanguage(SPIRVOperand *Op) {
5367 spv::SourceLanguage SourceLang = static_cast<spv::SourceLanguage>(Op->getNumID());
5368 out << spv::getSourceLanguageName(SourceLang);
5369}
5370
5371void SPIRVProducerPass::PrintFuncCtrl(SPIRVOperand *Op) {
5372 spv::FunctionControlMask FuncCtrl =
5373 static_cast<spv::FunctionControlMask>(Op->getNumID());
5374 out << spv::getFunctionControlName(FuncCtrl);
5375}
5376
5377void SPIRVProducerPass::PrintStorageClass(SPIRVOperand *Op) {
5378 spv::StorageClass StClass = static_cast<spv::StorageClass>(Op->getNumID());
5379 out << getStorageClassName(StClass);
5380}
5381
5382void SPIRVProducerPass::PrintDecoration(SPIRVOperand *Op) {
5383 spv::Decoration Deco = static_cast<spv::Decoration>(Op->getNumID());
5384 out << getDecorationName(Deco);
5385}
5386
5387void SPIRVProducerPass::PrintBuiltIn(SPIRVOperand *Op) {
5388 spv::BuiltIn BIn = static_cast<spv::BuiltIn>(Op->getNumID());
5389 out << getBuiltInName(BIn);
5390}
5391
5392void SPIRVProducerPass::PrintSelectionControl(SPIRVOperand *Op) {
5393 spv::SelectionControlMask BIn =
5394 static_cast<spv::SelectionControlMask>(Op->getNumID());
5395 out << getSelectionControlName(BIn);
5396}
5397
5398void SPIRVProducerPass::PrintLoopControl(SPIRVOperand *Op) {
5399 spv::LoopControlMask BIn = static_cast<spv::LoopControlMask>(Op->getNumID());
5400 out << getLoopControlName(BIn);
5401}
5402
5403void SPIRVProducerPass::PrintDimensionality(SPIRVOperand *Op) {
5404 spv::Dim DIM = static_cast<spv::Dim>(Op->getNumID());
5405 out << getDimName(DIM);
5406}
5407
5408void SPIRVProducerPass::PrintImageFormat(SPIRVOperand *Op) {
5409 spv::ImageFormat Format = static_cast<spv::ImageFormat>(Op->getNumID());
5410 out << getImageFormatName(Format);
5411}
5412
5413void SPIRVProducerPass::PrintMemoryAccess(SPIRVOperand *Op) {
5414 out << spv::getMemoryAccessName(
5415 static_cast<spv::MemoryAccessMask>(Op->getNumID()));
5416}
5417
5418void SPIRVProducerPass::PrintImageOperandsType(SPIRVOperand *Op) {
5419 auto LiteralNum = Op->getLiteralNum();
5420 spv::ImageOperandsMask Type =
5421 static_cast<spv::ImageOperandsMask>(LiteralNum[0]);
5422 out << getImageOperandsName(Type);
5423}
5424
5425void SPIRVProducerPass::WriteSPIRVAssembly() {
5426 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5427
5428 for (auto Inst : SPIRVInstList) {
5429 SPIRVOperandList Ops = Inst->getOperands();
5430 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5431
5432 switch (Opcode) {
5433 default: {
5434 llvm_unreachable("Unsupported SPIRV instruction");
5435 break;
5436 }
5437 case spv::OpCapability: {
5438 // Ops[0] = Capability
5439 PrintOpcode(Inst);
5440 out << " ";
5441 PrintCapability(Ops[0]);
5442 out << "\n";
5443 break;
5444 }
5445 case spv::OpMemoryModel: {
5446 // Ops[0] = Addressing Model
5447 // Ops[1] = Memory Model
5448 PrintOpcode(Inst);
5449 out << " ";
5450 PrintAddrModel(Ops[0]);
5451 out << " ";
5452 PrintMemModel(Ops[1]);
5453 out << "\n";
5454 break;
5455 }
5456 case spv::OpEntryPoint: {
5457 // Ops[0] = Execution Model
5458 // Ops[1] = EntryPoint ID
5459 // Ops[2] = Name (Literal String)
5460 // Ops[3] ... Ops[n] = Interface ID
5461 PrintOpcode(Inst);
5462 out << " ";
5463 PrintExecModel(Ops[0]);
5464 for (uint32_t i = 1; i < Ops.size(); i++) {
5465 out << " ";
5466 PrintOperand(Ops[i]);
5467 }
5468 out << "\n";
5469 break;
5470 }
5471 case spv::OpExecutionMode: {
5472 // Ops[0] = Entry Point ID
5473 // Ops[1] = Execution Mode
5474 // Ops[2] ... Ops[n] = Optional literals according to Execution Mode
5475 PrintOpcode(Inst);
5476 out << " ";
5477 PrintOperand(Ops[0]);
5478 out << " ";
5479 PrintExecMode(Ops[1]);
5480 for (uint32_t i = 2; i < Ops.size(); i++) {
5481 out << " ";
5482 PrintOperand(Ops[i]);
5483 }
5484 out << "\n";
5485 break;
5486 }
5487 case spv::OpSource: {
5488 // Ops[0] = SourceLanguage ID
5489 // Ops[1] = Version (LiteralNum)
5490 PrintOpcode(Inst);
5491 out << " ";
5492 PrintSourceLanguage(Ops[0]);
5493 out << " ";
5494 PrintOperand(Ops[1]);
5495 out << "\n";
5496 break;
5497 }
5498 case spv::OpDecorate: {
5499 // Ops[0] = Target ID
5500 // Ops[1] = Decoration (Block or BufferBlock)
5501 // Ops[2] ... Ops[n] = Optional literals according to Decoration
5502 PrintOpcode(Inst);
5503 out << " ";
5504 PrintOperand(Ops[0]);
5505 out << " ";
5506 PrintDecoration(Ops[1]);
5507 // Handle BuiltIn OpDecorate specially.
5508 if (Ops[1]->getNumID() == spv::DecorationBuiltIn) {
5509 out << " ";
5510 PrintBuiltIn(Ops[2]);
5511 } else {
5512 for (uint32_t i = 2; i < Ops.size(); i++) {
5513 out << " ";
5514 PrintOperand(Ops[i]);
5515 }
5516 }
5517 out << "\n";
5518 break;
5519 }
5520 case spv::OpMemberDecorate: {
5521 // Ops[0] = Structure Type ID
5522 // Ops[1] = Member Index(Literal Number)
5523 // Ops[2] = Decoration
5524 // Ops[3] ... Ops[n] = Optional literals according to Decoration
5525 PrintOpcode(Inst);
5526 out << " ";
5527 PrintOperand(Ops[0]);
5528 out << " ";
5529 PrintOperand(Ops[1]);
5530 out << " ";
5531 PrintDecoration(Ops[2]);
5532 for (uint32_t i = 3; i < Ops.size(); i++) {
5533 out << " ";
5534 PrintOperand(Ops[i]);
5535 }
5536 out << "\n";
5537 break;
5538 }
5539 case spv::OpTypePointer: {
5540 // Ops[0] = Storage Class
5541 // Ops[1] = Element Type ID
5542 PrintResID(Inst);
5543 out << " = ";
5544 PrintOpcode(Inst);
5545 out << " ";
5546 PrintStorageClass(Ops[0]);
5547 out << " ";
5548 PrintOperand(Ops[1]);
5549 out << "\n";
5550 break;
5551 }
5552 case spv::OpTypeImage: {
5553 // Ops[0] = Sampled Type ID
5554 // Ops[1] = Dim ID
5555 // Ops[2] = Depth (Literal Number)
5556 // Ops[3] = Arrayed (Literal Number)
5557 // Ops[4] = MS (Literal Number)
5558 // Ops[5] = Sampled (Literal Number)
5559 // Ops[6] = Image Format ID
5560 PrintResID(Inst);
5561 out << " = ";
5562 PrintOpcode(Inst);
5563 out << " ";
5564 PrintOperand(Ops[0]);
5565 out << " ";
5566 PrintDimensionality(Ops[1]);
5567 out << " ";
5568 PrintOperand(Ops[2]);
5569 out << " ";
5570 PrintOperand(Ops[3]);
5571 out << " ";
5572 PrintOperand(Ops[4]);
5573 out << " ";
5574 PrintOperand(Ops[5]);
5575 out << " ";
5576 PrintImageFormat(Ops[6]);
5577 out << "\n";
5578 break;
5579 }
5580 case spv::OpFunction: {
5581 // Ops[0] : Result Type ID
5582 // Ops[1] : Function Control
5583 // Ops[2] : Function Type ID
5584 PrintResID(Inst);
5585 out << " = ";
5586 PrintOpcode(Inst);
5587 out << " ";
5588 PrintOperand(Ops[0]);
5589 out << " ";
5590 PrintFuncCtrl(Ops[1]);
5591 out << " ";
5592 PrintOperand(Ops[2]);
5593 out << "\n";
5594 break;
5595 }
5596 case spv::OpSelectionMerge: {
5597 // Ops[0] = Merge Block ID
5598 // Ops[1] = Selection Control
5599 PrintOpcode(Inst);
5600 out << " ";
5601 PrintOperand(Ops[0]);
5602 out << " ";
5603 PrintSelectionControl(Ops[1]);
5604 out << "\n";
5605 break;
5606 }
5607 case spv::OpLoopMerge: {
5608 // Ops[0] = Merge Block ID
5609 // Ops[1] = Continue Target ID
5610 // Ops[2] = Selection Control
5611 PrintOpcode(Inst);
5612 out << " ";
5613 PrintOperand(Ops[0]);
5614 out << " ";
5615 PrintOperand(Ops[1]);
5616 out << " ";
5617 PrintLoopControl(Ops[2]);
5618 out << "\n";
5619 break;
5620 }
5621 case spv::OpImageSampleExplicitLod: {
5622 // Ops[0] = Result Type ID
5623 // Ops[1] = Sampled Image ID
5624 // Ops[2] = Coordinate ID
5625 // Ops[3] = Image Operands Type ID
5626 // Ops[4] ... Ops[n] = Operands ID
5627 PrintResID(Inst);
5628 out << " = ";
5629 PrintOpcode(Inst);
5630 for (uint32_t i = 0; i < 3; i++) {
5631 out << " ";
5632 PrintOperand(Ops[i]);
5633 }
5634 out << " ";
5635 PrintImageOperandsType(Ops[3]);
5636 for (uint32_t i = 4; i < Ops.size(); i++) {
5637 out << " ";
5638 PrintOperand(Ops[i]);
5639 }
5640 out << "\n";
5641 break;
5642 }
5643 case spv::OpVariable: {
5644 // Ops[0] : Result Type ID
5645 // Ops[1] : Storage Class
5646 // Ops[2] ... Ops[n] = Initializer IDs
5647 PrintResID(Inst);
5648 out << " = ";
5649 PrintOpcode(Inst);
5650 out << " ";
5651 PrintOperand(Ops[0]);
5652 out << " ";
5653 PrintStorageClass(Ops[1]);
5654 for (uint32_t i = 2; i < Ops.size(); i++) {
5655 out << " ";
5656 PrintOperand(Ops[i]);
5657 }
5658 out << "\n";
5659 break;
5660 }
5661 case spv::OpExtInst: {
5662 // Ops[0] = Result Type ID
5663 // Ops[1] = Set ID (OpExtInstImport ID)
5664 // Ops[2] = Instruction Number (Literal Number)
5665 // Ops[3] ... Ops[n] = Operand 1, ... , Operand n
5666 PrintResID(Inst);
5667 out << " = ";
5668 PrintOpcode(Inst);
5669 out << " ";
5670 PrintOperand(Ops[0]);
5671 out << " ";
5672 PrintOperand(Ops[1]);
5673 out << " ";
5674 PrintExtInst(Ops[2]);
5675 for (uint32_t i = 3; i < Ops.size(); i++) {
5676 out << " ";
5677 PrintOperand(Ops[i]);
5678 }
5679 out << "\n";
5680 break;
5681 }
5682 case spv::OpCopyMemory: {
5683 // Ops[0] = Addressing Model
5684 // Ops[1] = Memory Model
5685 PrintOpcode(Inst);
5686 out << " ";
5687 PrintOperand(Ops[0]);
5688 out << " ";
5689 PrintOperand(Ops[1]);
5690 out << " ";
5691 PrintMemoryAccess(Ops[2]);
5692 out << " ";
5693 PrintOperand(Ops[3]);
5694 out << "\n";
5695 break;
5696 }
5697 case spv::OpExtension:
5698 case spv::OpControlBarrier:
5699 case spv::OpMemoryBarrier:
5700 case spv::OpBranch:
5701 case spv::OpBranchConditional:
5702 case spv::OpStore:
5703 case spv::OpImageWrite:
5704 case spv::OpReturnValue:
5705 case spv::OpReturn:
5706 case spv::OpFunctionEnd: {
5707 PrintOpcode(Inst);
5708 for (uint32_t i = 0; i < Ops.size(); i++) {
5709 out << " ";
5710 PrintOperand(Ops[i]);
5711 }
5712 out << "\n";
5713 break;
5714 }
5715 case spv::OpExtInstImport:
5716 case spv::OpTypeRuntimeArray:
5717 case spv::OpTypeStruct:
5718 case spv::OpTypeSampler:
5719 case spv::OpTypeSampledImage:
5720 case spv::OpTypeInt:
5721 case spv::OpTypeFloat:
5722 case spv::OpTypeArray:
5723 case spv::OpTypeVector:
5724 case spv::OpTypeBool:
5725 case spv::OpTypeVoid:
5726 case spv::OpTypeFunction:
5727 case spv::OpFunctionParameter:
5728 case spv::OpLabel:
5729 case spv::OpPhi:
5730 case spv::OpLoad:
5731 case spv::OpSelect:
5732 case spv::OpAccessChain:
5733 case spv::OpPtrAccessChain:
5734 case spv::OpInBoundsAccessChain:
5735 case spv::OpUConvert:
5736 case spv::OpSConvert:
5737 case spv::OpConvertFToU:
5738 case spv::OpConvertFToS:
5739 case spv::OpConvertUToF:
5740 case spv::OpConvertSToF:
5741 case spv::OpFConvert:
5742 case spv::OpConvertPtrToU:
5743 case spv::OpConvertUToPtr:
5744 case spv::OpBitcast:
5745 case spv::OpIAdd:
5746 case spv::OpFAdd:
5747 case spv::OpISub:
5748 case spv::OpFSub:
5749 case spv::OpIMul:
5750 case spv::OpFMul:
5751 case spv::OpUDiv:
5752 case spv::OpSDiv:
5753 case spv::OpFDiv:
5754 case spv::OpUMod:
5755 case spv::OpSRem:
5756 case spv::OpFRem:
5757 case spv::OpBitwiseOr:
5758 case spv::OpBitwiseXor:
5759 case spv::OpBitwiseAnd:
5760 case spv::OpShiftLeftLogical:
5761 case spv::OpShiftRightLogical:
5762 case spv::OpShiftRightArithmetic:
5763 case spv::OpBitCount:
5764 case spv::OpCompositeExtract:
5765 case spv::OpVectorExtractDynamic:
5766 case spv::OpCompositeInsert:
5767 case spv::OpVectorInsertDynamic:
5768 case spv::OpVectorShuffle:
5769 case spv::OpIEqual:
5770 case spv::OpINotEqual:
5771 case spv::OpUGreaterThan:
5772 case spv::OpUGreaterThanEqual:
5773 case spv::OpULessThan:
5774 case spv::OpULessThanEqual:
5775 case spv::OpSGreaterThan:
5776 case spv::OpSGreaterThanEqual:
5777 case spv::OpSLessThan:
5778 case spv::OpSLessThanEqual:
5779 case spv::OpFOrdEqual:
5780 case spv::OpFOrdGreaterThan:
5781 case spv::OpFOrdGreaterThanEqual:
5782 case spv::OpFOrdLessThan:
5783 case spv::OpFOrdLessThanEqual:
5784 case spv::OpFOrdNotEqual:
5785 case spv::OpFUnordEqual:
5786 case spv::OpFUnordGreaterThan:
5787 case spv::OpFUnordGreaterThanEqual:
5788 case spv::OpFUnordLessThan:
5789 case spv::OpFUnordLessThanEqual:
5790 case spv::OpFUnordNotEqual:
5791 case spv::OpSampledImage:
5792 case spv::OpFunctionCall:
5793 case spv::OpConstantTrue:
5794 case spv::OpConstantFalse:
5795 case spv::OpConstant:
5796 case spv::OpSpecConstant:
5797 case spv::OpConstantComposite:
5798 case spv::OpSpecConstantComposite:
5799 case spv::OpConstantNull:
5800 case spv::OpLogicalOr:
5801 case spv::OpLogicalAnd:
5802 case spv::OpLogicalNot:
5803 case spv::OpLogicalNotEqual:
5804 case spv::OpUndef:
5805 case spv::OpIsInf:
5806 case spv::OpIsNan:
5807 case spv::OpAny:
5808 case spv::OpAll:
5809 case spv::OpAtomicIAdd:
5810 case spv::OpAtomicISub:
5811 case spv::OpAtomicExchange:
5812 case spv::OpAtomicIIncrement:
5813 case spv::OpAtomicIDecrement:
5814 case spv::OpAtomicCompareExchange:
5815 case spv::OpAtomicUMin:
5816 case spv::OpAtomicSMin:
5817 case spv::OpAtomicUMax:
5818 case spv::OpAtomicSMax:
5819 case spv::OpAtomicAnd:
5820 case spv::OpAtomicOr:
5821 case spv::OpAtomicXor:
5822 case spv::OpDot: {
5823 PrintResID(Inst);
5824 out << " = ";
5825 PrintOpcode(Inst);
5826 for (uint32_t i = 0; i < Ops.size(); i++) {
5827 out << " ";
5828 PrintOperand(Ops[i]);
5829 }
5830 out << "\n";
5831 break;
5832 }
5833 }
5834 }
5835}
5836
5837void SPIRVProducerPass::WriteOneWord(uint32_t Word) {
David Neto0676e6f2017-07-11 18:47:44 -04005838 binaryOut->write(reinterpret_cast<const char *>(&Word), sizeof(uint32_t));
David Neto22f144c2017-06-12 14:26:21 -04005839}
5840
5841void SPIRVProducerPass::WriteResultID(SPIRVInstruction *Inst) {
5842 WriteOneWord(Inst->getResultID());
5843}
5844
5845void SPIRVProducerPass::WriteWordCountAndOpcode(SPIRVInstruction *Inst) {
5846 // High 16 bit : Word Count
5847 // Low 16 bit : Opcode
5848 uint32_t Word = Inst->getOpcode();
5849 Word |= Inst->getWordCount() << 16;
5850 WriteOneWord(Word);
5851}
5852
5853void SPIRVProducerPass::WriteOperand(SPIRVOperand *Op) {
5854 SPIRVOperandType OpTy = Op->getType();
5855 switch (OpTy) {
5856 default: {
5857 llvm_unreachable("Unsupported SPIRV Operand Type???");
5858 break;
5859 }
5860 case SPIRVOperandType::NUMBERID: {
5861 WriteOneWord(Op->getNumID());
5862 break;
5863 }
5864 case SPIRVOperandType::LITERAL_STRING: {
5865 std::string Str = Op->getLiteralStr();
5866 const char *Data = Str.c_str();
5867 size_t WordSize = Str.size() / 4;
5868 for (unsigned Idx = 0; Idx < WordSize; Idx++) {
5869 WriteOneWord(*reinterpret_cast<const uint32_t *>(&Data[4 * Idx]));
5870 }
5871
5872 uint32_t Remainder = Str.size() % 4;
5873 uint32_t LastWord = 0;
5874 if (Remainder) {
5875 for (unsigned Idx = 0; Idx < Remainder; Idx++) {
5876 LastWord |= Data[4 * WordSize + Idx] << 8 * Idx;
5877 }
5878 }
5879
5880 WriteOneWord(LastWord);
5881 break;
5882 }
5883 case SPIRVOperandType::LITERAL_INTEGER:
5884 case SPIRVOperandType::LITERAL_FLOAT: {
5885 auto LiteralNum = Op->getLiteralNum();
5886 // TODO: Handle LiteranNum carefully.
5887 for (auto Word : LiteralNum) {
5888 WriteOneWord(Word);
5889 }
5890 break;
5891 }
5892 }
5893}
5894
5895void SPIRVProducerPass::WriteSPIRVBinary() {
5896 SPIRVInstructionList &SPIRVInstList = getSPIRVInstList();
5897
5898 for (auto Inst : SPIRVInstList) {
5899 SPIRVOperandList Ops = Inst->getOperands();
5900 spv::Op Opcode = static_cast<spv::Op>(Inst->getOpcode());
5901
5902 switch (Opcode) {
5903 default: {
5904 llvm_unreachable("Unsupported SPIRV instruction");
5905 break;
5906 }
5907 case spv::OpCapability:
5908 case spv::OpExtension:
5909 case spv::OpMemoryModel:
5910 case spv::OpEntryPoint:
5911 case spv::OpExecutionMode:
5912 case spv::OpSource:
5913 case spv::OpDecorate:
5914 case spv::OpMemberDecorate:
5915 case spv::OpBranch:
5916 case spv::OpBranchConditional:
5917 case spv::OpSelectionMerge:
5918 case spv::OpLoopMerge:
5919 case spv::OpStore:
5920 case spv::OpImageWrite:
5921 case spv::OpReturnValue:
5922 case spv::OpControlBarrier:
5923 case spv::OpMemoryBarrier:
5924 case spv::OpReturn:
5925 case spv::OpFunctionEnd:
5926 case spv::OpCopyMemory: {
5927 WriteWordCountAndOpcode(Inst);
5928 for (uint32_t i = 0; i < Ops.size(); i++) {
5929 WriteOperand(Ops[i]);
5930 }
5931 break;
5932 }
5933 case spv::OpTypeBool:
5934 case spv::OpTypeVoid:
5935 case spv::OpTypeSampler:
5936 case spv::OpLabel:
5937 case spv::OpExtInstImport:
5938 case spv::OpTypePointer:
5939 case spv::OpTypeRuntimeArray:
5940 case spv::OpTypeStruct:
5941 case spv::OpTypeImage:
5942 case spv::OpTypeSampledImage:
5943 case spv::OpTypeInt:
5944 case spv::OpTypeFloat:
5945 case spv::OpTypeArray:
5946 case spv::OpTypeVector:
5947 case spv::OpTypeFunction: {
5948 WriteWordCountAndOpcode(Inst);
5949 WriteResultID(Inst);
5950 for (uint32_t i = 0; i < Ops.size(); i++) {
5951 WriteOperand(Ops[i]);
5952 }
5953 break;
5954 }
5955 case spv::OpFunction:
5956 case spv::OpFunctionParameter:
5957 case spv::OpAccessChain:
5958 case spv::OpPtrAccessChain:
5959 case spv::OpInBoundsAccessChain:
5960 case spv::OpUConvert:
5961 case spv::OpSConvert:
5962 case spv::OpConvertFToU:
5963 case spv::OpConvertFToS:
5964 case spv::OpConvertUToF:
5965 case spv::OpConvertSToF:
5966 case spv::OpFConvert:
5967 case spv::OpConvertPtrToU:
5968 case spv::OpConvertUToPtr:
5969 case spv::OpBitcast:
5970 case spv::OpIAdd:
5971 case spv::OpFAdd:
5972 case spv::OpISub:
5973 case spv::OpFSub:
5974 case spv::OpIMul:
5975 case spv::OpFMul:
5976 case spv::OpUDiv:
5977 case spv::OpSDiv:
5978 case spv::OpFDiv:
5979 case spv::OpUMod:
5980 case spv::OpSRem:
5981 case spv::OpFRem:
5982 case spv::OpBitwiseOr:
5983 case spv::OpBitwiseXor:
5984 case spv::OpBitwiseAnd:
5985 case spv::OpShiftLeftLogical:
5986 case spv::OpShiftRightLogical:
5987 case spv::OpShiftRightArithmetic:
5988 case spv::OpBitCount:
5989 case spv::OpCompositeExtract:
5990 case spv::OpVectorExtractDynamic:
5991 case spv::OpCompositeInsert:
5992 case spv::OpVectorInsertDynamic:
5993 case spv::OpVectorShuffle:
5994 case spv::OpIEqual:
5995 case spv::OpINotEqual:
5996 case spv::OpUGreaterThan:
5997 case spv::OpUGreaterThanEqual:
5998 case spv::OpULessThan:
5999 case spv::OpULessThanEqual:
6000 case spv::OpSGreaterThan:
6001 case spv::OpSGreaterThanEqual:
6002 case spv::OpSLessThan:
6003 case spv::OpSLessThanEqual:
6004 case spv::OpFOrdEqual:
6005 case spv::OpFOrdGreaterThan:
6006 case spv::OpFOrdGreaterThanEqual:
6007 case spv::OpFOrdLessThan:
6008 case spv::OpFOrdLessThanEqual:
6009 case spv::OpFOrdNotEqual:
6010 case spv::OpFUnordEqual:
6011 case spv::OpFUnordGreaterThan:
6012 case spv::OpFUnordGreaterThanEqual:
6013 case spv::OpFUnordLessThan:
6014 case spv::OpFUnordLessThanEqual:
6015 case spv::OpFUnordNotEqual:
6016 case spv::OpExtInst:
6017 case spv::OpIsInf:
6018 case spv::OpIsNan:
6019 case spv::OpAny:
6020 case spv::OpAll:
6021 case spv::OpUndef:
6022 case spv::OpConstantNull:
6023 case spv::OpLogicalOr:
6024 case spv::OpLogicalAnd:
6025 case spv::OpLogicalNot:
6026 case spv::OpLogicalNotEqual:
6027 case spv::OpConstantComposite:
6028 case spv::OpSpecConstantComposite:
6029 case spv::OpConstantTrue:
6030 case spv::OpConstantFalse:
6031 case spv::OpConstant:
6032 case spv::OpSpecConstant:
6033 case spv::OpVariable:
6034 case spv::OpFunctionCall:
6035 case spv::OpSampledImage:
6036 case spv::OpImageSampleExplicitLod:
6037 case spv::OpSelect:
6038 case spv::OpPhi:
6039 case spv::OpLoad:
6040 case spv::OpAtomicIAdd:
6041 case spv::OpAtomicISub:
6042 case spv::OpAtomicExchange:
6043 case spv::OpAtomicIIncrement:
6044 case spv::OpAtomicIDecrement:
6045 case spv::OpAtomicCompareExchange:
6046 case spv::OpAtomicUMin:
6047 case spv::OpAtomicSMin:
6048 case spv::OpAtomicUMax:
6049 case spv::OpAtomicSMax:
6050 case spv::OpAtomicAnd:
6051 case spv::OpAtomicOr:
6052 case spv::OpAtomicXor:
6053 case spv::OpDot: {
6054 WriteWordCountAndOpcode(Inst);
6055 WriteOperand(Ops[0]);
6056 WriteResultID(Inst);
6057 for (uint32_t i = 1; i < Ops.size(); i++) {
6058 WriteOperand(Ops[i]);
6059 }
6060 break;
6061 }
6062 }
6063 }
6064}