LLVM 24.0.0git
SPIRVAsmPrinter.cpp
Go to the documentation of this file.
1//===-- SPIRVAsmPrinter.cpp - SPIR-V LLVM assembly writer ------*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to the SPIR-V assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRVAsmPrinter.h"
16#include "SPIRV.h"
17#include "SPIRVAuxDataHandler.h"
18#include "SPIRVInstrInfo.h"
19#include "SPIRVMCInstLower.h"
20#include "SPIRVModuleAnalysis.h"
22#include "SPIRVSubtarget.h"
23#include "SPIRVTargetMachine.h"
24#include "SPIRVUtils.h"
26#include "llvm/ADT/DenseMap.h"
37#include "llvm/IR/Analysis.h"
38#include "llvm/IR/PassManager.h"
39#include "llvm/MC/MCAsmInfo.h"
40#include "llvm/MC/MCAssembler.h"
41#include "llvm/MC/MCInst.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSymbol.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "asm-printer"
53
54namespace {
55class SPIRVAsmPrinter : public AsmPrinter {
56 unsigned NLabels = 0;
58
59public:
60 explicit SPIRVAsmPrinter(TargetMachine &TM,
61 std::unique_ptr<MCStreamer> Streamer)
62 : AsmPrinter(TM, std::move(Streamer), ID), ModuleSectionsEmitted(false),
63 ST(nullptr), TII(nullptr), MAI(nullptr) {
64 GetMAI = [this] {
65 return &getAnalysis<SPIRVModuleAnalysisWrapperPass>().MAI;
66 };
67 }
68 static char ID;
69 bool ModuleSectionsEmitted;
70 const SPIRVSubtarget *ST;
71 const SPIRVInstrInfo *TII;
72
73 StringRef getPassName() const override { return "SPIRV Assembly Printer"; }
74 void printOperand(const MachineInstr *MI, int OpNum, raw_ostream &O);
75 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
76 const char *ExtraCode, raw_ostream &O) override;
77
78 void outputMCInst(MCInst &Inst);
79 void outputInstruction(const MachineInstr *MI);
80 void outputModuleSection(SPIRV::ModuleSectionType MSType);
81 void outputGlobalRequirements();
82 void outputEntryPoints();
83 void outputDebugSourceAndStrings(const Module &M);
84 void outputOpExtInstImports(const Module &M);
85 void outputOpMemoryModel();
86 void outputOpFunctionEnd();
87 void outputExtFuncDecls();
88 void outputExecutionModeFromMDNode(MCRegister Reg, MDNode *Node,
89 SPIRV::ExecutionMode::ExecutionMode EM,
90 unsigned ExpectMDOps, int64_t DefVal);
91 void outputExecutionModeFromNumthreadsAttribute(
92 const MCRegister &Reg, const Attribute &Attr,
93 SPIRV::ExecutionMode::ExecutionMode EM);
94 void outputExecutionModeFromEnableMaximalReconvergenceAttr(
95 const MCRegister &Reg, const SPIRVSubtarget &ST);
96 void emitSimpleExecutionMode(MCRegister Reg,
97 SPIRV::ExecutionMode::ExecutionMode EM);
98 void outputExecutionMode(const Module &M);
99 void outputAnnotations(const Module &M);
100 void outputModuleSections();
101 void outputFPFastMathDefaultInfo();
102 bool isHidden() {
103 return MF->getFunction()
104 .getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME)
105 .isValid();
106 }
107
108 void emitInstruction(const MachineInstr *MI) override;
109 void emitFunctionEntryLabel() override {}
110 void emitFunctionHeader() override;
111 void emitFunctionBodyStart() override {}
112 void emitFunctionBodyEnd() override;
113 void emitBasicBlockStart(const MachineBasicBlock &MBB) override;
114 void emitBasicBlockEnd(const MachineBasicBlock &MBB) override {}
115 void emitGlobalVariable(const GlobalVariable *GV) override {}
116 void emitOpLabel(const MachineBasicBlock &MBB);
117 void emitEndOfAsmFile(Module &M) override;
118 bool doInitialization(Module &M) override;
119
120 void getAnalysisUsage(AnalysisUsage &AU) const override;
122 std::function<SPIRV::ModuleAnalysisInfo *()> GetMAI;
123
124 // Non-owning pointer to the NSDI handler registered via addAsmPrinterHandler.
125 // The handler's lifetime is managed by AsmPrinter (the base class of this
126 // object), so this pointer cannot dangle.
127 SPIRVNonSemanticDebugHandler *NSDebugHandler = nullptr;
128
129 std::unique_ptr<SPIRVAuxDataHandler> AuxDataHandler;
130};
131} // namespace
132
133void SPIRVAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
134 AU.addRequired<SPIRVModuleAnalysisWrapperPass>();
135 AU.addPreserved<SPIRVModuleAnalysisWrapperPass>();
137}
138
139// If the module has no functions, we need output global info anyway.
140void SPIRVAsmPrinter::emitEndOfAsmFile(Module &M) {
141 if (!ModuleSectionsEmitted) {
142 outputModuleSections();
143 ModuleSectionsEmitted = true;
144 }
145
146 ST = static_cast<const SPIRVTargetMachine &>(TM).getSubtargetImpl();
147 // SPIRVModuleAnalysis sets GR->Bound = MAI->MaxID before printing. Any IDs
148 // allocated by AsmPrinter handlers (e.g. SPIRVNonSemanticDebugHandler) during
149 // outputModuleSections() are not counted. Refresh the bound here so the
150 // formula below sees the final allocation count.
151 if (MAI)
152 ST->getSPIRVGlobalRegistry()->setBound(MAI->MaxID);
153 VersionTuple SPIRVVersion = ST->getSPIRVVersion();
154 uint32_t Major = SPIRVVersion.getMajor();
155 uint32_t Minor = SPIRVVersion.getMinor().value_or(0);
156 // Bound is an approximation that accounts for the maximum used register
157 // number and number of generated OpLabels
158 unsigned Bound = 2 * (ST->getBound() + 1) + NLabels;
159 if (MCAssembler *Asm = OutStreamer->getAssemblerPtr())
160 static_cast<SPIRVObjectWriter &>(Asm->getWriter())
161 .setBuildVersion(Major, Minor, Bound);
162}
163
164void SPIRVAsmPrinter::emitFunctionHeader() {
165 if (!ModuleSectionsEmitted) {
166 outputModuleSections();
167 ModuleSectionsEmitted = true;
168 }
169 // Get the subtarget from the current MachineFunction.
170 ST = &MF->getSubtarget<SPIRVSubtarget>();
171 TII = ST->getInstrInfo();
172 const Function &F = MF->getFunction();
173
174 if (isVerbose() && !isHidden()) {
175 OutStreamer->getCommentOS()
176 << "-- Begin function "
177 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
178 }
179
180 auto Section = getObjFileLowering().SectionForGlobal(&F, TM);
181 MF->setSection(Section);
182
183 // SPIRVAsmPrinter::emitFunctionHeader() does not call the base class,
184 // so handlers never receive beginFunction() from the normal path. Drive the
185 // per-function lifecycle here, matching what AsmPrinter::emitFunctionHeader()
186 // does for other targets.
187 for (auto &Handler : Handlers) {
188 Handler->beginFunction(MF);
189 Handler->beginBasicBlockSection(MF->front());
190 }
191}
192
193void SPIRVAsmPrinter::outputOpFunctionEnd() {
194 MCInst FunctionEndInst;
195 FunctionEndInst.setOpcode(SPIRV::OpFunctionEnd);
196 outputMCInst(FunctionEndInst);
197}
198
199void SPIRVAsmPrinter::emitFunctionBodyEnd() {
200 if (!isHidden())
201 outputOpFunctionEnd();
202}
203
204void SPIRVAsmPrinter::emitOpLabel(const MachineBasicBlock &MBB) {
205 // Do not emit anything if it's an internal service function.
206 if (isHidden())
207 return;
208
209 MCInst LabelInst;
210 LabelInst.setOpcode(SPIRV::OpLabel);
211 LabelInst.addOperand(MCOperand::createReg(MAI->getOrCreateMBBRegister(MBB)));
212 outputMCInst(LabelInst);
213 ++NLabels;
214 LabeledMBB.insert(&MBB);
215}
216
217void SPIRVAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
218 // Do not emit anything if it's an internal service function.
219 if (MBB.empty() || isHidden())
220 return;
221
222 // If it's the first MBB in MF, it has OpFunction and OpFunctionParameter, so
223 // OpLabel should be output after them.
224 if (MBB.getNumber() == MF->front().getNumber()) {
225 for (const MachineInstr &MI : MBB)
226 if (MI.getOpcode() == SPIRV::OpFunction)
227 return;
228 // TODO: this case should be checked by the verifier.
229 report_fatal_error("OpFunction is expected in the front MBB of MF");
230 }
231 emitOpLabel(MBB);
232}
233
234void SPIRVAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
235 raw_ostream &O) {
236 const MachineOperand &MO = MI->getOperand(OpNum);
237
238 switch (MO.getType()) {
241 break;
242
244 O << MO.getImm();
245 break;
246
248 O << MO.getFPImm();
249 break;
250
252 O << *MO.getMBB()->getSymbol();
253 break;
254
256 O << *getSymbol(MO.getGlobal());
257 break;
258
260 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
261 O << BA->getName();
262 break;
263 }
264
266 O << *GetExternalSymbolSymbol(MO.getSymbolName());
267 break;
268
271 default:
272 llvm_unreachable("<unknown operand type>");
273 }
274}
275
276bool SPIRVAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
277 const char *ExtraCode, raw_ostream &O) {
278 if (ExtraCode && ExtraCode[0])
279 return true; // Invalid instruction - SPIR-V does not have special modifiers
280
281 printOperand(MI, OpNo, O);
282 return false;
283}
284
286 const SPIRVInstrInfo *TII) {
287 return TII->isHeaderInstr(*MI) || MI->getOpcode() == SPIRV::OpFunction ||
288 MI->getOpcode() == SPIRV::OpFunctionParameter;
289}
290
291void SPIRVAsmPrinter::outputMCInst(MCInst &Inst) {
292 OutStreamer->emitInstruction(Inst, *OutContext.getSubtargetInfo());
293}
294
295void SPIRVAsmPrinter::outputInstruction(const MachineInstr *MI) {
296 SPIRVMCInstLower MCInstLowering;
297 MCInst TmpInst;
298 MCInstLowering.lower(MI, TmpInst, MAI);
299 outputMCInst(TmpInst);
300}
301
302void SPIRVAsmPrinter::emitInstruction(const MachineInstr *MI) {
303 SPIRV_MC::verifyInstructionPredicates(MI->getOpcode(),
304 getSubtargetInfo().getFeatureBits());
305
306 bool InstructionEmitted = !MAI->getSkipEmission(MI);
307 if (InstructionEmitted)
308 outputInstruction(MI);
309
310 // Output OpLabel after OpFunction and OpFunctionParameter in the first MBB.
311 const MachineInstr *NextMI = MI->getNextNode();
312 bool BlockHasLabel = LabeledMBB.contains(MI->getParent());
313 bool IsFunctionPreambleInstruction = isFuncOrHeaderInstr(MI, TII);
314 bool IsNextInstructionFunctionPreamble =
315 NextMI && isFuncOrHeaderInstr(NextMI, TII);
316 bool ShouldEmitEntryLabel = !BlockHasLabel && IsFunctionPreambleInstruction &&
317 !IsNextInstructionFunctionPreamble;
318 if (ShouldEmitEntryLabel) {
319 assert(MI->getParent()->getNumber() == MF->front().getNumber() &&
320 "OpFunction is not in the front MBB of MF");
321 emitOpLabel(*MI->getParent());
322 if (NSDebugHandler && !isHidden())
323 NSDebugHandler->notifyEntryLabelEmitted(*MF);
324 }
325}
326
327void SPIRVAsmPrinter::outputModuleSection(SPIRV::ModuleSectionType MSType) {
328 for (const MachineInstr *MI : MAI->getMSInstrs(MSType))
329 outputInstruction(MI);
330}
331
332void SPIRVAsmPrinter::outputDebugSourceAndStrings(const Module &M) {
333 // Output OpSourceExtensions.
334 for (auto &Str : MAI->SrcExt) {
335 MCInst Inst;
336 Inst.setOpcode(SPIRV::OpSourceExtension);
337 addStringImm(Str.first(), Inst);
338 outputMCInst(Inst);
339 }
340 // Output OpString.
341 outputModuleSection(SPIRV::MB_DebugStrings);
342 // Output OpSource.
343 MCInst Inst;
344 Inst.setOpcode(SPIRV::OpSource);
345 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->SrcLang)));
346 Inst.addOperand(
347 MCOperand::createImm(static_cast<unsigned>(MAI->SrcLangVersion)));
348 outputMCInst(Inst);
349 // Emit OpString instructions for NSDI file paths and type names here, in
350 // section 7. OpString must precede type/constant declarations per the SPIR-V
351 // module layout (section 2.4). The OpExtInst instructions that reference
352 // these strings are emitted later at section 10 by
353 // emitNonSemanticGlobalDebugInfo().
354 if (NSDebugHandler)
355 NSDebugHandler->emitNonSemanticDebugStrings(*MAI);
356 if (AuxDataHandler)
357 AuxDataHandler->emitAuxDataStrings(*MAI);
358}
359
360void SPIRVAsmPrinter::outputOpExtInstImports(const Module &M) {
361 for (auto &CU : MAI->ExtInstSetMap) {
362 unsigned Set = CU.first;
363 MCRegister Reg = CU.second;
364 MCInst Inst;
365 Inst.setOpcode(SPIRV::OpExtInstImport);
368 static_cast<SPIRV::InstructionSet::InstructionSet>(Set)),
369 Inst);
370 outputMCInst(Inst);
371 }
372}
373
374void SPIRVAsmPrinter::outputOpMemoryModel() {
375 MCInst Inst;
376 Inst.setOpcode(SPIRV::OpMemoryModel);
377 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->Addr)));
378 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(MAI->Mem)));
379 outputMCInst(Inst);
380}
381
382// Before the OpEntryPoints' output, we need to add the entry point's
383// interfaces. The interface is a list of IDs of global OpVariable instructions.
384// These declare the set of global variables from a module that form
385// the interface of this entry point.
386void SPIRVAsmPrinter::outputEntryPoints() {
387 // Find all OpVariable IDs with required StorageClass.
388 DenseSet<MCRegister> InterfaceIDs;
389 for (const MachineInstr *MI : MAI->GlobalVarList) {
390 assert(MI->getOpcode() == SPIRV::OpVariable ||
391 MI->getOpcode() == SPIRV::OpUntypedVariableKHR);
392 auto SC = static_cast<SPIRV::StorageClass::StorageClass>(
393 MI->getOperand(2).getImm());
394 // Before version 1.4, the interface's storage classes are limited to
395 // the Input and Output storage classes. Starting with version 1.4,
396 // the interface's storage classes are all storage classes used in
397 // declaring all global variables referenced by the entry point call tree.
398 if (ST->isAtLeastSPIRVVer(VersionTuple(1, 4)) ||
399 SC == SPIRV::StorageClass::Input || SC == SPIRV::StorageClass::Output) {
400 const MachineFunction *MF = MI->getMF();
401 MCRegister Reg = MAI->getRegisterAlias(MF, MI->getOperand(0).getReg());
402 InterfaceIDs.insert(Reg);
403 }
404 }
405
406 // Output OpEntryPoints adding interface args to all of them.
407 for (const MachineInstr *MI : MAI->getMSInstrs(SPIRV::MB_EntryPoints)) {
408 SPIRVMCInstLower MCInstLowering;
409 MCInst TmpInst;
410 MCInstLowering.lower(MI, TmpInst, MAI);
411 for (MCRegister Reg : InterfaceIDs) {
412 assert(Reg.isValid());
414 }
415 outputMCInst(TmpInst);
416 }
417}
418
419// Create global OpCapability instructions for the required capabilities.
420void SPIRVAsmPrinter::outputGlobalRequirements() {
421 // Abort here if not all requirements can be satisfied.
422 MAI->Reqs.checkSatisfiable(*ST);
423
424 for (const auto &Cap : MAI->Reqs.getMinimalCapabilities()) {
425 MCInst Inst;
426 Inst.setOpcode(SPIRV::OpCapability);
428 outputMCInst(Inst);
429 }
430
431 // Generate the final OpExtensions with strings instead of enums.
432 for (const auto &Ext : MAI->Reqs.getExtensions()) {
433 MCInst Inst;
434 Inst.setOpcode(SPIRV::OpExtension);
436 SPIRV::OperandCategory::ExtensionOperand, Ext),
437 Inst);
438 outputMCInst(Inst);
439 }
440 // TODO add a pseudo instr for version number.
441}
442
443void SPIRVAsmPrinter::outputExtFuncDecls() {
444 // Insert OpFunctionEnd after each declaration.
445 auto I = MAI->getMSInstrs(SPIRV::MB_ExtFuncDecls).begin(),
446 E = MAI->getMSInstrs(SPIRV::MB_ExtFuncDecls).end();
447 for (; I != E; ++I) {
448 outputInstruction(*I);
449 if ((I + 1) == E || (*(I + 1))->getOpcode() == SPIRV::OpFunction)
450 outputOpFunctionEnd();
451 }
452}
453
454// Encode LLVM type by SPIR-V execution mode VecTypeHint.
455static unsigned encodeVecTypeHint(Type *Ty) {
456 if (Ty->isHalfTy())
457 return 4;
458 if (Ty->isFloatTy())
459 return 5;
460 if (Ty->isDoubleTy())
461 return 6;
462 if (IntegerType *IntTy = dyn_cast<IntegerType>(Ty)) {
463 switch (IntTy->getIntegerBitWidth()) {
464 case 8:
465 return 0;
466 case 16:
467 return 1;
468 case 32:
469 return 2;
470 case 64:
471 return 3;
472 default:
473 llvm_unreachable("invalid integer type");
474 }
475 }
477 Type *EleTy = VecTy->getElementType();
478 unsigned Size = VecTy->getNumElements();
479 return Size << 16 | encodeVecTypeHint(EleTy);
480 }
481 llvm_unreachable("invalid type");
482}
483
484static void addOpsFromMDNode(MDNode *MDN, MCInst &Inst,
486 for (const MDOperand &MDOp : MDN->operands()) {
487 if (auto *CMeta = dyn_cast<ConstantAsMetadata>(MDOp)) {
488 Constant *C = CMeta->getValue();
489 if (ConstantInt *Const = dyn_cast<ConstantInt>(C)) {
490 Inst.addOperand(MCOperand::createImm(Const->getZExtValue()));
491 } else if (auto *CE = dyn_cast<Function>(C)) {
492 MCRegister FuncReg = MAI->getGlobalObjReg(CE);
493 assert(FuncReg.isValid());
494 Inst.addOperand(MCOperand::createReg(FuncReg));
495 }
496 }
497 }
498}
499
500void SPIRVAsmPrinter::outputExecutionModeFromMDNode(
501 MCRegister Reg, MDNode *Node, SPIRV::ExecutionMode::ExecutionMode EM,
502 unsigned ExpectMDOps, int64_t DefVal) {
503 MCInst Inst;
504 Inst.setOpcode(SPIRV::OpExecutionMode);
506 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(EM)));
507 addOpsFromMDNode(Node, Inst, MAI);
508 // reqd_work_group_size and work_group_size_hint require 3 operands,
509 // if metadata contains less operands, just add a default value
510 unsigned NodeSz = Node->getNumOperands();
511 if (ExpectMDOps > 0 && NodeSz < ExpectMDOps)
512 for (unsigned i = NodeSz; i < ExpectMDOps; ++i)
513 Inst.addOperand(MCOperand::createImm(DefVal));
514 outputMCInst(Inst);
515}
516
517void SPIRVAsmPrinter::outputExecutionModeFromNumthreadsAttribute(
518 const MCRegister &Reg, const Attribute &Attr,
519 SPIRV::ExecutionMode::ExecutionMode EM) {
520 assert(Attr.isValid() && "Function called with an invalid attribute.");
521
522 MCInst Inst;
523 Inst.setOpcode(SPIRV::OpExecutionMode);
525 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(EM)));
526
527 unsigned X, Y, Z;
532
533 outputMCInst(Inst);
534}
535
536void SPIRVAsmPrinter::emitSimpleExecutionMode(
537 MCRegister Reg, SPIRV::ExecutionMode::ExecutionMode EM) {
538 MCInst Inst;
539 Inst.setOpcode(SPIRV::OpExecutionMode);
541 Inst.addOperand(MCOperand::createImm(static_cast<unsigned>(EM)));
542 outputMCInst(Inst);
543}
544
545void SPIRVAsmPrinter::outputExecutionModeFromEnableMaximalReconvergenceAttr(
546 const MCRegister &Reg, const SPIRVSubtarget &ST) {
547 assert(ST.canUseExtension(SPIRV::Extension::SPV_KHR_maximal_reconvergence) &&
548 "Function called when SPV_KHR_maximal_reconvergence is not enabled.");
549
550 emitSimpleExecutionMode(Reg, SPIRV::ExecutionMode::MaximallyReconvergesKHR);
551}
552
553void SPIRVAsmPrinter::outputExecutionMode(const Module &M) {
554 NamedMDNode *Node = M.getNamedMetadata("spirv.ExecutionMode");
555 if (Node) {
556 for (unsigned i = 0; i < Node->getNumOperands(); i++) {
557 const auto EM =
559 cast<ConstantAsMetadata>((Node->getOperand(i))->getOperand(1))
560 ->getValue())
561 ->getZExtValue();
562 // Skip ArithmeticPoisonKHR to avoid a duplicate.
563 if (EM == SPIRV::ExecutionMode::ArithmeticPoisonKHR)
564 continue;
565 // If SPV_KHR_float_controls2 is enabled and we find any of
566 // FPFastMathDefault, ContractionOff or SignedZeroInfNanPreserve execution
567 // modes, skip it, it'll be done somewhere else.
568 if (ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) {
569 if (EM == SPIRV::ExecutionMode::FPFastMathDefault ||
570 EM == SPIRV::ExecutionMode::ContractionOff ||
571 EM == SPIRV::ExecutionMode::SignedZeroInfNanPreserve)
572 continue;
573 }
574
575 MCInst Inst;
576 Inst.setOpcode(SPIRV::OpExecutionMode);
577 addOpsFromMDNode(cast<MDNode>(Node->getOperand(i)), Inst, MAI);
578 outputMCInst(Inst);
579 }
580 outputFPFastMathDefaultInfo();
581 }
582 for (auto FI = M.begin(), E = M.end(); FI != E; ++FI) {
583 const Function &F = *FI;
584 // Only operands of OpEntryPoint instructions are allowed to be
585 // <Entry Point> operands of OpExecutionMode
586 if (F.isDeclaration() || !isEntryPoint(F))
587 continue;
588 MCRegister FReg = MAI->getGlobalObjReg(&F);
589 assert(FReg.isValid());
590
591 if (Attribute Attr = F.getFnAttribute("hlsl.shader"); Attr.isValid()) {
592 // SPIR-V common validation: Fragment requires OriginUpperLeft or
593 // OriginLowerLeft.
594 // VUID-StandaloneSpirv-OriginLowerLeft-04653: Fragment must declare
595 // OriginUpperLeft.
596 if (Attr.getValueAsString() == "pixel") {
597 emitSimpleExecutionMode(FReg, SPIRV::ExecutionMode::OriginUpperLeft);
598 // Vulkan: "To write to FragStencilRefEXT, a shader must declare the
599 // StencilRefReplacingEXT execution mode." The StencilExportEXT
600 // capability is only required by that built-in.
601 if (llvm::is_contained(MAI->Reqs.getMinimalCapabilities(),
602 SPIRV::Capability::StencilExportEXT))
603 emitSimpleExecutionMode(FReg,
604 SPIRV::ExecutionMode::StencilRefReplacingEXT);
605 }
606 }
607 if (MDNode *Node = F.getMetadata("reqd_work_group_size"))
608 outputExecutionModeFromMDNode(FReg, Node, SPIRV::ExecutionMode::LocalSize,
609 3, 1);
610 if (Attribute Attr = F.getFnAttribute("hlsl.numthreads"); Attr.isValid())
611 outputExecutionModeFromNumthreadsAttribute(
612 FReg, Attr, SPIRV::ExecutionMode::LocalSize);
613 if (Attribute Attr = F.getFnAttribute("enable-maximal-reconvergence");
614 Attr.getValueAsBool()) {
615 outputExecutionModeFromEnableMaximalReconvergenceAttr(FReg, *ST);
616 }
617 if (MDNode *Node = F.getMetadata("work_group_size_hint"))
618 outputExecutionModeFromMDNode(FReg, Node,
619 SPIRV::ExecutionMode::LocalSizeHint, 3, 1);
620 if (MDNode *Node = F.getMetadata("reqd_sub_group_size"))
621 outputExecutionModeFromMDNode(FReg, Node,
622 SPIRV::ExecutionMode::SubgroupSize, 0, 0);
623 if (MDNode *Node = F.getMetadata("intel_reqd_sub_group_size"))
624 outputExecutionModeFromMDNode(FReg, Node,
625 SPIRV::ExecutionMode::SubgroupSize, 0, 0);
626 if (MDNode *Node = F.getMetadata("max_work_group_size")) {
627 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_kernel_attributes))
628 outputExecutionModeFromMDNode(
629 FReg, Node, SPIRV::ExecutionMode::MaxWorkgroupSizeINTEL, 3, 1);
630 }
631 if (MDNode *Node = F.getMetadata("vec_type_hint")) {
632 MCInst Inst;
633 Inst.setOpcode(SPIRV::OpExecutionMode);
635 unsigned EM = static_cast<unsigned>(SPIRV::ExecutionMode::VecTypeHint);
637 unsigned TypeCode = encodeVecTypeHint(getMDOperandAsType(Node, 0));
638 Inst.addOperand(MCOperand::createImm(TypeCode));
639 outputMCInst(Inst);
640 }
641 // Per SPV_KHR_poison_freeze description of PoisonFreezeKHR "If declared,
642 // all entry points must use the ArithmeticPoisonKHR execution mode".
643 if (llvm::is_contained(MAI->Reqs.getMinimalCapabilities(),
644 SPIRV::Capability::PoisonFreezeKHR)) {
645 emitSimpleExecutionMode(FReg, SPIRV::ExecutionMode::ArithmeticPoisonKHR);
646 }
647 // --spirv-fp-contract=off forces to emit ContractionOff for this kernel
648 // entry point, --spirv-fp-contract=fast suppresses it.
649 SPIRVFPContractMode FPContract = ST->getCLOpts().fp_contract;
650 bool EmitContractionOff =
651 ST->isKernel() && !M.getNamedMetadata("spirv.ExecutionMode") &&
652 FPContract != SPIRVFPContractMode::Fast &&
653 (FPContract == SPIRVFPContractMode::Off ||
654 !M.getNamedMetadata("opencl.enable.FP_CONTRACT"));
655 if (EmitContractionOff) {
656 if (ST->canUseExtension(SPIRV::Extension::SPV_KHR_float_controls2)) {
657 // When SPV_KHR_float_controls2 is enabled, ContractionOff is
658 // deprecated. We need to use FPFastMathDefault with the appropriate
659 // flags instead. Since FPFastMathDefault takes a target type, we need
660 // to emit it for each floating-point type that exists in the module
661 // to match the effect of ContractionOff. As of now, there are 3 FP
662 // types: fp16, fp32 and fp64.
663
664 // We only end up here because there is no "spirv.ExecutionMode"
665 // metadata, so that means no FPFastMathDefault. Therefore, we only
666 // need to make sure AllowContract is set to 0, as the rest of flags.
667 // We still need to emit the OpExecutionMode instruction, otherwise
668 // it's up to the client API to define the flags. Therefore, we need
669 // to find the constant with 0 value.
670
671 // Collect the SPIRVTypes for fp16, fp32, and fp64 and the constant of
672 // type int32 with 0 value to represent the FP Fast Math Mode.
673 std::vector<const MachineInstr *> SPIRVFloatTypes;
674 const MachineInstr *ConstZeroInt32 = nullptr;
675 for (const MachineInstr *MI :
676 MAI->getMSInstrs(SPIRV::MB_TypeConstVars)) {
677 unsigned OpCode = MI->getOpcode();
678
679 // Collect the SPIRV type if it's a float.
680 if (OpCode == SPIRV::OpTypeFloat) {
681 // Skip if the target type is not fp16, fp32, fp64.
682 const unsigned OpTypeFloatSize = MI->getOperand(1).getImm();
683 if (OpTypeFloatSize != 16 && OpTypeFloatSize != 32 &&
684 OpTypeFloatSize != 64) {
685 continue;
686 }
687 SPIRVFloatTypes.push_back(MI);
688 continue;
689 }
690
691 if (OpCode == SPIRV::OpConstantNull) {
692 // Check if the constant is int32, if not skip it.
693 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
694 MachineInstr *TypeMI = MRI.getVRegDef(MI->getOperand(1).getReg());
695 bool IsInt32Ty = TypeMI &&
696 TypeMI->getOpcode() == SPIRV::OpTypeInt &&
697 TypeMI->getOperand(1).getImm() == 32;
698 if (IsInt32Ty)
699 ConstZeroInt32 = MI;
700 }
701 }
702
703 // When SPV_KHR_float_controls2 is enabled, ContractionOff is
704 // deprecated. We need to use FPFastMathDefault with the appropriate
705 // flags instead. Since FPFastMathDefault takes a target type, we need
706 // to emit it for each floating-point type that exists in the module
707 // to match the effect of ContractionOff. As of now, there are 3 FP
708 // types: fp16, fp32 and fp64.
709 for (const MachineInstr *MI : SPIRVFloatTypes) {
710 MCInst Inst;
711 Inst.setOpcode(SPIRV::OpExecutionModeId);
713 unsigned EM =
714 static_cast<unsigned>(SPIRV::ExecutionMode::FPFastMathDefault);
716 const MachineFunction *MF = MI->getMF();
717 MCRegister TypeReg =
718 MAI->getRegisterAlias(MF, MI->getOperand(0).getReg());
719 Inst.addOperand(MCOperand::createReg(TypeReg));
720 assert(ConstZeroInt32 && "There should be a constant zero.");
721 MCRegister ConstReg = MAI->getRegisterAlias(
722 ConstZeroInt32->getMF(), ConstZeroInt32->getOperand(0).getReg());
723 Inst.addOperand(MCOperand::createReg(ConstReg));
724 outputMCInst(Inst);
725 }
726 } else {
727 emitSimpleExecutionMode(FReg, SPIRV::ExecutionMode::ContractionOff);
728 }
729 }
730 }
731}
732
733void SPIRVAsmPrinter::outputAnnotations(const Module &M) {
734 outputModuleSection(SPIRV::MB_Annotations);
735 // Process llvm.global.annotations special global variable.
736 if (const GlobalVariable *V = M.getNamedGlobal("llvm.global.annotations")) {
737 const ConstantArray *CA = cast<ConstantArray>(V->getOperand(0));
738 for (Value *Op : CA->operands()) {
739 ConstantStruct *CS = cast<ConstantStruct>(Op);
740 // The first field of the struct contains a pointer to
741 // the annotated variable.
742 Value *AnnotatedVar = CS->getOperand(0)->stripPointerCasts();
743 auto *GO = dyn_cast<GlobalObject>(AnnotatedVar);
744 MCRegister Reg = GO ? MAI->getGlobalObjReg(GO) : MCRegister();
745 if (!Reg.isValid()) {
746 std::string DiagMsg;
747 raw_string_ostream OS(DiagMsg);
748 AnnotatedVar->print(OS);
749 DiagMsg = "Unsupported value in llvm.global.annotations: " + DiagMsg;
750 report_fatal_error(DiagMsg.c_str());
751 }
752
753 // The second field contains a pointer to a global annotation string.
754 GlobalVariable *GV =
756
757 StringRef AnnotationString;
758 [[maybe_unused]] bool Success =
759 getConstantStringInfo(GV, AnnotationString);
760 assert(Success && "Failed to get annotation string");
761 MCInst Inst;
762 Inst.setOpcode(SPIRV::OpDecorate);
764 unsigned Dec = static_cast<unsigned>(SPIRV::Decoration::UserSemantic);
766 addStringImm(AnnotationString, Inst);
767 outputMCInst(Inst);
768 }
769 }
770}
771
772void SPIRVAsmPrinter::outputFPFastMathDefaultInfo() {
773 // Collect the SPIRVTypes that are OpTypeFloat and the constants of type
774 // int32, that might be used as FP Fast Math Mode.
775 std::vector<const MachineInstr *> SPIRVFloatTypes;
776 // Hashtable to associate immediate values with the constant holding them.
777 DenseMap<int, const MachineInstr *> ConstMap;
778 for (const MachineInstr *MI : MAI->getMSInstrs(SPIRV::MB_TypeConstVars)) {
779 // Skip if the instruction is not OpTypeFloat or OpConstant.
780 unsigned OpCode = MI->getOpcode();
781 if (OpCode != SPIRV::OpTypeFloat && OpCode != SPIRV::OpConstantI &&
782 OpCode != SPIRV::OpConstantNull)
783 continue;
784
785 // Collect the SPIRV type if it's a float.
786 if (OpCode == SPIRV::OpTypeFloat) {
787 SPIRVFloatTypes.push_back(MI);
788 } else {
789 // Check if the constant is int32, if not skip it.
790 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
791 MachineInstr *TypeMI = MRI.getVRegDef(MI->getOperand(1).getReg());
792 if (!TypeMI || TypeMI->getOpcode() != SPIRV::OpTypeInt ||
793 TypeMI->getOperand(1).getImm() != 32)
794 continue;
795
796 if (OpCode == SPIRV::OpConstantI)
797 ConstMap[MI->getOperand(2).getImm()] = MI;
798 else
799 ConstMap[0] = MI;
800 }
801 }
802
803 for (const auto &[Func, FPFastMathDefaultInfoVec] :
804 MAI->FPFastMathDefaultInfoMap) {
805 if (FPFastMathDefaultInfoVec.empty())
806 continue;
807
808 for (const MachineInstr *MI : SPIRVFloatTypes) {
809 unsigned OpTypeFloatSize = MI->getOperand(1).getImm();
812 assert(Index < FPFastMathDefaultInfoVec.size() &&
813 "Index out of bounds for FPFastMathDefaultInfoVec");
814 const auto &FPFastMathDefaultInfo = FPFastMathDefaultInfoVec[Index];
815 assert(FPFastMathDefaultInfo.Ty &&
816 "Expected target type for FPFastMathDefaultInfo");
817 assert(FPFastMathDefaultInfo.Ty->getScalarSizeInBits() ==
818 OpTypeFloatSize &&
819 "Mismatched float type size");
820 MCInst Inst;
821 Inst.setOpcode(SPIRV::OpExecutionModeId);
822 MCRegister FuncReg = MAI->getGlobalObjReg(Func);
823 assert(FuncReg.isValid());
824 Inst.addOperand(MCOperand::createReg(FuncReg));
825 Inst.addOperand(
826 MCOperand::createImm(SPIRV::ExecutionMode::FPFastMathDefault));
827 MCRegister TypeReg =
828 MAI->getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
829 Inst.addOperand(MCOperand::createReg(TypeReg));
830 unsigned Flags = FPFastMathDefaultInfo.FastMathFlags;
831 if (FPFastMathDefaultInfo.ContractionOff &&
832 (Flags & SPIRV::FPFastMathMode::AllowContract))
834 "Conflicting FPFastMathFlags: ContractionOff and AllowContract");
835
836 if (FPFastMathDefaultInfo.SignedZeroInfNanPreserve &&
837 !(Flags &
838 (SPIRV::FPFastMathMode::NotNaN | SPIRV::FPFastMathMode::NotInf |
839 SPIRV::FPFastMathMode::NSZ))) {
840 if (FPFastMathDefaultInfo.FPFastMathDefault)
841 report_fatal_error("Conflicting FPFastMathFlags: "
842 "SignedZeroInfNanPreserve but at least one of "
843 "NotNaN/NotInf/NSZ is enabled.");
844 }
845
846 // Don't emit if none of the execution modes was used.
847 if (Flags == SPIRV::FPFastMathMode::None &&
848 !FPFastMathDefaultInfo.ContractionOff &&
849 !FPFastMathDefaultInfo.SignedZeroInfNanPreserve &&
850 !FPFastMathDefaultInfo.FPFastMathDefault)
851 continue;
852
853 // Retrieve the constant instruction for the immediate value.
854 auto It = ConstMap.find(Flags);
855 if (It == ConstMap.end())
856 report_fatal_error("Expected constant instruction for FP Fast Math "
857 "Mode operand of FPFastMathDefault execution mode.");
858 const MachineInstr *ConstMI = It->second;
859 MCRegister ConstReg = MAI->getRegisterAlias(
860 ConstMI->getMF(), ConstMI->getOperand(0).getReg());
861 Inst.addOperand(MCOperand::createReg(ConstReg));
862 outputMCInst(Inst);
863 }
864 }
865}
866
867void SPIRVAsmPrinter::outputModuleSections() {
868 const Module *M = MMI->getModule();
869 // Get the global subtarget to output module-level info.
870 ST = static_cast<const SPIRVTargetMachine &>(TM).getSubtargetImpl();
871 TII = ST->getInstrInfo();
872 MAI = GetMAI();
873 assert(ST && TII && MAI && M && "Module analysis is required");
874
875 if (!AuxDataHandler &&
876 spirvPreserveAuxData(ST->getCLOpts(), M->getTargetTriple()))
877 AuxDataHandler = std::make_unique<SPIRVAuxDataHandler>(*this, *M);
878
879 // Let the NSDI handler add its extension and ext inst import entry to MAI
880 // before the module header sections are emitted.
881 if (NSDebugHandler)
882 NSDebugHandler->prepareModuleOutput(*ST, *MAI);
883 if (AuxDataHandler)
884 AuxDataHandler->prepareModuleOutput(*ST, *MAI);
885 // Generate the module-scope NSDI to decide if extensions (like
886 // SPV_KHR_relaxed_extended_instruction) are actually needed.
887 if (NSDebugHandler)
888 NSDebugHandler->generateModuleDebugInfo(*MAI);
889
890 // Output instructions according to the Logical Layout of a Module:
891 // 1,2. All OpCapability instructions, then optional OpExtension
892 // instructions.
893 outputGlobalRequirements();
894 // 3. Optional OpExtInstImport instructions.
895 outputOpExtInstImports(*M);
896 // 4. The single required OpMemoryModel instruction.
897 outputOpMemoryModel();
898 // 5. All entry point declarations, using OpEntryPoint.
899 outputEntryPoints();
900 // 6. Execution-mode declarations, using OpExecutionMode or
901 // OpExecutionModeId.
902 outputExecutionMode(*M);
903 // 7a. Debug: all OpString, OpSourceExtension, OpSource, and
904 // OpSourceContinued, without forward references.
905 outputDebugSourceAndStrings(*M);
906 // 7b. Debug: all OpName and all OpMemberName.
907 outputModuleSection(SPIRV::MB_DebugNames);
908 for (const auto &[Reg, Name] : MAI->MBBNames) {
909 MCInst Inst;
910 Inst.setOpcode(SPIRV::OpName);
912 addStringImm(Name, Inst);
913 outputMCInst(Inst);
914 }
915 // 7c. Debug: all OpModuleProcessed instructions.
916 outputModuleSection(SPIRV::MB_DebugModuleProcessed);
917 // xxx. SPV_INTEL_memory_access_aliasing instructions go before 8.
918 // "All annotation instructions"
919 outputModuleSection(SPIRV::MB_AliasingInsts);
920 // 8. All annotation instructions (all decorations).
921 outputAnnotations(*M);
922 // 9. All type declarations (OpTypeXXX instructions), all constant
923 // instructions, and all global variable declarations. This section is
924 // the first section to allow use of: OpLine and OpNoLine debug information;
925 // non-semantic instructions with OpExtInst.
926 outputModuleSection(SPIRV::MB_TypeConstVars);
927 // 10. All global NonSemantic.Shader.DebugInfo.100 instructions. The
928 // SPIRVNonSemanticDebugHandler outputs the MCInsts it buffered;
929 // the MB_NonSemanticGlobalDI section in MAI is intentionally left empty.
930 if (NSDebugHandler)
931 NSDebugHandler->emitNonSemanticGlobalDebugInfo(*MAI);
932 if (AuxDataHandler)
933 AuxDataHandler->emitAuxData(*MAI);
934 // 11. All function declarations (functions without a body).
935 outputExtFuncDecls();
936 // 12. All function definitions (functions with a body).
937 // This is done in regular function output.
938}
939
940bool SPIRVAsmPrinter::doInitialization(Module &M) {
941 ModuleSectionsEmitted = false;
942 if (!M.getModuleInlineAsm().empty()) {
943 M.getContext().emitError(
944 "SPIR-V does not support module-level inline assembly");
945 M.removeModuleInlineAsm();
946 }
947
948 // Register the NSDI handler before calling the base class so that
949 // AsmPrinter::doInitialization() calls Handler->beginModule(M) for it.
950 if (M.getNamedMetadata("llvm.dbg.cu")) {
951 auto Handler = std::make_unique<SPIRVNonSemanticDebugHandler>(*this);
952 NSDebugHandler = Handler.get();
953 addAsmPrinterHandler(std::move(Handler));
954 }
955 // We need to call the parent's one explicitly.
957}
958
959char SPIRVAsmPrinter::ID = 0;
960
961INITIALIZE_PASS(SPIRVAsmPrinter, "spirv-asm-printer", "SPIRV Assembly Printer",
962 false, false)
963
964// Force static initialization.
966LLVMInitializeSPIRVAsmPrinter() {
970}
971
974 SPIRVAsmPrinter &AsmPrinter = static_cast<SPIRVAsmPrinter &>(
975 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
978 return PreservedAnalyses::all();
979}
980
984 SPIRVAsmPrinter &AsmPrinter = static_cast<SPIRVAsmPrinter &>(
986 .getCachedResult<AsmPrinterAnalysis>(*MF.getFunction().getParent())
987 ->getPrinter());
989 AsmPrinter.GetMAI = [&MFAM, &MF] {
991 .getCachedResult<SPIRVModuleAnalysis>(*MF.getFunction().getParent());
992 };
994 return PreservedAnalyses::all();
995}
996
999 SPIRVAsmPrinter &AsmPrinter = static_cast<SPIRVAsmPrinter &>(
1000 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
1002 AsmPrinter.GetMAI = [&MAM, &M] {
1003 return MAM.getCachedResult<SPIRVModuleAnalysis>(M);
1004 };
1006 return PreservedAnalyses::all();
1007}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static void addOpsFromMDNode(MDNode *MDN, MCInst &Inst, SPIRV::ModuleAnalysisInfo *MAI)
static bool isFuncOrHeaderInstr(const MachineInstr *MI, const SPIRVInstrInfo *TII)
static unsigned encodeVecTypeHint(Type *Ty)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:561
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
std::unique_ptr< MCStreamer > && Streamer
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:93
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
bool doFinalization(Module &M) override
Shut down the asmprinter.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition AsmPrinter.h:478
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Class to represent fixed width SIMD vectors.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Module * getParent()
Get the module that this global value is contained inside of...
Class to represent integer types.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
void addOperand(const MCOperand Op)
Definition MCInst.h:214
void setOpcode(unsigned Op)
Definition MCInst.h:200
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
Metadata node.
Definition Metadata.h:1087
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
const GlobalValue * getGlobal() const
int64_t getImm() const
MachineBasicBlock * getMBB() const
const BlockAddress * getBlockAddress() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_FPImmediate
Floating-point immediate operand.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
const MachineFunction & getMF() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
constexpr bool isValid() const
Definition Register.h:109
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static const char * getRegisterName(MCRegister Reg)
void lower(const MachineInstr *MI, MCInst &OutMI, SPIRV::ModuleAnalysisInfo *MAI) const
AsmPrinter handler that emits NonSemantic.Shader.DebugInfo.100 (NSDI) instructions for the SPIR-V bac...
void emitNonSemanticGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &)
Output the module-scope NSDI built by generateModuleDebugInfo().
void emitNonSemanticDebugStrings(SPIRV::ModuleAnalysisInfo &)
Output the NSDI OpStrings built by generateModuleDebugInfo() into the debug section (section 7 of the...
void prepareModuleOutput(const SPIRVSubtarget &ST, SPIRV::ModuleAnalysisInfo &MAI)
Add SPV_KHR_non_semantic_info extension and NonSemantic.Shader.DebugInfo.100 ext inst set entry to MA...
void generateModuleDebugInfo(SPIRV::ModuleAnalysisInfo &MAI)
Buffer the module-scope NSDI and add SPV_KHR_relaxed_extended_instruction to MAI if a forward referen...
void notifyEntryLabelEmitted(const MachineFunction &MF)
Called after the synthesized entry OpLabel has been emitted.
const SPIRVInstrInfo * getInstrInfo() const override
bool isAtLeastSPIRVVer(VersionTuple VerToCompareTo) const
SPIRVGlobalRegistry * getSPIRVGlobalRegistry() const
const SPIRVOptions & getCLOpts() const
VersionTuple getSPIRVVersion() const
unsigned getBound() const
bool canUseExtension(SPIRV::Extension::Extension E) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
unsigned getMajor() const
Retrieve the major version number.
std::optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI void parseThreadCounts(StringRef Str, unsigned &Count1, unsigned &Count2, unsigned &Count3)
Definition HLSLUtils.cpp:23
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
void addStringImm(StringRef Str, MCInst &Inst)
Target & getTheSPIRV32Target()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
DenseMap< Value *, Constant * > ConstMap
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
std::string getExtInstSetName(SPIRV::InstructionSet::InstructionSet Set)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
SPIRVFPContractMode
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
std::string getSymbolicOperandMnemonic(SPIRV::OperandCategory::OperandCategory Category, int32_t Value)
bool isEntryPoint(const Function &F)
Target & getTheSPIRV64Target()
Target & getTheSPIRVLogicalTarget()
DWARFExpression::Operation Op
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Type * getMDOperandAsType(const MDNode *N, unsigned I)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool spirvPreserveAuxData(const SPIRVOptions &CLOpts, const Triple &TT)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
static size_t computeFPFastMathDefaultInfoVecIndex(size_t BitWidth)
Definition SPIRVUtils.h:149
MCRegister getGlobalObjReg(const GlobalObject *GO)