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