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