LLVM 24.0.0git
SPIRVNonSemanticDebugHandler.cpp
Go to the documentation of this file.
1//===-- SPIRVNonSemanticDebugHandler.cpp - NSDI AsmPrinter handler -*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
12#include "SPIRVSubtarget.h"
13#include "SPIRVTargetMachine.h"
14#include "SPIRVUtils.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/Twine.h"
25#include "llvm/IR/DebugInfo.h"
31#include "llvm/IR/Module.h"
32#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCStreamer.h"
36#include "llvm/Support/Path.h"
37#include <cassert>
38
39using namespace llvm;
40
41namespace {
42
43/// Look up \p Key in a register map and return its value, or std::nullopt when
44/// the key is absent.
45template <typename MapT>
46static std::optional<MCRegister> lookupOptReg(const MapT &Map,
47 typename MapT::key_type Key) {
48 auto It = Map.find(Key);
49 if (It == Map.end())
50 return std::nullopt;
51 assert(It->second.isValid() && "invalid register stored in map");
52 return It->second;
53}
54
55enum : uint32_t {
56 NSDIFlagIsProtected = 1u << 0,
57 NSDIFlagIsPrivate = 1u << 1,
58 NSDIFlagIsPublic = NSDIFlagIsPrivate | NSDIFlagIsProtected,
59 NSDIFlagIsLocal = 1u << 2,
60 NSDIFlagIsDefinition = 1u << 3,
61 NSDIFlagFwdDecl = 1u << 4,
62 NSDIFlagArtificial = 1u << 5,
63 NSDIFlagExplicit = 1u << 6,
64 NSDIFlagPrototyped = 1u << 7,
65 NSDIFlagObjectPointer = 1u << 8,
66 NSDIFlagStaticMember = 1u << 9,
67 NSDIFlagIndirectVariable = 1u << 10,
68 NSDIFlagLValueReference = 1u << 11,
69 NSDIFlagRValueReference = 1u << 12,
70 NSDIFlagIsOptimized = 1u << 13,
71 NSDIFlagIsEnumClass = 1u << 14,
72 NSDIFlagTypePassByValue = 1u << 15,
73 NSDIFlagTypePassByReference = 1u << 16,
74 NSDIFlagUnknownPhysicalLayout = 1u << 17,
75};
76
77static uint32_t mapDIFlagsToNonSemantic(DINode::DIFlags DFlags) {
78 uint32_t Flags = 0;
79 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPublic)
80 Flags |= NSDIFlagIsPublic;
81 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagProtected)
82 Flags |= NSDIFlagIsProtected;
83 if ((DFlags & DINode::FlagAccessibility) == DINode::FlagPrivate)
84 Flags |= NSDIFlagIsPrivate;
85 if (DFlags & DINode::FlagFwdDecl)
86 Flags |= NSDIFlagFwdDecl;
87 if (DFlags & DINode::FlagArtificial)
88 Flags |= NSDIFlagArtificial;
89 if (DFlags & DINode::FlagExplicit)
90 Flags |= NSDIFlagExplicit;
91 if (DFlags & DINode::FlagPrototyped)
92 Flags |= NSDIFlagPrototyped;
93 if (DFlags & DINode::FlagObjectPointer)
94 Flags |= NSDIFlagObjectPointer;
95 if (DFlags & DINode::FlagStaticMember)
96 Flags |= NSDIFlagStaticMember;
97 if (DFlags & DINode::FlagLValueReference)
98 Flags |= NSDIFlagLValueReference;
99 if (DFlags & DINode::FlagRValueReference)
100 Flags |= NSDIFlagRValueReference;
101 if (DFlags & DINode::FlagTypePassByValue)
102 Flags |= NSDIFlagTypePassByValue;
103 if (DFlags & DINode::FlagTypePassByReference)
104 Flags |= NSDIFlagTypePassByReference;
105 if (DFlags & DINode::FlagEnumClass)
106 Flags |= NSDIFlagIsEnumClass;
107 return Flags;
108}
109
110static uint32_t transDebugFlags(const DINode *DN) {
111 uint32_t Flags = 0;
112 if (const auto *GV = dyn_cast<DIGlobalVariable>(DN)) {
113 if (GV->isLocalToUnit())
114 Flags |= NSDIFlagIsLocal;
115 if (GV->isDefinition())
116 Flags |= NSDIFlagIsDefinition;
117 }
118 if (const auto *SP = dyn_cast<DISubprogram>(DN)) {
119 if (SP->isLocalToUnit())
120 Flags |= NSDIFlagIsLocal;
121 if (SP->isOptimized())
122 Flags |= NSDIFlagIsOptimized;
123 if (SP->isDefinition())
124 Flags |= NSDIFlagIsDefinition;
125 Flags |= mapDIFlagsToNonSemantic(SP->getFlags());
126 }
127 if (DN->getTag() == dwarf::DW_TAG_reference_type)
128 Flags |= NSDIFlagLValueReference;
129 if (DN->getTag() == dwarf::DW_TAG_rvalue_reference_type)
130 Flags |= NSDIFlagRValueReference;
131 if (const auto *Ty = dyn_cast<DIType>(DN))
132 Flags |= mapDIFlagsToNonSemantic(Ty->getFlags());
133 if (const auto *LV = dyn_cast<DILocalVariable>(DN))
134 Flags |= mapDIFlagsToNonSemantic(LV->getFlags());
135 return Flags;
136}
137
138// Map a DWARF composite tag to a NonSemantic.Shader.DebugInfo Composite Type
139// value: Class 0, Structure 1, Union 2.
140static uint32_t mapCompositeTypeTag(unsigned Tag) {
141 switch (Tag) {
142 case dwarf::DW_TAG_class_type:
143 return 0;
144 case dwarf::DW_TAG_structure_type:
145 return 1;
146 case dwarf::DW_TAG_union_type:
147 return 2;
148 default:
149 reportFatalInternalError("unexpected DWARF composite tag " + Twine(Tag) +
150 ". Expecting 0, 1 or 2");
151 }
152}
153
154// Map a DWARF qualifier tag to a NonSemantic.Shader.DebugInfo Type Qualifier
155// value: Const 0, Volatile 1, Restrict 2, Atomic 3.
156static std::optional<uint32_t> mapTypeQualifierTag(unsigned Tag) {
157 switch (Tag) {
158 case dwarf::DW_TAG_const_type:
159 return 0;
160 case dwarf::DW_TAG_volatile_type:
161 return 1;
162 case dwarf::DW_TAG_restrict_type:
163 return 2;
164 case dwarf::DW_TAG_atomic_type:
165 return 3;
166 default:
167 return std::nullopt;
168 }
169}
170
171static const MachineInstr *
172findLastFunctionOpVariableDeclaration(const MachineFunction &MF,
174
175 // We iterate over the instructions to find the last OpVariable instruction if
176 // any. The following SPIRV rule is used to terminate the traversal earlier:
177 // SPIR-V 2.16.1, Function Structure: "All OpVariable instructions in a
178 // function must be in the first block in the function. These instructions,
179 // together with any intermixed OpLine and OpNoLine instructions, must be the
180 // first instructions in that block."
181 const MachineInstr *LastOpVariable = nullptr;
182 bool SeenOpVariable = false;
183 for (const MachineInstr &MI : MF.front()) {
184 if (MI.getOpcode() == SPIRV::OpVariable) {
185 SeenOpVariable = true;
186 if (!MAI.getSkipEmission(&MI))
187 LastOpVariable = &MI;
188 continue;
189 }
190
191 bool CanInterleaveWithOpVariable =
192 MI.getOpcode() == SPIRV::OpLine || MI.getOpcode() == SPIRV::OpNoLine;
193 if (SeenOpVariable && !CanInterleaveWithOpVariable &&
194 !MAI.getSkipEmission(&MI))
195 break;
196 }
197 return LastOpVariable;
198}
199
200} // namespace
201
205
206// Map DWARF source language codes to NonSemantic.Shader.DebugInfo.100 source
207// language codes. Values are from the SourceLanguage enum in the
208// NonSemantic.Shader.DebugInfo.100 specification, section 4.3.
209unsigned SPIRVNonSemanticDebugHandler::toNSDISrcLang(unsigned DwarfSrcLang) {
210 switch (DwarfSrcLang) {
211 case dwarf::DW_LANG_OpenCL:
212 return 3; // OpenCL_C
213 case dwarf::DW_LANG_OpenCL_CPP:
214 return 4; // OpenCL_CPP
215 case dwarf::DW_LANG_CPP_for_OpenCL:
216 return 6; // CPP_for_OpenCL
217 case dwarf::DW_LANG_GLSL:
218 return 2; // GLSL
219 case dwarf::DW_LANG_HLSL:
220 return 5; // HLSL
221 case dwarf::DW_LANG_SYCL:
222 return 7; // SYCL
223 case dwarf::DW_LANG_Zig:
224 return 12; // Zig
225 default:
226 return 0; // Unknown
227 }
228}
229
230static bool isBooleanType(const DIBasicType *BT) {
231 return BT->getEncoding() == dwarf::DW_ATE_boolean;
232}
233
234// \p Value truncated to the width of \p BT, or 0 or 1 for a boolean.
236 // A boolean is one of two values and a DIBasicType may give it no size, so
237 // masking to its width would turn every true into a false.
238 if (isBooleanType(BT))
239 return Value != 0;
240 unsigned Width = BT->getSizeInBits();
241 return Width >= 64 ? Value : Value & ((uint64_t(1) << Width) - 1);
242}
243
244// \p Value truncated to the width of \p BT. APInt::getZExtValue() asserts
245// above 64 bits, so the truncation comes first.
247 unsigned Width = isBooleanType(BT) ? 1 : BT->getSizeInBits();
248 return constantBits(Value.getActiveBits() > 64
249 ? Value.trunc(std::min(Width, 64u)).getZExtValue()
250 : Value.getZExtValue(),
251 BT);
252}
253
254// The DIBasicType that \p Ty resolves to through typedefs and qualifiers, or
255// null.
256static const DIBasicType *stripToScalarType(const DIType *Ty) {
257 // visitDIDerivedType accepts a cyclic chain of typedefs and qualifiers, so
258 // this stops once it reaches an already seen type.
260 while (const auto *DT = dyn_cast_or_null<DIDerivedType>(Ty)) {
261 unsigned Tag = DT->getTag();
262 if ((Tag != dwarf::DW_TAG_typedef && !mapTypeQualifierTag(Tag)) ||
263 !Seen.insert(DT).second)
264 return nullptr;
265 Ty = DT->getBaseType();
266 }
267
268 const auto *BT = dyn_cast_or_null<DIBasicType>(Ty);
269 if (!BT)
270 return nullptr;
271
272 // OpTypeBool carries no width, so a boolean of any size is accepted.
273 if (isBooleanType(BT))
274 return BT;
275
276 unsigned Size = BT->getSizeInBits();
277 switch (BT->getEncoding()) {
278 case dwarf::DW_ATE_signed:
279 case dwarf::DW_ATE_unsigned:
280 case dwarf::DW_ATE_signed_char:
281 case dwarf::DW_ATE_unsigned_char:
282 return Size == 8 || Size == 16 || Size == 32 || Size == 64 ? BT : nullptr;
283 case dwarf::DW_ATE_float:
284 // SPIR-V has no 8-bit float.
285 return Size == 16 || Size == 32 || Size == 64 ? BT : nullptr;
286 default:
287 return nullptr;
288 }
289}
290
291// Collect distinct DILocations and DILocalVariables from LLVM IR.
292//
293// DILocations come from instruction debug locations and from the debug records
294// attached to them. DebugLine pre-emission and MIR lookups assume every
295// machine-instruction debug location already appeared here; a codegen-only
296// location would not be collected and emission will be skipped.
297//
298// DILocalVariables come from the DbgVariableRecords attached to instructions
299// and from the retained nodes of each DISubprogram. Retained nodes are needed
300// because a variable with no remaining debug record (e.g. optimized away) must
301// still get a DebugLocalVariable.
303 const Module &M, SetVector<const DILocation *> &Locations,
305 for (const Function &F : M) {
306 const DISubprogram *SP = F.getSubprogram();
307 if (!SP)
308 continue;
309 for (const MDNode *N : SP->getRetainedNodes())
310 if (const auto *LV = dyn_cast_or_null<DILocalVariable>(N))
311 LVs.insert(LV);
312 for (const Instruction &I : instructions(F)) {
313 if (const DILocation *DL = I.getDebugLoc().get())
314 Locations.insert(DL);
315 for (DbgRecord &DR : I.getDbgRecordRange()) {
316 if (const DILocation *DL = DR.getDebugLoc().get())
317 Locations.insert(DL);
318 if (const auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
319 if (const DILocalVariable *LV = DVR->getVariable())
320 LVs.insert(LV);
321 }
322 }
323 }
324}
325
326// Insert \p S and its enclosing DILexicalBlock/DINamespace/DILexicalBlockFile
327// chain into \p Out, parent before child, so single-pass emission never needs
328// a forward reference for the Parent operand.
331 // Walk up child-first, then insert in reverse to get parents in first.
333 while (S && !Out.contains(S) &&
335 Chain.push_back(S);
336 S = S->getScope();
337 }
338 Out.insert(Chain.rbegin(), Chain.rend());
339}
340
342 // The base class sets Asm = nullptr when the module has no compile units,
343 // and initializes lexical scope tracking otherwise.
345
346 if (!Asm)
347 return;
348
349 CompileUnits.clear();
350 DebugTypes.clear();
351 EnumCompileUnits.clear();
352 Subprograms.clear();
353 UniqueDebugLocations.clear();
354 GlobalVariableDebugInfoMap.clear();
355 LocalVariables.clear();
356 DebugLocalVariableRegs.clear();
357 DebugExpressionRegs.clear();
358 LexicalBlocks.clear();
359 DebugScopeRegs.clear();
360 ScopesInProgress.clear();
361 HasRelaxedExtInst = false;
362 FailedScopes.clear();
363 DebugInlinedAtRegs.clear();
364 ScopeToPathOpStringReg.clear();
365 DebugSourceRegByFileStr.clear();
366 OpStringContentCache.clear();
367 ScalarTypeCache.clear();
368 ScalarConstantCache.clear();
369 ConstantValueRegs.clear();
370 DebugOperationCache.clear();
371 DebugExpressionCache.clear();
372 ModuleScopeIds.clear();
373 GlobalDIEmitted = false;
374 GlobalNSDIEnabled = false;
375 CurrentMAI = nullptr;
376#ifndef NDEBUG
377 NonSemanticOpStringsSectionEmitted = false;
378#endif
379 CachedDebugInfoNoneReg = MCRegister();
380 CachedEmptyStringReg = MCRegister();
381 CachedOpTypeVoidReg = MCRegister();
382 CachedOpTypeInt32Reg = MCRegister();
383
384 // Collect compile-unit info: file paths and source languages.
385 for (const DICompileUnit *CU : M->debug_compile_units()) {
386 const DIFile *File = CU->getFile();
387 CompileUnitInfo Info;
388 Info.TheCU = CU;
389 if (sys::path::is_absolute(File->getFilename()))
390 Info.FilePath = File->getFilename();
391 else
392 sys::path::append(Info.FilePath, File->getDirectory(),
393 File->getFilename());
394 // getName() returns the language code regardless of whether the name is
395 // versioned. getUnversionedName() would assert on versioned names.
396 Info.SpirvSourceLanguage = toNSDISrcLang(CU->getSourceLanguage().getName());
397 CompileUnits.push_back(std::move(Info));
398 for (const DICompositeType *ET : CU->getEnumTypes())
399 EnumCompileUnits.try_emplace(ET, CU);
400 }
401
402 // Collect DWARF version from module flags. For CodeView modules there is no
403 // "Dwarf Version" flag; DwarfVersion remains 0, which is the correct value
404 // for the DebugCompilationUnit DWARF Version operand in that case.
405 if (const NamedMDNode *Flags = M->getNamedMetadata("llvm.module.flags")) {
406 for (const auto *Op : Flags->operands()) {
407 const MDOperand &NameOp = Op->getOperand(1);
408 if (NameOp.equalsStr("Dwarf Version"))
409 DwarfVersion =
411 cast<ConstantAsMetadata>(Op->getOperand(2))->getValue())
412 ->getSExtValue();
413 }
414 }
415
416 // Find all debug info types that may be referenced by NSDI instructions.
417 // Member types are not roots: each one is emitted only from its composite.
418 DebugInfoFinder Finder;
419 Finder.processModule(*M);
420 copy_if(Finder.types(), std::back_inserter(DebugTypes), [](const DIType *Ty) {
421 return Ty->getTag() != dwarf::DW_TAG_member;
422 });
423
424 Subprograms.assign(Finder.subprograms().begin(), Finder.subprograms().end());
425
426 // Walk LLVM globals to map each DIGlobalVariable to its llvm::GlobalVariable.
428 for (const GlobalVariable &G : M->globals()) {
430 G.getDebugInfo(GVEs);
431 for (DIGlobalVariableExpression *GVE : GVEs) {
432 if (const DIGlobalVariable *GV = GVE->getVariable()) {
433 DIGVToLLVMGV.try_emplace(GV, &G);
434 }
435 }
436 }
437
438 for (const DIGlobalVariableExpression *GVE : Finder.global_variables()) {
439 const DIGlobalVariable *GV = GVE->getVariable();
440 const DIExpression *Expr = GVE->getExpression();
441 GlobalVariableDebugInfoMap.try_emplace(
442 GV, GlobalVariableDebugInfo{Expr, DIGVToLLVMGV.lookup(GV)});
443 }
444
445 collectDebugLocationsAndLocalVariables(*M, UniqueDebugLocations,
446 LocalVariables);
447
448 // DILexicalBlock and DINamespace scopes are lowered to DebugLexicalBlock.
449 // DILexicalBlockFile is lowered to DebugLexicalBlockDiscriminator.
450 // Collect them in parent-before-child order so they can be emitted in a
451 // single pass.
452 for (const DIScope *S : Finder.scopes())
453 collectLexicalBlockChain(S, LexicalBlocks);
454}
455
456// The emitted SPIR-V id of \p MI, or an invalid register when \p MI defines
457// no result.
460 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg() ||
461 !MI.getOperand(0).isDef())
462 return MCRegister();
463 return MAI.getRegisterAlias(MI.getMF(), MI.getOperand(0).getReg());
464}
465
468 if (CompileUnits.empty())
469 return;
470 if (!ST.canUseExtension(SPIRV::Extension::SPV_KHR_non_semantic_info))
471 return;
472
473 // Add the extension to requirements so OpExtension is output.
474 MAI.Reqs.addExtension(SPIRV::Extension::SPV_KHR_non_semantic_info);
475
476 HasRelaxedExtInst =
477 CLOpts.debug_scope_forward_refs &&
478 ST.canUseExtension(
479 SPIRV::Extension::SPV_KHR_relaxed_extended_instruction);
480 if (HasRelaxedExtInst)
481 MAI.Reqs.addExtension(
482 SPIRV::Extension::SPV_KHR_relaxed_extended_instruction);
483
484 // Add the NonSemantic.Shader.DebugInfo.100 entry to ExtInstSetMap so that
485 // outputOpExtInstImports() emits the OpExtInstImport instruction. Allocate a
486 // fresh result ID for it now; the same ID is used in emitExtInst() operands.
487 if (!MAI.ExtInstSetMap.count(NSSet))
488 MAI.ExtInstSetMap[NSSet] = MAI.getNextIDRegister();
489
491 if (MCRegister Id = getResultId(*MI, MAI))
492 ModuleScopeIds.insert(Id);
493 }
494}
495
496void SPIRVNonSemanticDebugHandler::emitMCInst(MCInst &Inst) {
497 Asm->OutStreamer->emitInstruction(Inst, Asm->getSubtargetInfo());
498}
499
501SPIRVNonSemanticDebugHandler::emitOpString(StringRef S,
504 MCInst Inst;
505 Inst.setOpcode(SPIRV::OpString);
507 addStringImm(S, Inst);
508 emitMCInst(Inst);
509 return Reg;
510}
511
512MCRegister SPIRVNonSemanticDebugHandler::emitOpStringIfNew(
514#ifndef NDEBUG
515 assert(!NonSemanticOpStringsSectionEmitted &&
516 "emitOpStringIfNew is only valid while emitting SPIR-V section 7");
517#endif
518 auto [It, Inserted] = OpStringContentCache.try_emplace(S, MCRegister());
519 if (Inserted)
520 It->second = emitOpString(S, MAI);
521
522 return It->second;
523}
524
525MCRegister SPIRVNonSemanticDebugHandler::getCachedOpStringReg(StringRef S) {
526#ifndef NDEBUG
527 assert(NonSemanticOpStringsSectionEmitted &&
528 "getCachedOpStringReg requires emitNonSemanticDebugStrings() first");
529#endif
530 auto It = OpStringContentCache.find(S);
531 assert(It != OpStringContentCache.end() &&
532 "NSDI OpString missing from cache; emitNonSemanticDebugStrings must "
533 "cache every string used in section 10");
534 return It->second;
535}
536
537MCRegister SPIRVNonSemanticDebugHandler::emitAndCacheScopePathOpStringReg(
538 const DIScope *Scope, SPIRV::ModuleAnalysisInfo &MAI) {
539 auto [It, Inserted] = ScopeToPathOpStringReg.try_emplace(Scope, MCRegister());
540 if (Inserted)
541 It->second = emitOpStringIfNew(getDebugFullPath(Scope), MAI);
542 return It->second;
543}
544
545MCRegister SPIRVNonSemanticDebugHandler::getCachedScopePathOpStringReg(
546 const DIScope *Scope, bool UseEmptyPathIfNullScope) {
547 if (!Scope) {
548 assert(UseEmptyPathIfNullScope &&
549 "null scope path lookup requires UseEmptyPathIfNullScope");
550 assert(CachedEmptyStringReg.isValid() &&
551 "empty path OpString must be cached in emitNonSemanticDebugStrings");
552 return CachedEmptyStringReg;
553 }
554 auto It = ScopeToPathOpStringReg.find(Scope);
555 assert(It != ScopeToPathOpStringReg.end() &&
556 "path OpString must be cached in emitNonSemanticDebugStrings");
557 MCRegister FileStrReg = It->second;
558 assert(FileStrReg.isValid() && "path OpString id must be valid once cached");
559 return FileStrReg;
560}
561
562MCRegister SPIRVNonSemanticDebugHandler::emitOpConstantI32(
563 uint32_t Value, MCRegister I32TypeReg, SPIRV::ModuleAnalysisInfo &MAI) {
564 return findOrEmitConstant(SPIRV::OpConstantI, I32TypeReg, Value,
565 /*Width=*/32, MAI);
566}
567
568bool SPIRVNonSemanticDebugHandler::markForwardReferencedOperands(
570 bool HasForwardRef = false;
571 for (auto &Entry : ScopesInProgress) {
572 InProgressScope &InProgress = Entry.second;
573 assert(InProgress.Id.isValid() &&
574 "in-progress scope must have a reserved id");
575 if (!is_contained(Operands, InProgress.Id))
576 continue;
577 InProgress.ForwardReferenced = true;
578 HasForwardRef = true;
579 }
580 return HasForwardRef;
581}
582
583MCRegister SPIRVNonSemanticDebugHandler::emitExtInst(
584 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
585 MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
587 std::optional<MCRegister> ResultReg) {
588 assert((!ResultReg || ResultReg->isValid()) &&
589 "ResultReg must be a valid id when provided");
590 MCRegister Reg = ResultReg ? *ResultReg : MAI.getNextIDRegister();
591
592 // An operand that is still an in-progress scope id is a forward reference.
593 // Tag the instruction with OpExtInstWithForwardRefsKHR and remember the id:
594 // if that scope later fails, the id still needs a definition.
595 bool HasForwardRef =
596 HasRelaxedExtInst && markForwardReferencedOperands(Operands);
597
598 MCInst Inst;
599 Inst.setOpcode(HasForwardRef ? SPIRV::OpExtInstWithForwardRefsKHR
600 : SPIRV::OpExtInst);
602 Inst.addOperand(MCOperand::createReg(VoidTypeReg));
603 Inst.addOperand(MCOperand::createReg(ExtInstSetReg));
604 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Opcode)));
605 for (MCRegister R : Operands)
607 emitMCInst(Inst);
608 return Reg;
609}
610
611MCRegister SPIRVNonSemanticDebugHandler::getOrEmitOpTypeVoidReg(
613 if (!CachedOpTypeVoidReg.isValid())
614 CachedOpTypeVoidReg = findOrEmitOpTypeVoid(MAI);
615 return CachedOpTypeVoidReg;
616}
617
618MCRegister SPIRVNonSemanticDebugHandler::getOrEmitOpTypeInt32Reg(
620 if (!CachedOpTypeInt32Reg.isValid())
621 CachedOpTypeInt32Reg = findOrEmitOpTypeInt32(MAI);
622 return CachedOpTypeInt32Reg;
623}
624
625MCRegister SPIRVNonSemanticDebugHandler::findOrEmitOpTypeVoid(
627 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
628 if (MI->getOpcode() == SPIRV::OpTypeVoid)
629 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
630 }
631 MCRegister Reg = MAI.getNextIDRegister();
632 MCInst Inst;
633 Inst.setOpcode(SPIRV::OpTypeVoid);
635 emitMCInst(Inst);
636 return Reg;
637}
638
639// Whether declaring \p BT's SPIR-V type would require a capability. The type
640// width determines the requirement: Int8, Int16, Int64, Float16 and Float64 in
641// SPIRVModuleAnalysis::collectReqs(). A boolean and a 32-bit scalar are free.
643 if (isBooleanType(BT))
644 return false;
645 unsigned Width = BT->getSizeInBits();
646 return Width != 32;
647}
648
649MCRegister SPIRVNonSemanticDebugHandler::findOrEmitScalarType(
651 bool IsBool = isBooleanType(BT);
652 bool IsFloat = BT->getEncoding() == dwarf::DW_ATE_float;
653 unsigned Opcode = IsBool ? SPIRV::OpTypeBool
654 : IsFloat ? SPIRV::OpTypeFloat
655 : SPIRV::OpTypeInt;
656 // Two DIBasicTypes can describe one SPIR-V type, and OpTypeBool has no
657 // width, so the key is the opcode and the width rather than the node.
658 int64_t Width = IsBool ? 0 : BT->getSizeInBits();
659
660 // OpTypeInt 32 0 is already owned by getOrEmitOpTypeInt32Reg(), which every
661 // line and column constant needs. Declaring a second one is a duplicate type
662 // declaration, which the validator rejects.
663 if (Opcode == SPIRV::OpTypeInt && Width == 32)
664 return getOrEmitOpTypeInt32Reg(MAI);
665
666 auto [CacheIt, Inserted] =
667 ScalarTypeCache.try_emplace({Opcode, Width}, MCRegister());
668 if (!Inserted)
669 return CacheIt->second;
670
671 // The backend writes every integer type with signedness 0, so a signed and
672 // an unsigned DIBasicType of the same width share one OpTypeInt.
673 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
674 if (MI->getOpcode() != Opcode)
675 continue;
676 if (IsBool || (MI->getOperand(1).getImm() == Width &&
677 (IsFloat || MI->getOperand(2).getImm() == 0))) {
678 CacheIt->second =
679 MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
680 return CacheIt->second;
681 }
682 }
683
684 // A non-semantic instruction "has no semantic impact, and can be safely
685 // removed from the module", so debug info must leave the module's
686 // requirements alone. Declaring OpTypeInt 64 forces Int64, which Vulkan ties
687 // to a device feature, so this returns nothing if the type requires a new
688 // capability.
690 return MCRegister();
691
692 MCRegister Reg = MAI.getNextIDRegister();
693 MCInst Inst;
694 Inst.setOpcode(Opcode);
696 if (!IsBool) {
697 Inst.addOperand(MCOperand::createImm(Width));
698 if (!IsFloat)
700 }
701 emitMCInst(Inst);
702 CacheIt->second = Reg;
703 return Reg;
704}
705
706// Whether the constant \p MI holds \p Value, read as two words when \p IsWide.
708 bool IsWide) {
709 unsigned Words = IsWide ? 2 : 1;
710 if (MI.getNumOperands() < 2 + Words)
711 return false;
712 uint64_t Found = 0;
713 for (unsigned I = 0; I < Words; ++I) {
714 if (!MI.getOperand(2 + I).isImm())
715 return false;
716 Found |= static_cast<uint64_t>(
717 static_cast<uint32_t>(MI.getOperand(2 + I).getImm()))
718 << (32 * I);
719 }
720 return Found == Value;
721}
722
723MCRegister SPIRVNonSemanticDebugHandler::findModuleConstant(
724 unsigned Opcode, MCRegister TypeReg, uint64_t Value, bool IsBool,
725 bool IsWide, SPIRV::ModuleAnalysisInfo &MAI) {
726 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
727 if (MI->getOpcode() != Opcode || MI->getNumOperands() < 2)
728 continue;
729 if (MAI.getRegisterAlias(MI->getMF(), MI->getOperand(1).getReg()) !=
730 TypeReg)
731 continue;
732 // A boolean holds its value in its opcode, so there is nothing to compare.
733 if (!IsBool && !constantHasValue(*MI, Value, IsWide))
734 continue;
735 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
736 }
737 return MCRegister();
738}
739
740// \p Width is 0 for a boolean, whose value lives in \p Opcode.
741MCRegister SPIRVNonSemanticDebugHandler::findOrEmitConstant(
742 unsigned Opcode, MCRegister TypeReg, uint64_t Value, unsigned Width,
744 bool IsBool = Width == 0;
745 bool IsWide = Width == 64;
746
747 auto [CacheIt, Inserted] =
748 ScalarConstantCache.try_emplace({TypeReg.id(), Value}, MCRegister());
749 if (!Inserted)
750 return CacheIt->second;
751
752 MCRegister Found =
753 findModuleConstant(Opcode, TypeReg, Value, IsBool, IsWide, MAI);
754 if (Found.isValid()) {
755 CacheIt->second = Found;
756 return Found;
757 }
758
759 MCRegister Reg = MAI.getNextIDRegister();
760 MCInst Inst;
761 Inst.setOpcode(Opcode);
763 Inst.addOperand(MCOperand::createReg(TypeReg));
764 if (!IsBool) {
765 // OpConstant's Value is "the bit pattern for the constant. Types 32 bits
766 // wide or smaller take one word. Larger types take multiple words, with
767 // low-order words appearing first" (SPIR-V specification, OpConstant).
768 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Lo_32(Value))));
769 if (IsWide) {
770 Inst.addOperand(MCOperand::createImm(static_cast<int64_t>(Hi_32(Value))));
771 } else if (Width == 16) {
772 // A 16-bit float takes one word, the same as a 32-bit one, so the text
773 // printer needs the width to pick the right APFloat semantics.
775 }
776 }
777 emitMCInst(Inst);
778 CacheIt->second = Reg;
779 return Reg;
780}
781
782MCRegister SPIRVNonSemanticDebugHandler::findOrEmitScalarConstant(
784 MCRegister TypeReg = findOrEmitScalarType(BT, MAI);
785 if (!TypeReg.isValid())
786 return MCRegister();
787
788 bool IsBool = isBooleanType(BT);
789 bool IsFloat = BT->getEncoding() == dwarf::DW_ATE_float;
790 unsigned Opcode =
791 IsBool ? (Value ? SPIRV::OpConstantTrue : SPIRV::OpConstantFalse)
792 : IsFloat ? SPIRV::OpConstantF
793 : SPIRV::OpConstantI;
794 return findOrEmitConstant(Opcode, TypeReg, Value,
795 IsBool ? 0 : BT->getSizeInBits(), MAI);
796}
797
798MCRegister SPIRVNonSemanticDebugHandler::findOrEmitOpTypeInt32(
800 for (const MachineInstr *MI : MAI.getMSInstrs(SPIRV::MB_TypeConstVars)) {
801 if (MI->getOpcode() == SPIRV::OpTypeInt &&
802 MI->getOperand(1).getImm() == 32 && MI->getOperand(2).getImm() == 0)
803 return MAI.getRegisterAlias(MI->getMF(), MI->getOperand(0).getReg());
804 }
805 MCRegister Reg = MAI.getNextIDRegister();
806 MCInst Inst;
807 Inst.setOpcode(SPIRV::OpTypeInt);
809 Inst.addOperand(MCOperand::createImm(32)); // width
810 Inst.addOperand(MCOperand::createImm(0)); // signedness (unsigned)
811 emitMCInst(Inst);
812 return Reg;
813}
814
815// Each node emits its dependencies first. E.g. for `void f() { struct L; }`,
816// node L emits f, then L. Entering a scope reserves its result id. For
817// `struct S { S *p; }`, S* is a back edge. When forward references are
818// enabled, that id is used with OpExtInstWithForwardRefsKHR, and a later
819// failure defines it as DebugInfoNone only when an emitted instruction already
820// named it. Otherwise the edge is dropped and the reserved id stays unused.
821auto SPIRVNonSemanticDebugHandler::getOrCreateDebugScope(const DIScope *S)
822 -> EmitResult<MCRegister> {
823 if (!S || FailedScopes.contains(S))
824 return EmitResult<MCRegister>::unsupported();
825 if (auto Reg = lookupOptReg(DebugScopeRegs, S))
826 return EmitResult<MCRegister>::emitted(*Reg);
827
828 // Mark the scope node as in progress while its dependencies are
829 // resolved/emitted.
830 auto [InProgressIt, FirstVisit] = ScopesInProgress.try_emplace(S);
831 if (!FirstVisit) { // We hit a back edge, it is not the first insertion.
832 if (!HasRelaxedExtInst)
833 return EmitResult<MCRegister>::inProgress(); // No support for forward
834 // refs.
835 // Use the reserved id for the back edge when forward references are
836 // supported.
837 MCRegister ReservedId = InProgressIt->second.Id;
838 assert(ReservedId.isValid() && "in-progress scope must have a reserved id");
839 return EmitResult<MCRegister>::emitted(ReservedId);
840 }
841
842 // Reserve the result id first: a dependency may refer back to this scope.
843 assert(CurrentMAI && "debug scope id allocation requires CurrentMAI");
844 MCRegister Id = CurrentMAI->getNextIDRegister();
845 assert(Id.isValid() && "debug scope id must be a valid register");
846 InProgressIt->second.Id = Id;
847
848 EmitResult<PreparedScope> P = emitDebugScope(S);
849 assert((!HasRelaxedExtInst || P.Status != EmitStatus::InProgress) &&
850 "InProgress is only returned when forward references are unsupported");
851 if (!P) {
852 // Emission during recursion updates the container. Look the scope up again.
853 InProgressIt = ScopesInProgress.find(S);
854 assert(InProgressIt != ScopesInProgress.end() &&
855 "scope must stay in progress until its instruction is emitted");
856 bool ForwardReferenced = InProgressIt->second.ForwardReferenced;
857 ScopesInProgress.erase(InProgressIt);
858 // P here is either unsupported or in progress. When forward references are
859 // supported, P can only be unsupported. Define the id only when an
860 // already-emitted instruction named it.
861 if (ForwardReferenced) {
862 assert(HasRelaxedExtInst &&
863 "a forward reference requires relaxed extended instructions");
864 assert(P.Status == EmitStatus::Unsupported &&
865 "a forward-referenced scope fails as unsupported");
866 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
867 emitExtInst(SPIRV::NonSemanticExtInst::DebugInfoNone,
868 getOrEmitOpTypeVoidReg(MAI), MAI.getExtInstSetReg(NSSet), {},
869 MAI, Id);
870 }
871
872 // InProgress is a dropped back edge (when forward references are not
873 // supported). Leave it out of FailedScopes so a later walk can retry the
874 // scope. Regardless of forward references, cache unsupported scopes to
875 // avoid retrying them.
876 if (P.Status == EmitStatus::Unsupported)
877 FailedScopes.insert(S);
878 return P.Status == EmitStatus::InProgress
879 ? EmitResult<MCRegister>::inProgress()
880 : EmitResult<MCRegister>::unsupported();
881 }
882
883 // The scope was successfully emitted.
884 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
886 emitExtInst(P.Value->Opcode, getOrEmitOpTypeVoidReg(MAI),
887 MAI.getExtInstSetReg(NSSet), P.Value->Operands, MAI, Id);
888 assert(Reg == Id &&
889 "debug scope result id must reuse the id reserved at entry");
890 ScopesInProgress.erase(S);
891 assert(!GlobalNSDIEnabled &&
892 "debug type or scope created after module-scope NSDI emission");
893 DebugScopeRegs[S] = Reg;
894 return EmitResult<MCRegister>::emitted(Reg);
895}
896
897auto SPIRVNonSemanticDebugHandler::getOrCreateDebugTypeOrNone(const DIType *Ty)
898 -> EmitResult<MCRegister> {
899 if (Ty)
900 return getOrCreateDebugScope(Ty);
901 assert(CachedDebugInfoNoneReg.isValid() &&
902 "DebugInfoNone must be emitted before debug types");
903 return EmitResult<MCRegister>::emitted(CachedDebugInfoNoneReg);
904}
905
906auto SPIRVNonSemanticDebugHandler::emitDebugTypeBasic(
907 const DIBasicType *BT, MCRegister I32TypeReg,
908 SPIRV::ModuleAnalysisInfo &MAI) -> EmitResult<PreparedScope> {
909 if (!isUInt<32>(BT->getSizeInBits()))
910 return EmitResult<PreparedScope>::unsupported();
911
912 MCRegister NameReg = getCachedOpStringReg(BT->getName());
913 MCRegister SizeReg = emitOpConstantI32(
914 static_cast<uint32_t>(BT->getSizeInBits()), I32TypeReg, MAI);
915
916 // Map DWARF base type encodings to NSDI encoding codes per
917 // NonSemantic.Shader.DebugInfo.100 specification, section 4.5.
918 unsigned Encoding = 0; // Unspecified
919 switch (BT->getEncoding()) {
920 case dwarf::DW_ATE_address:
921 Encoding = 1;
922 break;
923 case dwarf::DW_ATE_boolean:
924 Encoding = 2;
925 break;
926 case dwarf::DW_ATE_float:
927 Encoding = 3;
928 break;
929 case dwarf::DW_ATE_signed:
930 Encoding = 4;
931 break;
932 case dwarf::DW_ATE_signed_char:
933 Encoding = 5;
934 break;
935 case dwarf::DW_ATE_unsigned:
936 Encoding = 6;
937 break;
938 case dwarf::DW_ATE_unsigned_char:
939 Encoding = 7;
940 break;
941 }
942 MCRegister EncodingReg = emitOpConstantI32(Encoding, I32TypeReg, MAI);
943 MCRegister FlagsReg = emitOpConstantI32(0, I32TypeReg, MAI);
944 return EmitResult<PreparedScope>::emitted(
945 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeBasic,
946 {NameReg, SizeReg, EncodingReg, FlagsReg}});
947}
948
949auto SPIRVNonSemanticDebugHandler::emitDebugScope(const DIScope *S)
950 -> EmitResult<PreparedScope> {
951 assert(CurrentMAI && "emitDebugScope requires CurrentMAI");
952 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
953 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
954 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
955 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
956
957 if (const auto *BT = dyn_cast<DIBasicType>(S))
958 return emitDebugTypeBasic(BT, I32TypeReg, MAI);
959 if (const auto *ST = dyn_cast<DISubroutineType>(S))
960 return emitDebugTypeFunctionForSubroutineType(ST, MAI);
961 if (const auto *CT = dyn_cast<DICompositeType>(S))
962 return emitDebugTypeForCompositeType(CT, VoidTypeReg, I32TypeReg,
963 ExtInstSetReg, MAI);
964 if (const auto *DT = dyn_cast<DIDerivedType>(S))
965 return emitDebugTypeForDerivedType(DT, VoidTypeReg, I32TypeReg,
966 ExtInstSetReg, MAI);
968 return emitDebugLexicalBlock(S, VoidTypeReg, I32TypeReg, ExtInstSetReg,
969 MAI);
970 if (const auto *LBF = dyn_cast<DILexicalBlockFile>(S))
971 return emitDebugLexicalBlockDiscriminator(LBF, VoidTypeReg, I32TypeReg,
972 ExtInstSetReg, MAI);
973 if (const auto *SP = dyn_cast<DISubprogram>(S)) {
974 if (SP->isDefinition())
975 return emitDebugFunction(SP, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
976 return emitDebugFunctionDeclaration(SP, VoidTypeReg, I32TypeReg,
977 ExtInstSetReg, MAI);
978 }
979 return EmitResult<PreparedScope>::unsupported();
980}
981
982auto SPIRVNonSemanticDebugHandler::emitDebugTypeForCompositeType(
983 const DICompositeType *CT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
984 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
985 -> EmitResult<PreparedScope> {
986 switch (CT->getTag()) {
987 case dwarf::DW_TAG_array_type:
988 // A vector is an array with DINode::FlagVector. A plain array is the
989 // same tag without it. A matrix is also lowered to a DW_TAG_array_type
990 // (two subranges), so it is indistinguishable from a 2D array here and
991 // is emitted as a DebugTypeArray.
992 //
993 // FIXME: Emitting a matrix as a DebugTypeArray is valid but loses the
994 // matrix shape. DWARF has no matrix tag, so distinguishing a matrix needs
995 // a new DINode flag analogous to FlagVector, set on the array, plus a way
996 // to carry column-major vs row-major traits. Array-of-vectors alone would
997 // not disambiguate a matrix from a genuine array of vectors. Once the
998 // frontend marks matrices, route them to a DebugTypeMatrix path here.
999 if (CT->isVector())
1000 return emitDebugTypeVector(CT, MAI);
1001 return emitDebugTypeArray(CT, MAI);
1002 case dwarf::DW_TAG_structure_type:
1003 case dwarf::DW_TAG_class_type:
1004 case dwarf::DW_TAG_union_type:
1005 return emitDebugTypeComposite(CT, VoidTypeReg, I32TypeReg, ExtInstSetReg,
1006 MAI);
1007 case dwarf::DW_TAG_enumeration_type:
1008 return emitDebugTypeEnum(CT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1009 default:
1010 return EmitResult<PreparedScope>::unsupported();
1011 }
1012}
1013
1014auto SPIRVNonSemanticDebugHandler::emitDebugTypeForDerivedType(
1015 const DIDerivedType *DT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1016 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1017 -> EmitResult<PreparedScope> {
1018 switch (DT->getTag()) {
1019 case dwarf::DW_TAG_pointer_type:
1020 return emitDebugTypePointer(DT, MAI);
1021 case dwarf::DW_TAG_typedef:
1022 return emitDebugTypedef(DT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1023 case dwarf::DW_TAG_member:
1024 return emitDebugTypeMember(DT, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1025 default:
1026 if (std::optional<uint32_t> Qualifier = mapTypeQualifierTag(DT->getTag()))
1027 return emitDebugTypeQualifier(DT, *Qualifier, MAI);
1028 return EmitResult<PreparedScope>::unsupported();
1029 }
1030}
1031
1032auto SPIRVNonSemanticDebugHandler::emitDebugTypePointer(
1034 -> EmitResult<PreparedScope> {
1035 // A DWARF address space is required to determine the SPIR-V storage class.
1036 // Skip pointer types that do not carry one.
1037 if (!PT->getDWARFAddressSpace().has_value())
1038 return EmitResult<PreparedScope>::unsupported();
1039
1040 EmitResult<MCRegister> Base = getOrCreateDebugTypeOrNone(PT->getBaseType());
1041 if (!Base)
1042 return EmitResult<PreparedScope>::failure(Base);
1043
1044 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1045 MCRegister DebugTypePointerFlagsReg =
1046 emitOpConstantI32(transDebugFlags(PT), I32TypeReg, MAI);
1047
1048 // For SPIR-V targets, Clang sets DwarfAddressSpace to the LLVM IR address
1049 // space, which addressSpaceToStorageClass expects.
1050 const auto &ST = static_cast<const SPIRVSubtarget &>(Asm->getSubtargetInfo());
1051 MCRegister StorageClassReg = emitOpConstantI32(
1052 addressSpaceToStorageClass(PT->getDWARFAddressSpace().value(), ST),
1053 I32TypeReg, MAI);
1054
1055 return EmitResult<PreparedScope>::emitted(
1056 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypePointer,
1057 {*Base.Value, StorageClassReg, DebugTypePointerFlagsReg}});
1058}
1059
1060auto SPIRVNonSemanticDebugHandler::emitDebugTypeQualifier(
1061 const DIDerivedType *QT, uint32_t Qualifier, SPIRV::ModuleAnalysisInfo &MAI)
1062 -> EmitResult<PreparedScope> {
1063 EmitResult<MCRegister> Base = getOrCreateDebugTypeOrNone(QT->getBaseType());
1064 if (!Base)
1065 return EmitResult<PreparedScope>::failure(Base);
1066
1067 MCRegister QualifierReg =
1068 emitOpConstantI32(Qualifier, getOrEmitOpTypeInt32Reg(MAI), MAI);
1069 return EmitResult<PreparedScope>::emitted(
1070 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeQualifier,
1071 {*Base.Value, QualifierReg}});
1072}
1073
1074auto SPIRVNonSemanticDebugHandler::emitDebugTypeFunctionForSubroutineType(
1076 -> EmitResult<PreparedScope> {
1077 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
1078 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1079 MCRegister DebugTypeFunctionFlagsReg =
1080 emitOpConstantI32(transDebugFlags(ST), I32TypeReg, MAI);
1081 DITypeArray TA = ST->getTypeArray();
1083 Ops.push_back(DebugTypeFunctionFlagsReg);
1084 // Empty DI type tuple: no explicit return or parameter slots (hand-written IR
1085 // may use !{}). Emit void-only prototype. Same as SPIRV-LLVM-Translator when
1086 // DISubroutineType::getTypeArray() has zero elements.
1087 if (TA.empty()) {
1088 Ops.push_back(VoidTypeReg);
1089 } else {
1090 for (unsigned I = 0, E = TA.size(); I != E; ++I) {
1091 bool IsReturnType = (I == 0);
1092 EmitResult<MCRegister> Slot =
1093 mapDISignatureTypeToReg(TA[I], VoidTypeReg, IsReturnType);
1094 // No emitted DebugType* id for this slot (e.g., pointer that
1095 // was skipped due missing address space, etc.).
1096 if (!Slot)
1097 return EmitResult<PreparedScope>::failure(Slot);
1098 Ops.push_back(*Slot.Value);
1099 }
1100 }
1101 return EmitResult<PreparedScope>::emitted(
1102 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeFunction, Ops});
1103}
1104
1105// Match SPIRV-LLVM-Translator's selection logic for the Parent operand.
1106auto SPIRVNonSemanticDebugHandler::resolveScope(const DIScope *Scope,
1107 const DICompileUnit *FallbackCU)
1108 -> EmitResult<MCRegister> {
1109 if (!CLOpts.debug_lexical_block_discriminator_scope)
1110 while (const auto *LBF = dyn_cast_or_null<DILexicalBlockFile>(Scope))
1111 Scope = LBF->getScope();
1112
1113 // These scopes have their own debug instruction.
1115 DILexicalBlockFile>(Scope))
1116 return getOrCreateDebugScope(Scope);
1117
1118 // For a file, compile-unit, or absent scope, fall back to a compile unit.
1119 auto CUResult = [](std::optional<MCRegister> Reg) {
1120 return Reg ? EmitResult<MCRegister>::emitted(*Reg)
1121 : EmitResult<MCRegister>::unsupported();
1122 };
1123 if (FallbackCU)
1124 return CUResult(lookupOptReg(DebugScopeRegs, FallbackCU));
1125
1126 if (CompileUnits.empty())
1127 return EmitResult<MCRegister>::unsupported();
1128
1129 return CUResult(lookupOptReg(DebugScopeRegs, CompileUnits[0].TheCU));
1130}
1131
1132auto SPIRVNonSemanticDebugHandler::emitDebugLexicalBlock(
1133 const DIScope *S, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1134 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1135 -> EmitResult<PreparedScope> {
1137 "S must be a DILexicalBlock or DINamespace in emitDebugLexicalBlock");
1138 EmitResult<MCRegister> Parent = resolveScope(S->getScope());
1139 if (!Parent)
1140 return EmitResult<PreparedScope>::failure(Parent);
1141
1142 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1143 S->getFile(), /*UseEmptyPathIfNullScope=*/true);
1144 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1145 ExtInstSetReg, MAI);
1146
1148 if (const auto *LB = dyn_cast<DILexicalBlock>(S)) {
1149 MCRegister LineReg = emitOpConstantI32(static_cast<uint32_t>(LB->getLine()),
1150 I32TypeReg, MAI);
1151 MCRegister ColReg = emitOpConstantI32(
1152 static_cast<uint32_t>(LB->getColumn()), I32TypeReg, MAI);
1153 Ops = {SrcReg, LineReg, ColReg, *Parent.Value};
1154 } else {
1155 const auto *NS = cast<DINamespace>(S);
1156 // DINamespace carries no line/column info.
1157 MCRegister LineReg = emitOpConstantI32(0, I32TypeReg, MAI);
1158 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1159 MCRegister NameReg = getCachedOpStringReg(NS->getName());
1160 Ops = {SrcReg, LineReg, ColReg, *Parent.Value, NameReg};
1161 }
1162
1163 return EmitResult<PreparedScope>::emitted(
1164 PreparedScope{SPIRV::NonSemanticExtInst::DebugLexicalBlock, Ops});
1165}
1166
1167auto SPIRVNonSemanticDebugHandler::emitDebugLexicalBlockDiscriminator(
1168 const DILexicalBlockFile *LBF, MCRegister VoidTypeReg,
1169 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1170 SPIRV::ModuleAnalysisInfo &MAI) -> EmitResult<PreparedScope> {
1171 assert(LBF && "LBF must not be null");
1172 EmitResult<MCRegister> Parent = resolveScope(LBF->getScope());
1173 if (!Parent)
1174 return EmitResult<PreparedScope>::failure(Parent);
1175
1176 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1177 LBF->getFile(), /*UseEmptyPathIfNullScope=*/true);
1178 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1179 ExtInstSetReg, MAI);
1180 MCRegister DiscReg = emitOpConstantI32(
1181 static_cast<uint32_t>(LBF->getDiscriminator()), I32TypeReg, MAI);
1182 return EmitResult<PreparedScope>::emitted(
1183 PreparedScope{SPIRV::NonSemanticExtInst::DebugLexicalBlockDiscriminator,
1184 {SrcReg, DiscReg, *Parent.Value}});
1185}
1186
1187MCRegister SPIRVNonSemanticDebugHandler::getOrEmitDebugInlinedAt(
1188 const DILocation *IA, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1189 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1190 assert(IA && "IA must not be null in getOrEmitDebugInlinedAt");
1191
1192 if (MCRegister Cached = DebugInlinedAtRegs.lookup(IA))
1193 return Cached;
1194
1195 EmitResult<MCRegister> Scope = resolveScope(IA->getScope());
1196 if (!Scope)
1197 return MCRegister();
1198
1199 MCRegister LineReg =
1200 emitOpConstantI32(static_cast<uint32_t>(IA->getLine()), I32TypeReg, MAI);
1201
1202 SmallVector<MCRegister, 3> Ops{LineReg, *Scope.Value};
1203 // Recurse before building this instruction's operands so an outer
1204 // inlined-at link is always available.
1205 if (const DILocation *Outer = IA->getInlinedAt()) {
1206 MCRegister OuterReg = getOrEmitDebugInlinedAt(
1207 Outer, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1208 if (!OuterReg.isValid())
1209 return MCRegister();
1210 Ops.push_back(OuterReg);
1211 }
1212
1213 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugInlinedAt,
1214 VoidTypeReg, ExtInstSetReg, Ops, MAI);
1215 DebugInlinedAtRegs[IA] = Reg;
1216 return Reg;
1217}
1218
1219auto SPIRVNonSemanticDebugHandler::emitDebugFunctionDeclaration(
1220 const DISubprogram *SP, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1221 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1222 -> EmitResult<PreparedScope> {
1223 assert(SP && "SP must not be null in emitDebugFunctionDeclaration");
1224 assert(!SP->isDefinition() &&
1225 "SP must not be a definition in emitDebugFunctionDeclaration");
1226
1227 // The IR verifier already enforces that this cannot be null.
1228 EmitResult<MCRegister> FnTy = getOrCreateDebugScope(SP->getType());
1229 if (!FnTy)
1230 return EmitResult<PreparedScope>::failure(FnTy);
1231
1232 EmitResult<MCRegister> Parent = resolveScope(SP->getScope(), SP->getUnit());
1233 if (!Parent)
1234 return EmitResult<PreparedScope>::failure(Parent);
1235
1236 MCRegister FileStrReg = getCachedScopePathOpStringReg(SP);
1237
1238 MCRegister NameReg = getCachedOpStringReg(SP->getName());
1239 MCRegister LinkageReg = getCachedOpStringReg(SP->getLinkageName());
1240 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1241 ExtInstSetReg, MAI);
1242
1243 MCRegister LineReg =
1244 emitOpConstantI32(static_cast<uint32_t>(SP->getLine()), I32TypeReg, MAI);
1245 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1246
1247 uint32_t FlagsVal = transDebugFlags(SP);
1248 // TODO: When composite scopes are DebugFunctionDeclaration parents (available
1249 // in DebugScopeRegs), sync declaration Flags with SPIRV-LLVM-Translator.
1250 FlagsVal &= ~NSDIFlagIsDefinition;
1251 MCRegister FlagsReg = emitOpConstantI32(FlagsVal, I32TypeReg, MAI);
1252
1253 return EmitResult<PreparedScope>::emitted(
1254 PreparedScope{SPIRV::NonSemanticExtInst::DebugFunctionDeclaration,
1255 {NameReg, *FnTy.Value, SrcReg, LineReg, ColReg,
1256 *Parent.Value, LinkageReg, FlagsReg}});
1257}
1258
1259auto SPIRVNonSemanticDebugHandler::emitDebugFunction(
1260 const DISubprogram *SP, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1261 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1262 -> EmitResult<PreparedScope> {
1263 assert(SP && "SP must not be null in emitDebugFunction");
1264 assert(SP->isDefinition() && "SP must be a definition in emitDebugFunction");
1265
1266 EmitResult<MCRegister> FnTy = getOrCreateDebugScope(SP->getType());
1267 if (!FnTy)
1268 return EmitResult<PreparedScope>::failure(FnTy);
1269
1270 EmitResult<MCRegister> Parent = resolveScope(SP->getScope(), SP->getUnit());
1271 if (!Parent)
1272 return EmitResult<PreparedScope>::failure(Parent);
1273
1274 MCRegister NameReg = getCachedOpStringReg(SP->getName());
1275 MCRegister LinkageReg = getCachedOpStringReg(SP->getLinkageName());
1276 MCRegister FileStrReg = getCachedScopePathOpStringReg(SP);
1277 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1278 ExtInstSetReg, MAI);
1279
1280 MCRegister LineReg =
1281 emitOpConstantI32(static_cast<uint32_t>(SP->getLine()), I32TypeReg, MAI);
1282 // LLVM's DISubprogram has no column field but SPIR-V expects one in
1283 // DebugFunction.
1284 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1285 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(SP), I32TypeReg, MAI);
1286 MCRegister ScopeLineReg = emitOpConstantI32(
1287 static_cast<uint32_t>(SP->getScopeLine()), I32TypeReg, MAI);
1288
1289 SmallVector<MCRegister, 10> Ops = {NameReg, *FnTy.Value, SrcReg,
1290 LineReg, ColReg, *Parent.Value,
1291 LinkageReg, FlagsReg, ScopeLineReg};
1292
1293 if (const DISubprogram *Decl = SP->getDeclaration()) {
1294 EmitResult<MCRegister> DeclRes = getOrCreateDebugScope(Decl);
1295 if (DeclRes)
1296 Ops.push_back(*DeclRes.Value);
1297 }
1298
1299 return EmitResult<PreparedScope>::emitted(
1300 PreparedScope{SPIRV::NonSemanticExtInst::DebugFunction, Ops});
1301}
1302
1303auto SPIRVNonSemanticDebugHandler::mapDISignatureTypeToReg(
1304 const DIType *Ty, MCRegister VoidTypeReg, bool ReturnType)
1305 -> EmitResult<MCRegister> {
1306 if (!Ty && ReturnType)
1307 return EmitResult<MCRegister>::emitted(VoidTypeReg);
1308 return getOrCreateDebugTypeOrNone(Ty);
1309}
1310
1311// NonSemantic.Shader.DebugInfo.100 debug operation encodings
1312// (section 4.5, "Debug Operations").
1325
1326static std::optional<NonSemanticDebugOp>
1328 switch (DwarfOp) {
1329 case dwarf::DW_OP_deref:
1331 case dwarf::DW_OP_plus:
1333 case dwarf::DW_OP_minus:
1335 case dwarf::DW_OP_plus_uconst:
1337 case dwarf::DW_OP_bit_piece:
1339 case dwarf::DW_OP_swap:
1341 case dwarf::DW_OP_xderef:
1343 case dwarf::DW_OP_stack_value:
1345 case dwarf::DW_OP_constu:
1349 default:
1350 return std::nullopt;
1351 }
1352}
1353
1354// The DebugOperation operand values for \p Op. Each becomes an OpConstant of
1355// OpTypeInt 32 0, so every argument must fit in 32 bits.
1356static std::optional<SmallVector<uint32_t, 3>>
1358 std::optional<NonSemanticDebugOp> NSOp =
1360 if (!NSOp)
1361 return std::nullopt;
1362
1363 SmallVector<uint32_t, 3> Operands{static_cast<uint32_t>(*NSOp)};
1364 for (unsigned I = 0, E = Op.getNumArgs(); I != E; ++I) {
1365 uint64_t Arg = Op.getArg(I);
1366 if (!isUInt<32>(Arg))
1367 return std::nullopt;
1368 Operands.push_back(static_cast<uint32_t>(Arg));
1369 }
1370 return Operands;
1371}
1372
1373std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugOperation(
1374 const DIExpression::ExprOperand &Op, MCRegister VoidTypeReg,
1375 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1377 std::optional<SmallVector<uint32_t, 3>> Key = mapExprOperand(Op);
1378 if (!Key)
1379 return std::nullopt;
1380
1381 auto [It, Inserted] = DebugOperationCache.try_emplace(std::move(*Key));
1382 if (!Inserted)
1383 return It->second;
1384
1386 for (uint32_t V : It->first)
1387 Operands.push_back(emitOpConstantI32(V, I32TypeReg, MAI));
1388 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugOperation,
1389 VoidTypeReg, ExtInstSetReg, Operands, MAI);
1390 It->second = Reg;
1391 return Reg;
1392}
1393
1394std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugExpression(
1395 const DIExpression *Expr, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1396 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1397 assert(Expr && "Expr must not be null in emitDebugExpression");
1398
1399 SmallVector<MCRegister> OperationRegs;
1400 for (const DIExpression::ExprOperand &Op : Expr->expr_ops()) {
1401 std::optional<MCRegister> OpReg =
1402 emitDebugOperation(Op, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
1403 if (!OpReg)
1404 return std::nullopt;
1405 OperationRegs.push_back(*OpReg);
1406 }
1407
1408 auto [It, Inserted] =
1409 DebugExpressionCache.try_emplace(std::move(OperationRegs));
1410 if (!Inserted)
1411 return It->second;
1412
1413 MCRegister Reg = emitExtInst(SPIRV::NonSemanticExtInst::DebugExpression,
1414 VoidTypeReg, ExtInstSetReg, It->first, MAI);
1415 It->second = Reg;
1416 return Reg;
1417}
1418
1419std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugGlobalVariable(
1420 const DIGlobalVariable *GV, const GlobalVariableDebugInfo &Info,
1421 MCRegister VoidTypeReg, MCRegister I32TypeReg, MCRegister ExtInstSetReg,
1423 assert(GV && "GV must not be null in emitDebugGlobalVariable");
1424
1425 EmitResult<MCRegister> Parent = resolveScope(GV->getScope());
1426 if (!Parent)
1427 return std::nullopt;
1428
1429 MCRegister ParentReg = *Parent.Value;
1430
1431 // TyReg: DebugInfoNone when GV has no DI type (as done in
1432 // SPIRV-LLVM-Translator). Declarations (isDefinition: false) can have null
1433 // getType() while definitions must have a non-null one (enforced by the IR
1434 // verifier).
1435 MCRegister TyReg = CachedDebugInfoNoneReg;
1436 if (const DIType *Ty = GV->getType()) {
1437 auto TyRegOpt = lookupOptReg(DebugScopeRegs, Ty);
1438 if (!TyRegOpt)
1439 return std::nullopt;
1440 TyReg = *TyRegOpt;
1441 }
1442
1443 std::optional<MCRegister> StaticMemberRegOpt;
1444 if (const DIDerivedType *SM = GV->getStaticDataMemberDeclaration()) {
1445 // Do not create the member here, just look it up to avoid orphaning it.
1446 StaticMemberRegOpt = lookupOptReg(DebugScopeRegs, SM);
1447 if (!StaticMemberRegOpt)
1448 return std::nullopt;
1449 }
1450
1451 MCRegister NameReg = getCachedOpStringReg(GV->getName());
1452 MCRegister LinkageReg = getCachedOpStringReg(GV->getLinkageName());
1453 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1454 GV->getFile(), /*UseEmptyPathIfNullScope=*/true);
1455 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1456 ExtInstSetReg, MAI);
1457
1458 MCRegister LineReg =
1459 emitOpConstantI32(static_cast<uint32_t>(GV->getLine()), I32TypeReg, MAI);
1460 // DIGlobalVariable or DIGlobalVariableExpression metadata carry no column
1461 // field. Column is hardcoded to 0 (because it can't be determined), matching
1462 // SPIRV-LLVM-Translator.
1463 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1464
1465 // Variable: @g OpVariable id when !dbg matches; else a DebugExpression for
1466 // the GVE init value when no @g exists and the expression is non-empty; else
1467 // DebugInfoNone. As per spec, the DebugExpression must contain the constant
1468 // value of the variable that was optimized out. An empty expression contains
1469 // no value, so we emit DebugInfoNone instead.
1470 MCRegister VariableReg = CachedDebugInfoNoneReg;
1471 if (const GlobalVariable *LLVMGV = Info.LLVMGV) {
1472 MCRegister GVReg = MAI.getGlobalObjReg(LLVMGV);
1473 if (GVReg.isValid())
1474 VariableReg = GVReg;
1475 } else if (Info.Expr && Info.Expr->getNumElements() != 0) {
1476 if (auto ExprReg = emitDebugExpression(Info.Expr, VoidTypeReg, I32TypeReg,
1477 ExtInstSetReg, MAI))
1478 VariableReg = *ExprReg;
1479 }
1480
1481 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(GV), I32TypeReg, MAI);
1482
1483 SmallVector<MCRegister, 10> Ops = {NameReg, TyReg, SrcReg,
1484 LineReg, ColReg, ParentReg,
1485 LinkageReg, VariableReg, FlagsReg};
1486
1487 if (StaticMemberRegOpt)
1488 Ops.push_back(*StaticMemberRegOpt);
1489
1490 return emitExtInst(SPIRV::NonSemanticExtInst::DebugGlobalVariable,
1491 VoidTypeReg, ExtInstSetReg, Ops, MAI);
1492}
1493
1494std::optional<MCRegister> SPIRVNonSemanticDebugHandler::emitDebugLocalVariable(
1495 const DILocalVariable *LV, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1496 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI) {
1497 assert(LV && "LV must not be null in emitDebugLocalVariable");
1498
1499 EmitResult<MCRegister> Parent = resolveScope(LV->getScope());
1500 if (!Parent)
1501 return std::nullopt;
1502
1503 MCRegister TyReg = CachedDebugInfoNoneReg;
1504 if (const DIType *Ty = LV->getType()) {
1505 auto TyRegOpt = lookupOptReg(DebugScopeRegs, Ty);
1506 if (!TyRegOpt)
1507 return std::nullopt;
1508 TyReg = *TyRegOpt;
1509 }
1510
1511 MCRegister NameReg = getCachedOpStringReg(LV->getName());
1512 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1513 LV->getFile(), /*UseEmptyPathIfNullScope=*/true);
1514 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1515 ExtInstSetReg, MAI);
1516 MCRegister LineReg =
1517 emitOpConstantI32(static_cast<uint32_t>(LV->getLine()), I32TypeReg, MAI);
1518 // DILocalVariable has no column field. Column is hardcoded to 0.
1519 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1520 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(LV), I32TypeReg, MAI);
1521
1522 SmallVector<MCRegister, 8> Ops = {NameReg, TyReg, SrcReg, LineReg,
1523 ColReg, *Parent.Value, FlagsReg};
1524 if (unsigned Arg = LV->getArg())
1525 Ops.push_back(emitOpConstantI32(Arg, I32TypeReg, MAI));
1526
1527 return emitExtInst(SPIRV::NonSemanticExtInst::DebugLocalVariable, VoidTypeReg,
1528 ExtInstSetReg, Ops, MAI);
1529}
1530
1531auto SPIRVNonSemanticDebugHandler::emitDebugTypeVector(
1533 -> EmitResult<PreparedScope> {
1534 const auto *BaseTy = dyn_cast_or_null<DIBasicType>(VT->getBaseType());
1535 if (!BaseTy)
1536 return EmitResult<PreparedScope>::unsupported();
1537
1538 // DebugTypeVector models only 1D vectors (multi-subrange types cannot be
1539 // encoded).
1540 DINodeArray Elements = VT->getElements();
1541 if (Elements.size() != 1)
1542 return EmitResult<PreparedScope>::unsupported();
1543 const auto *SR = cast<DISubrange>(Elements[0]);
1544 const auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount());
1545 if (!CI)
1546 return EmitResult<PreparedScope>::unsupported();
1547
1548 EmitResult<MCRegister> Base = getOrCreateDebugScope(BaseTy);
1549 if (!Base)
1550 return EmitResult<PreparedScope>::failure(Base);
1551
1552 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1553 MCRegister CountReg = emitOpConstantI32(
1554 static_cast<uint32_t>(CI->getZExtValue()), I32TypeReg, MAI);
1555 return EmitResult<PreparedScope>::emitted(PreparedScope{
1556 SPIRV::NonSemanticExtInst::DebugTypeVector, {*Base.Value, CountReg}});
1557}
1558
1559auto SPIRVNonSemanticDebugHandler::emitDebugTypeArray(
1561 -> EmitResult<PreparedScope> {
1562 // Unlike DebugTypeVector, the element may be any debug type, not only a
1563 // basic type. Create it first so this array names an id that already exists.
1564 EmitResult<MCRegister> Base = getOrCreateDebugScope(AT->getBaseType());
1565 if (!Base)
1566 return EmitResult<PreparedScope>::failure(Base);
1567
1568 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
1569
1571 Ops.push_back(*Base.Value);
1572
1573 // One component count per DISubrange, in DWARF subrange order. Emit 0 for
1574 // counts that are not a compile-time constant (dynamic arrays). This matches
1575 // OpTypeRuntimeArray.
1576 for (const DINode *Element : AT->getElements()) {
1577 const auto *SR = dyn_cast<DISubrange>(Element);
1578 if (!SR)
1579 continue;
1580 // A DIVariable count (a variable-length array) is not a ConstantInt, so it
1581 // maps to 0 here. DebugTypeArray also allows a DebugLocalVariable or
1582 // DebugGlobalVariable id for it, but no frontend we target emits one. A
1583 // constant wider than 32 bits maps to 0 too, since the count operand is a
1584 // 32-bit OpConstant and such an array cannot occur in a shader.
1585 uint32_t Count = 0;
1586 if (const auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount())) {
1587 const APInt &Value = CI->getValue();
1588 if (Value.getActiveBits() <= 32)
1589 Count = static_cast<uint32_t>(Value.getZExtValue());
1590 }
1591 Ops.push_back(emitOpConstantI32(Count, I32TypeReg, MAI));
1592 }
1593
1594 return EmitResult<PreparedScope>::emitted(
1595 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeArray, Ops});
1596}
1597
1598auto SPIRVNonSemanticDebugHandler::emitDebugTypeMember(
1599 const DIDerivedType *M, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1600 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1601 -> EmitResult<PreparedScope> {
1602 EmitResult<MCRegister> Ty = getOrCreateDebugScope(M->getBaseType());
1603 if (!Ty)
1604 return EmitResult<PreparedScope>::failure(Ty);
1605
1606 if (!isUInt<32>(M->getOffsetInBits()) || !isUInt<32>(M->getSizeInBits()))
1607 return EmitResult<PreparedScope>::unsupported();
1608
1609 MCRegister NameReg = getCachedOpStringReg(M->getName());
1610 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1611 M->getFile(), /*UseEmptyPathIfNullScope=*/true);
1612 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1613 ExtInstSetReg, MAI);
1614 MCRegister LineReg =
1615 emitOpConstantI32(static_cast<uint32_t>(M->getLine()), I32TypeReg, MAI);
1616
1617 // DIDerivedType members carry no column, so emit 0.
1618 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1619 MCRegister OffsetReg = emitOpConstantI32(
1620 static_cast<uint32_t>(M->getOffsetInBits()), I32TypeReg, MAI);
1621 MCRegister SizeReg = emitOpConstantI32(
1622 static_cast<uint32_t>(M->getSizeInBits()), I32TypeReg, MAI);
1623 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(M), I32TypeReg, MAI);
1624
1625 // In NonSemantic.Shader.DebugInfo a DebugTypeMember has no Parent operand:
1626 // only the composite references its members. This is by design, it drops the
1627 // Parent that OpenCL.DebugInfo.100 had, and it avoids a composite/member
1628 // reference cycle.
1629 //
1630 // FIXME: Static members are not handled yet: their constant initializer is
1631 // available but is not emitted as the optional Value operand, and under DWARF
1632 // 5 a static member is tagged DW_TAG_variable, which the caller's member loop
1633 // skips.
1634 return EmitResult<PreparedScope>::emitted(
1635 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeMember,
1636 {NameReg, *Ty.Value, SrcReg, LineReg, ColReg, OffsetReg,
1637 SizeReg, FlagsReg}});
1638}
1639
1640auto SPIRVNonSemanticDebugHandler::emitDebugTypeComposite(
1641 const DICompositeType *CT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1642 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1643 -> EmitResult<PreparedScope> {
1644 // Parent and size before any member: a failure must stream nothing, or a
1645 // retry would emit the members again.
1646 EmitResult<MCRegister> Parent = resolveScope(CT->getScope());
1647 if (!Parent)
1648 return EmitResult<PreparedScope>::failure(Parent);
1649
1650 if (!isUInt<32>(CT->getSizeInBits()))
1651 return EmitResult<PreparedScope>::unsupported();
1652
1653 SmallVector<MCRegister, 8> MemberRegs;
1654 for (const DINode *Element : CT->getElements()) {
1655 const auto *M = dyn_cast<DIDerivedType>(Element);
1656 if (!M || M->getTag() != dwarf::DW_TAG_member)
1657 continue;
1658 EmitResult<MCRegister> Member = getOrCreateDebugScope(M);
1659 if (Member)
1660 MemberRegs.push_back(*Member.Value);
1661 }
1662
1663 MCRegister NameReg = getCachedOpStringReg(CT->getName());
1664 MCRegister LinkageReg = getCachedOpStringReg(CT->getIdentifier());
1665 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1666 CT->getFile(), /*UseEmptyPathIfNullScope=*/true);
1667 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1668 ExtInstSetReg, MAI);
1669
1670 MCRegister TagReg =
1671 emitOpConstantI32(mapCompositeTypeTag(CT->getTag()), I32TypeReg, MAI);
1672 MCRegister LineReg =
1673 emitOpConstantI32(static_cast<uint32_t>(CT->getLine()), I32TypeReg, MAI);
1674 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1675
1676 // A forward declaration has no known size or members: Size is DebugInfoNone.
1677 MCRegister SizeReg = CachedDebugInfoNoneReg;
1678 if (!CT->isForwardDecl())
1679 SizeReg = emitOpConstantI32(static_cast<uint32_t>(CT->getSizeInBits()),
1680 I32TypeReg, MAI);
1681
1682 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(CT), I32TypeReg, MAI);
1683
1684 SmallVector<MCRegister> Ops = {NameReg, TagReg, SrcReg,
1685 LineReg, ColReg, *Parent.Value,
1686 LinkageReg, SizeReg, FlagsReg};
1687 Ops.append(MemberRegs.begin(), MemberRegs.end());
1688 return EmitResult<PreparedScope>::emitted(
1689 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeComposite, Ops});
1690}
1691
1692auto SPIRVNonSemanticDebugHandler::emitDebugTypeEnum(
1693 const DICompositeType *ET, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1694 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1695 -> EmitResult<PreparedScope> {
1696 // Skip incomplete enums.
1697 uint64_t Size = ET->getSizeInBits();
1698 if (Size == 0 || !isUInt<32>(Size))
1699 return EmitResult<PreparedScope>::unsupported();
1700
1701 EmitResult<MCRegister> Underlying =
1702 getOrCreateDebugTypeOrNone(ET->getBaseType());
1703 if (!Underlying)
1704 return EmitResult<PreparedScope>::failure(Underlying);
1705
1706 EmitResult<MCRegister> Parent =
1707 resolveScope(ET->getScope(), EnumCompileUnits.lookup(ET));
1708 if (!Parent)
1709 return EmitResult<PreparedScope>::failure(Parent);
1710
1711 MCRegister NameReg = getCachedOpStringReg(ET->getName());
1712 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1713 ET->getFile(), /*UseEmptyPathIfNullScope=*/true);
1714 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1715 ExtInstSetReg, MAI);
1716 MCRegister LineReg =
1717 emitOpConstantI32(static_cast<uint32_t>(ET->getLine()), I32TypeReg, MAI);
1718 // DICompositeType carries no column, so emit 0.
1719 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1720 MCRegister SizeReg =
1721 emitOpConstantI32(static_cast<uint32_t>(Size), I32TypeReg, MAI);
1722 MCRegister FlagsReg = emitOpConstantI32(transDebugFlags(ET), I32TypeReg, MAI);
1723
1724 SmallVector<MCRegister> Ops = {NameReg, *Underlying.Value, SrcReg, LineReg,
1725 ColReg, *Parent.Value, SizeReg, FlagsReg};
1726
1727 // Each Value is a 32-bit integer constant. Skip the Value and Name pair of an
1728 // enumerator whose value needs more bits. Otherwise, the truncation would
1729 // show a different value.
1730 for (const DINode *Element : ET->getElements()) {
1731 const auto *E = dyn_cast<DIEnumerator>(Element);
1732 if (!E)
1733 continue;
1734 const APInt &Value = E->getValue();
1735 if (E->isUnsigned() ? !Value.isIntN(32) : !Value.isSignedIntN(32))
1736 continue;
1737 uint32_t Bits = E->isUnsigned()
1738 ? static_cast<uint32_t>(Value.getZExtValue())
1739 : static_cast<uint32_t>(Value.getSExtValue());
1740 Ops.push_back(emitOpConstantI32(Bits, I32TypeReg, MAI));
1741 Ops.push_back(getCachedOpStringReg(E->getName()));
1742 }
1743
1744 return EmitResult<PreparedScope>::emitted(
1745 PreparedScope{SPIRV::NonSemanticExtInst::DebugTypeEnum, Ops});
1746}
1747
1748auto SPIRVNonSemanticDebugHandler::emitDebugTypedef(
1749 const DIDerivedType *TD, MCRegister VoidTypeReg, MCRegister I32TypeReg,
1750 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI)
1751 -> EmitResult<PreparedScope> {
1752 EmitResult<MCRegister> Base = getOrCreateDebugScope(TD->getBaseType());
1753 if (!Base)
1754 return EmitResult<PreparedScope>::failure(Base);
1755
1756 MCRegister NameReg = getCachedOpStringReg(TD->getName());
1757 MCRegister FileStrReg = getCachedScopePathOpStringReg(
1758 TD->getFile(), /*UseEmptyPathIfNullScope=*/true);
1759 MCRegister SrcReg = getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg,
1760 ExtInstSetReg, MAI);
1761 MCRegister LineReg =
1762 emitOpConstantI32(static_cast<uint32_t>(TD->getLine()), I32TypeReg, MAI);
1763 // DIDerivedType typedefs carry no column, so emit 0.
1764 MCRegister ColReg = emitOpConstantI32(0, I32TypeReg, MAI);
1765
1766 // Parent must be a lexical scope. Valid NSDI lexical scopes are
1767 // DebugCompilationUnit, DebugFunction, DebugLexicalBlock, or
1768 // DebugTypeComposite.
1769 EmitResult<MCRegister> Parent = resolveScope(TD->getScope());
1770 if (!Parent)
1771 return EmitResult<PreparedScope>::failure(Parent);
1772
1773 return EmitResult<PreparedScope>::emitted(PreparedScope{
1774 SPIRV::NonSemanticExtInst::DebugTypedef,
1775 {NameReg, *Base.Value, SrcReg, LineReg, ColReg, *Parent.Value}});
1776}
1777
1780 if (CompileUnits.empty())
1781 return;
1782 // Check that prepareModuleOutput() registered the extended instruction set.
1783 // If the subtarget does not support the extension, neither strings nor ext
1784 // insts are emitted.
1785 if (!MAI.getExtInstSetReg(NSSet).isValid())
1786 return;
1787
1788 for (const CompileUnitInfo &Info : CompileUnits) {
1789 if (Info.TheCU) {
1790 MCRegister PathReg = emitOpStringIfNew(Info.FilePath, MAI);
1791 ScopeToPathOpStringReg[Info.TheCU] = PathReg;
1792 if (const DIFile *F = Info.TheCU->getFile())
1793 ScopeToPathOpStringReg[F] = PathReg;
1794 }
1795 }
1796
1797 for (const DISubprogram *SP : Subprograms) {
1798 emitOpStringIfNew(SP->getName(), MAI);
1799 emitOpStringIfNew(SP->getLinkageName(), MAI);
1800 emitAndCacheScopePathOpStringReg(SP, MAI);
1801 }
1802
1803 for (const DIType *Ty : DebugTypes) {
1804 if (const auto *BT = dyn_cast<DIBasicType>(Ty)) {
1805 emitOpStringIfNew(BT->getName(), MAI);
1806 continue;
1807 }
1808 if (const auto *CT = dyn_cast<DICompositeType>(Ty)) {
1809 // Cache the enum's name, file path and enumerator names as OpStrings for
1810 // DebugTypeEnum.
1811 if (CT->getTag() == dwarf::DW_TAG_enumeration_type) {
1812 emitOpStringIfNew(CT->getName(), MAI);
1813 emitAndCacheScopePathOpStringReg(CT->getFile(), MAI);
1814 for (const DINode *Element : CT->getElements())
1815 if (const auto *E = dyn_cast<DIEnumerator>(Element))
1816 emitOpStringIfNew(E->getName(), MAI);
1817 continue;
1818 }
1819 // Cache the OpStrings each DebugTypeComposite and its DebugTypeMembers
1820 // use: the composite name, identifier (linkage name), and path, plus
1821 // each member name and path. Arrays and vectors have no such strings.
1822 if (CT->getTag() != dwarf::DW_TAG_structure_type &&
1823 CT->getTag() != dwarf::DW_TAG_class_type &&
1824 CT->getTag() != dwarf::DW_TAG_union_type)
1825 continue;
1826 emitOpStringIfNew(CT->getName(), MAI);
1827 emitOpStringIfNew(CT->getIdentifier(), MAI);
1828 emitAndCacheScopePathOpStringReg(CT->getFile(), MAI);
1829 for (const DINode *Element : CT->getElements()) {
1830 const auto *M = dyn_cast<DIDerivedType>(Element);
1831 if (!M || M->getTag() != dwarf::DW_TAG_member)
1832 continue;
1833 emitOpStringIfNew(M->getName(), MAI);
1834 emitAndCacheScopePathOpStringReg(M->getFile(), MAI);
1835 }
1836 continue;
1837 }
1838 // Cache the name and path OpStrings each DebugTypedef uses.
1839 const auto *TD = dyn_cast<DIDerivedType>(Ty);
1840 if (TD && TD->getTag() == dwarf::DW_TAG_typedef) {
1841 emitOpStringIfNew(TD->getName(), MAI);
1842 emitAndCacheScopePathOpStringReg(TD->getFile(), MAI);
1843 }
1844 }
1845
1846 for (const auto &[GV, _] : GlobalVariableDebugInfoMap) {
1847 emitOpStringIfNew(GV->getName(), MAI);
1848 emitOpStringIfNew(GV->getLinkageName(), MAI);
1849 emitAndCacheScopePathOpStringReg(GV->getFile(), MAI);
1850 }
1851
1852 for (const DILocalVariable *LV : LocalVariables) {
1853 emitOpStringIfNew(LV->getName(), MAI);
1854 emitAndCacheScopePathOpStringReg(LV->getFile(), MAI);
1855 }
1856
1857 for (const DIScope *S : LexicalBlocks) {
1858 emitAndCacheScopePathOpStringReg(S->getFile(), MAI);
1859 if (const auto *NS = dyn_cast<DINamespace>(S))
1860 emitOpStringIfNew(NS->getName(), MAI);
1861 }
1862
1863 for (const DILocation *DL : UniqueDebugLocations)
1864 emitAndCacheScopePathOpStringReg(DL->getScope(), MAI);
1865
1866 CachedEmptyStringReg = emitOpStringIfNew("", MAI);
1867
1868#ifndef NDEBUG
1869 NonSemanticOpStringsSectionEmitted = true;
1870#endif
1871}
1872
1873void SPIRVNonSemanticDebugHandler::emitDebugFunctionDefinition(
1874 MCRegister DebugFunctionReg, MCRegister OpFunctionReg,
1876 assert(DebugFunctionReg.isValid() && OpFunctionReg.isValid() &&
1877 "DebugFunctionDefinition operands must be valid");
1878 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
1879 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
1880 emitExtInst(SPIRV::NonSemanticExtInst::DebugFunctionDefinition, VoidTypeReg,
1881 ExtInstSetReg, {DebugFunctionReg, OpFunctionReg}, MAI);
1882}
1883
1884void SPIRVNonSemanticDebugHandler::resetPerFunctionDebugState() {
1885 CurrentMF = nullptr;
1886 LastFunctionOpVariable = nullptr;
1887 DebugFunctionDefinitionEmitted = false;
1888 LastLineMI = nullptr;
1889 LastScopeMI = nullptr;
1890 Records.clear();
1891}
1892
1893void SPIRVNonSemanticDebugHandler::preparePerFunctionDebug(
1894 const MachineFunction *MF) {
1895 resetPerFunctionDebugState();
1896 if (!GlobalNSDIEnabled || !CurrentMAI)
1897 return;
1898
1899 CurrentMF = MF;
1900
1901 if (MF->getFunction()
1903 .isValid())
1904 return;
1905
1906 const DISubprogram *SP = MF->getFunction().getSubprogram();
1907 if (!SP || !SP->isDefinition())
1908 return;
1909
1910 // DebugFunctionDefinition is emitted after the last function-level
1911 // OpVariable. If there are none, it is emitted after the entry OpLabel.
1912 LastFunctionOpVariable =
1913 findLastFunctionOpVariableDeclaration(*MF, *CurrentMAI);
1914
1915 analyzeDebugRecords(*MF);
1916}
1917
1918void SPIRVNonSemanticDebugHandler::tryEmitDebugFunctionDefinition(
1920 if (DebugFunctionDefinitionEmitted || !GlobalNSDIEnabled)
1921 return;
1922
1923 assert(CurrentMF && "no current MachineFunction");
1924 const Function &F = CurrentMF->getFunction();
1925 const DISubprogram *SP = F.getSubprogram();
1926 if (!SP || !SP->isDefinition())
1927 return;
1928
1929 auto DFIt = DebugScopeRegs.find(SP);
1930 if (DFIt == DebugScopeRegs.end())
1931 return;
1932
1933 MCRegister OpFunctionReg = MAI.getGlobalObjReg(&F);
1934 if (!OpFunctionReg.isValid())
1935 return;
1936
1937 emitDebugFunctionDefinition(DFIt->second, OpFunctionReg, MAI);
1938 DebugFunctionDefinitionEmitted = true;
1939}
1940
1942 const MachineFunction *MF) {
1943 preparePerFunctionDebug(MF);
1944}
1945
1947 (void)MF;
1948 resetPerFunctionDebugState();
1949}
1950
1952 assert(CurMI == nullptr && "CurMI must be null");
1953 CurMI = MI;
1954
1955 if (!DebugFunctionDefinitionEmitted)
1956 return;
1957
1958 emitAnalyzedRecords(MI);
1959
1960 std::optional<const MachineInstr *> Target = resolveDebugLocTarget(MI);
1961 if (!Target)
1962 return;
1963
1964 (void)emitDebugScopeForInstruction(*Target);
1965 emitDebugLineForInstruction(*Target);
1966}
1967
1968// The register that holds the variable's address in \p MI, or std::nullopt
1969// when \p MI is not a declare this backend can describe.
1970//
1971// The spec requires DebugDeclare's Variable operand to be "the <id> of an
1972// OpVariable instruction that defines the local variable". MIR has no
1973// DBG_DECLARE, so what this looks for is an indirect DBG_VALUE whose location
1974// register an OpVariable defines.
1975static std::optional<Register>
1977 // #dbg_declare is an indirect DBG_VALUE in MIR; #dbg_value is normally a
1978 // direct one except for the variadic case.
1979 if (!MI.isIndirectDebugValue())
1980 return std::nullopt;
1981
1982 // A variadic #dbg_value becomes DBG_VALUE $noreg, 0, ... which is indirect
1983 // too, and $noreg is not virtual.
1984 Register LocReg = MI.getDebugOperand(0).getReg();
1985 if (!LocReg.isVirtual())
1986 return std::nullopt;
1987
1988 // DebugDeclare can only encode the address of an OpVariable.
1989 // Other legitimate #dbg_declare cannot be encoded.
1990 // Examples: an access chain for a field, an OpFunctionParameter for a byval
1991 // argument, or a module-scope constant for a null or fixed address.
1992
1993 // LocReg may also have no def at all: erasing dead storage leaves the
1994 // DBG_VALUE pointing at an undefined register. MachineVerifier permits that
1995 // because LiveDebugVariables normally clears it, but this pipeline has no
1996 // register allocation, so LiveDebugVariables never runs.
1997 const MachineInstr *Def = MI.getMF()->getRegInfo().getUniqueVRegDef(LocReg);
1998 if (!Def || Def->getOpcode() != SPIRV::OpVariable)
1999 return std::nullopt;
2000
2001 return LocReg;
2002}
2003
2004void SPIRVNonSemanticDebugHandler::emitDebugBinding(
2005 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
2006 const MachineInstr *MI, MCRegister LocationReg) {
2007 assert(DebugFunctionDefinitionEmitted &&
2008 "DebugFunctionDefinition must be emitted");
2009 assert(CurrentMAI && "CurrentMAI must be set");
2010
2011 auto VarRegOpt = lookupOptReg(DebugLocalVariableRegs, MI->getDebugVariable());
2012 if (!VarRegOpt)
2013 return;
2014
2015 auto ExprRegOpt = lookupOptReg(DebugExpressionRegs, MI->getDebugExpression());
2016 if (!ExprRegOpt)
2017 return;
2018
2019 if (!emitDebugScopeForInstruction(MI))
2020 return;
2021 emitDebugLineForInstruction(MI);
2022
2023 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2024 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2025 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2026 emitExtInst(Opcode, VoidTypeReg, ExtInstSetReg,
2027 {*VarRegOpt, LocationReg, *ExprRegOpt}, MAI);
2028}
2029
2030// The scalar type and value of the constant \p MI assigns, or nullopt when
2031// this backend cannot name it.
2032static std::optional<std::pair<const DIBasicType *, uint64_t>>
2034 if (!MI.isNonListDebugValue() || MI.isIndirectDebugValue())
2035 return std::nullopt;
2036
2037 const MachineOperand &Value = MI.getDebugOperand(0);
2038 if (!Value.isImm() && !Value.isCImm() && !Value.isFPImm())
2039 return std::nullopt;
2040
2041 const DILocalVariable *LV = MI.getDebugVariable();
2042 const DIBasicType *BT = LV ? stripToScalarType(LV->getType()) : nullptr;
2043 if (!BT)
2044 return std::nullopt;
2045
2046 uint64_t Bits;
2047 if (Value.isImm())
2048 Bits = constantBits(static_cast<uint64_t>(Value.getImm()), BT);
2049 else if (Value.isCImm())
2050 Bits = constantBits(Value.getCImm()->getValue(), BT);
2051 else
2052 Bits = constantBits(Value.getFPImm()->getValueAPF().bitcastToAPInt(), BT);
2053 return std::make_pair(BT, Bits);
2054}
2055
2056std::optional<MCRegister> SPIRVNonSemanticDebugHandler::getConstantValueReg(
2057 const MachineInstr &MI) const {
2058 std::optional<std::pair<const DIBasicType *, uint64_t>> Const =
2060 if (!Const)
2061 return std::nullopt;
2062
2063 auto It = ConstantValueRegs.find(*Const);
2064 if (It == ConstantValueRegs.end() || !It->second.isValid())
2065 return std::nullopt;
2066 return It->second;
2067}
2068
2069static std::optional<Register> getDebugValueReg(const MachineInstr &MI) {
2070 if (!MI.isNonListDebugValue() || MI.isIndirectDebugValue())
2071 return std::nullopt;
2072
2073 const MachineOperand &Value = MI.getDebugOperand(0);
2074 if (!Value.isReg())
2075 return std::nullopt;
2076
2077 Register ValueReg = Value.getReg();
2078 if (!ValueReg.isVirtual())
2079 return std::nullopt;
2080
2081 const MachineInstr *Def = MI.getMF()->getRegInfo().getUniqueVRegDef(ValueReg);
2082 if (!Def || (Def->isPseudo() && !Def->isPHI()) || Def->isMetaInstruction() ||
2083 Def->getNumOperands() == 0 || !Def->getOperand(0).isReg() ||
2084 !Def->getOperand(0).isDef() || Def->getOperand(0).getReg() != ValueReg)
2085 return std::nullopt;
2086
2087 return ValueReg;
2088}
2089
2090static bool isMergeInstruction(unsigned Opcode) {
2091 return Opcode == SPIRV::OpSelectionMerge || Opcode == SPIRV::OpLoopMerge ||
2092 Opcode == SPIRV::OpLoopControlINTEL;
2093}
2094
2095// Whether \p MI becomes a SPIR-V instruction in the output.
2097 return !MI->isMetaInstruction() && !MAI.getSkipEmission(MI);
2098}
2099
2102 if (!isEmitted(MI, MAI))
2103 return false;
2104 switch (MI->getOpcode()) {
2105 case SPIRV::OpFunction:
2106 case SPIRV::OpFunctionParameter:
2107 case SPIRV::OpFunctionEnd:
2108 case SPIRV::OpLabel:
2109 case TargetOpcode::PHI:
2110 return false;
2111 default:
2112 return true;
2113 }
2114}
2115
2116static const MachineInstr *
2118 SPIRV::ModuleAnalysisInfo &MAI, bool Forward) {
2119 for (const MachineInstr *Adj = Forward ? MI->getNextNode()
2120 : MI->getPrevNode();
2121 Adj; Adj = Forward ? Adj->getNextNode() : Adj->getPrevNode()) {
2122 if (!isEmitted(Adj, MAI))
2123 continue;
2124 return Adj;
2125 }
2126 return nullptr;
2127}
2128
2129std::optional<const MachineInstr *>
2130SPIRVNonSemanticDebugHandler::resolveDebugLocTarget(const MachineInstr *MI) {
2131 assert(CurrentMAI && "CurrentMAI must be set");
2132 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2133
2134 // Structural opcodes don't require a DebugLine/DebugScope, other opcodes
2135 // might have already been emitted in the module scope.
2136 if (!isDebugLocTarget(MI, MAI))
2137 return std::nullopt;
2138
2139 // DebugLine/DebugScope can be emitted before a merge instruction, but not
2140 // after it (nothing may sit between the merge and its terminator). We can
2141 // use either the merge's or the terminator's debug info; we emit the
2142 // terminator's one.
2143 const MachineInstr *Prev = findAdjacentEmittedInstruction(MI, MAI, false);
2144 if (Prev && isMergeInstruction(Prev->getOpcode()))
2145 return std::nullopt;
2146
2147 if (isMergeInstruction(MI->getOpcode())) {
2148 // Use the terminator's debug info; when we reach it later, the check
2149 // above skips it.
2150 MI = findAdjacentEmittedInstruction(MI, MAI, true);
2151 assert(MI && "Merge instruction must be followed by a terminator");
2152 // The assert is compiled out in a release build, and returning MI there
2153 // would give an engaged optional holding null.
2154 if (!MI)
2155 return std::nullopt;
2156 }
2157
2158 return MI;
2159}
2160
2161void SPIRVNonSemanticDebugHandler::resolveDebugRecord(
2162 const MachineInstr &MI, const MachineInstr *LastEmitted,
2163 const MachineDominatorTree &DomTree) {
2164 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2165 const MachineFunction &MF = *MI.getMF();
2166
2167 // A record sits at its own position, except in a merge region: nothing may
2168 // be emitted between a merge and its terminator, so it belongs ahead of the
2169 // merge.
2170 const MachineInstr *Anchor =
2171 LastEmitted && isMergeInstruction(LastEmitted->getOpcode()) ? LastEmitted
2172 : &MI;
2173
2174 // A #dbg_declare reaches Machine IR as an indirect DBG_VALUE. Its storage is
2175 // an OpVariable in the entry block, so it is in the output by the time any
2176 // record naming it is reached.
2177 if (std::optional<Register> LocReg = getDebugDeclareStorageReg(MI)) {
2178 MCRegister StorageReg = MAI.getRegisterAlias(&MF, *LocReg);
2179 if (StorageReg.isValid())
2180 placeRecord(SPIRV::NonSemanticExtInst::DebugDeclare, MI, StorageReg,
2181 Anchor);
2182 return;
2183 }
2184
2185 if (std::optional<MCRegister> ConstReg = getConstantValueReg(MI)) {
2186 placeRecord(SPIRV::NonSemanticExtInst::DebugValue, MI, *ConstReg, Anchor);
2187 return;
2188 }
2189
2190 std::optional<Register> ValReg = getDebugValueReg(MI);
2191 if (!ValReg)
2192 return;
2193 MCRegister ValueReg = MAI.getRegisterAlias(&MF, *ValReg);
2194 if (!ValueReg.isValid())
2195 return;
2196
2197 // NonSemantic.Shader.DebugInfo states that "Forward references are not
2198 // allowed, to be compliant with SPV_KHR_non_semantic_info", so the id has to
2199 // be in the output already. A module section precedes every function body.
2200 //
2201 // For anything else, SPIR-V requires a definition in a function block to
2202 // dominate a non-phi use, and requires a block to precede every block it
2203 // dominates, so a dominating definition is also one already printed. A
2204 // record naming a definition that does not dominate it is dropped.
2205 const MachineInstr *Def = MF.getRegInfo().getUniqueVRegDef(*ValReg);
2206 if (ModuleScopeIds.contains(ValueReg) ||
2207 (isEmitted(Def, MAI) && DomTree.dominates(Def, &MI)))
2208 placeRecord(SPIRV::NonSemanticExtInst::DebugValue, MI, ValueReg, Anchor);
2209}
2210
2211void SPIRVNonSemanticDebugHandler::analyzeDebugRecords(
2212 const MachineFunction &MF) {
2213 assert(CurrentMAI && "CurrentMAI must be set");
2214
2215 // Built on the first record rather than required as an analysis pass, which
2216 // would build a tree for every SPIR-V compilation.
2217 std::optional<MachineDominatorTree> DomTree;
2218
2219 for (const MachineBasicBlock &MBB : MF) {
2220 const MachineInstr *LastEmitted = nullptr;
2221 for (const MachineInstr &MI : MBB) {
2222 if (MI.isDebugValueLike()) {
2223 if (!DomTree)
2224 DomTree.emplace(const_cast<MachineFunction &>(MF));
2225 resolveDebugRecord(MI, LastEmitted, *DomTree);
2226 }
2227
2228 if (isEmitted(&MI, *CurrentMAI))
2229 LastEmitted = &MI;
2230 }
2231 }
2232}
2233
2234void SPIRVNonSemanticDebugHandler::placeRecord(
2235 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
2236 const MachineInstr &MI, MCRegister LocationReg,
2237 const MachineInstr *Anchor) {
2238 Records[Anchor].push_back({&MI, Opcode, LocationReg});
2239}
2240
2241void SPIRVNonSemanticDebugHandler::emitAnalyzedRecords(
2242 const MachineInstr *Anchor) {
2243 auto It = Records.find(Anchor);
2244 if (It == Records.end())
2245 return;
2246 for (const DebugRecord &R : It->second)
2247 emitDebugBinding(R.Opcode, R.MI, R.LocationReg);
2248}
2249
2250bool SPIRVNonSemanticDebugHandler::emitDebugScopeForInstruction(
2251 const MachineInstr *MI) {
2252 assert(DebugFunctionDefinitionEmitted &&
2253 "DebugFunctionDefinition must be emitted");
2254 assert(CurrentMAI && "CurrentMAI must be set");
2255
2256 // The region is implicitly closed at each basic block boundary, so a
2257 // LastScopeMI from another block must be dropped before it is read below:
2258 // the new block needs its own DebugScope, and has no region left to close.
2259 if (LastScopeMI && MI->getParent() != LastScopeMI->getParent())
2260 LastScopeMI = nullptr;
2261
2262 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2263 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2264 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2265
2266 const DILocation *CurDL = MI->getDebugLoc().get();
2267 if (!CurDL) {
2268 // No location for the current instruction.
2269 if (LastScopeMI) {
2270 // Close the current DebugScope region.
2271 emitExtInst(SPIRV::NonSemanticExtInst::DebugNoScope, VoidTypeReg,
2272 ExtInstSetReg, {}, MAI);
2273 LastScopeMI = nullptr;
2274 }
2275 return true;
2276 }
2277
2278 const DIScope *CurScope = CurDL->getScope();
2279 const DILocation *CurInlinedAt = CurDL->getInlinedAt();
2280
2281 if (LastScopeMI) {
2282 const DILocation *LastDL = LastScopeMI->getDebugLoc().get();
2283 if (LastDL->getScope() == CurScope &&
2284 LastDL->getInlinedAt() == CurInlinedAt)
2285 return true;
2286 }
2287
2288 EmitResult<MCRegister> CurScopeRes = resolveScope(CurScope);
2289 if (!CurScopeRes)
2290 return false;
2291
2292 SmallVector<MCRegister, 2> Ops{*CurScopeRes.Value};
2293 if (CurInlinedAt) {
2294 // If the global emission did not include this inlined-at case, we skip it.
2295 MCRegister InlinedReg = DebugInlinedAtRegs.lookup(CurInlinedAt);
2296 if (!InlinedReg.isValid())
2297 return false;
2298 Ops.push_back(InlinedReg);
2299 }
2300
2301 // A new DebugScope region is needed.
2302 emitExtInst(SPIRV::NonSemanticExtInst::DebugScope, VoidTypeReg, ExtInstSetReg,
2303 Ops, MAI);
2304
2305 LastScopeMI = MI;
2306 return true;
2307}
2308
2309void SPIRVNonSemanticDebugHandler::emitDebugLineForInstruction(
2310 const MachineInstr *MI) {
2311 assert(DebugFunctionDefinitionEmitted &&
2312 "DebugFunctionDefinition must be emitted");
2313 assert(CurrentMAI && "CurrentMAI must be set");
2314
2315 // The region is implicitly closed at each basic block boundary, so a
2316 // LastLineMI from another block must be dropped before it is read below:
2317 // the new block needs its own DebugLine, and has no region left to close.
2318 if (LastLineMI && MI->getParent() != LastLineMI->getParent())
2319 LastLineMI = nullptr;
2320
2321 SPIRV::ModuleAnalysisInfo &MAI = *CurrentMAI;
2322 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2323 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2324
2325 const DILocation *DL = MI->getDebugLoc().get();
2326 if (!DL) {
2327 // No location for the current instruction
2328 if (LastLineMI) {
2329 // Close the current DebugLine region.
2330 emitExtInst(SPIRV::NonSemanticExtInst::DebugNoLine, VoidTypeReg,
2331 ExtInstSetReg, {}, MAI);
2332 LastLineMI = nullptr;
2333 }
2334 // No DebugLine region to close.
2335 return;
2336 }
2337
2338 // At this point, there is a location for the current instruction.
2339 // If it matches the last emitted DebugLine, no new DebugLine region is
2340 // needed. Otherwise, emit a new DebugLine region and update LastLineMI.
2341
2342 MCRegister FileStrReg = getCachedScopePathOpStringReg(
2343 DL->getScope(), /*UseEmptyPathIfNullScope=*/true);
2344 unsigned Line = DL->getLine();
2345 unsigned Col = DL->getColumn();
2346
2347 unsigned I32TypeId = CachedOpTypeInt32Reg.id();
2348 MCRegister SrcReg = DebugSourceRegByFileStr.lookup(FileStrReg.id());
2349 MCRegister LineReg = ScalarConstantCache.lookup({I32TypeId, Line});
2350 MCRegister ColStartReg = ScalarConstantCache.lookup({I32TypeId, Col});
2351 MCRegister ColEndReg = ScalarConstantCache.lookup({I32TypeId, Col + 1});
2352
2353 // The elements of each collected DILocation (DebugSource, line/column
2354 // constants) are pre-emitted from LLVM-IR instruction !dbg attachments and
2355 // debug-program records; MIR is expected to reuse those same locations (or
2356 // carry none). A lookup miss means codegen attached a source position whose
2357 // elements were never pre-emitted, and debug-line emission is skipped.
2358 if (!SrcReg.isValid() || !LineReg.isValid() || !ColStartReg.isValid() ||
2359 !ColEndReg.isValid())
2360 return;
2361
2362 // Current location matches the last emitted DebugLine region.
2363 if (LastLineMI && MI->getDebugLoc() == LastLineMI->getDebugLoc())
2364 return;
2365
2366 // A new DebugLine region is needed.
2367 emitExtInst(SPIRV::NonSemanticExtInst::DebugLine, VoidTypeReg, ExtInstSetReg,
2368 {SrcReg, LineReg, LineReg, ColStartReg, ColEndReg}, MAI);
2369
2370 LastLineMI = MI;
2371}
2372
2374 const MachineInstr *MI = CurMI;
2375 CurMI = nullptr;
2376
2377 if (!MI || !GlobalNSDIEnabled || !CurrentMF)
2378 return;
2379
2380 if (DebugFunctionDefinitionEmitted || MI != LastFunctionOpVariable)
2381 return;
2382
2383 // If this is the last function-level OpVariable, emit the
2384 // DebugFunctionDefinition. Otherwise, we had already done it before right
2385 // after the OpLabel (see notifyEntryLabelEmitted).
2386 assert(CurrentMAI && "CurrentMAI must be set");
2387 tryEmitDebugFunctionDefinition(*CurrentMAI);
2388}
2389
2391 const MachineFunction &MF) {
2392 if (!GlobalNSDIEnabled || DebugFunctionDefinitionEmitted || !CurrentMF)
2393 return;
2394
2395 assert(CurrentMF == &MF &&
2396 "notification does not match the current MachineFunction");
2397
2398 if (LastFunctionOpVariable)
2399 return;
2400
2401 // If there are no function-level OpVariables, emit the
2402 // DebugFunctionDefinition. Otherwise, DebugFunctionDefinition is emitted
2403 // after the last OpVariable (see endInstruction).
2404 tryEmitDebugFunctionDefinition(*CurrentMAI);
2405}
2406
2407void SPIRVNonSemanticDebugHandler::collectDebugExpressions(
2408 const SPIRV::ModuleAnalysisInfo &MAI,
2410 for (const MachineInstr *MI : MAI.DebugValueMIs)
2411 Out.insert(MI->getDebugExpression());
2412}
2413
2416 if (GlobalDIEmitted)
2417 return;
2418
2419 GlobalDIEmitted = true;
2420
2421 if (CompileUnits.empty()) {
2422 GlobalNSDIEnabled = false;
2423 return;
2424 }
2425
2426 // Retrieve the ext inst set register allocated by prepareModuleOutput().
2427 MCRegister ExtInstSetReg = MAI.getExtInstSetReg(NSSet);
2428 if (!ExtInstSetReg.isValid()) {
2429 GlobalNSDIEnabled = false;
2430 return;
2431 }
2432
2433#ifndef NDEBUG
2434 assert(NonSemanticOpStringsSectionEmitted &&
2435 "emitNonSemanticDebugStrings() must run before "
2436 "emitNonSemanticGlobalDebugInfo()");
2437#endif
2438
2439 CurrentMAI = &MAI;
2440
2441 MCRegister VoidTypeReg = getOrEmitOpTypeVoidReg(MAI);
2442 MCRegister I32TypeReg = getOrEmitOpTypeInt32Reg(MAI);
2443
2444 CachedDebugInfoNoneReg = emitExtInst(SPIRV::NonSemanticExtInst::DebugInfoNone,
2445 VoidTypeReg, ExtInstSetReg, {}, MAI);
2446
2447 // Emit integer constants shared across all NSDI instructions. The constant
2448 // cache ensures each value is emitted at most once even when referenced from
2449 // multiple instructions. All constants are pre-emitted before any DebugSource
2450 // so that the output order is: constants, then
2451 // DebugSource+DebugCompilationUnit pairs. This keeps OpConstant instructions
2452 // grouped before the OpExtInst instructions.
2453
2454 // The Version operand of DebugCompilationUnit is the version of the
2455 // NonSemantic.Shader.DebugInfo instruction set, which is 100 for
2456 // "NonSemantic.Shader.DebugInfo.100" (NonSemanticShaderDebugInfo100Version).
2457 MCRegister DebugInfoVersionReg = emitOpConstantI32(100, I32TypeReg, MAI);
2458 MCRegister DwarfVersionReg =
2459 emitOpConstantI32(static_cast<uint32_t>(DwarfVersion), I32TypeReg, MAI);
2460
2461 // Pre-emit source language constants for all compile units before entering
2462 // the DebugSource loop.
2463 SmallVector<MCRegister> SrcLangRegs =
2464 map_to_vector(CompileUnits, [&](const CompileUnitInfo &Info) {
2465 return emitOpConstantI32(Info.SpirvSourceLanguage, I32TypeReg, MAI);
2466 });
2467
2468 // Emit DebugSource and DebugCompilationUnit for each compile unit.
2469 for (auto [Info, SrcLangReg] : llvm::zip(CompileUnits, SrcLangRegs)) {
2470 MCRegister FileStrReg = ScopeToPathOpStringReg.lookup(Info.TheCU);
2471 assert(FileStrReg.isValid() &&
2472 "CU path OpString must be emitted in emitNonSemanticDebugStrings");
2473 MCRegister DebugSourceReg = getOrEmitDebugSourceForFileStrReg(
2474 FileStrReg, VoidTypeReg, ExtInstSetReg, MAI);
2475 MCRegister CUDbgReg = emitExtInst(
2476 SPIRV::NonSemanticExtInst::DebugCompilationUnit, VoidTypeReg,
2477 ExtInstSetReg,
2478 {DebugInfoVersionReg, DwarfVersionReg, DebugSourceReg, SrcLangReg},
2479 MAI);
2480 if (Info.TheCU)
2481 DebugScopeRegs[Info.TheCU] = CUDbgReg;
2482 }
2483
2484 for (const DIScope *S :
2485 concat<const DIScope *const>(LexicalBlocks, DebugTypes, Subprograms))
2486 getOrCreateDebugScope(S);
2487
2488 // Emit DebugLocalVariable after DebugFunction and their lexical blocks so the
2489 // Parent operand can resolve. Record the ids for DebugDeclare.
2490 for (const DILocalVariable *LV : LocalVariables)
2491 if (auto LVReg = emitDebugLocalVariable(LV, VoidTypeReg, I32TypeReg,
2492 ExtInstSetReg, MAI))
2493 DebugLocalVariableRegs[LV] = *LVReg;
2494
2495 // Opcodes like DebugDeclare are part of the function body, but
2496 // DebugExpression is not. For such opcodes, we collect the expressions
2497 // directly from the MIR to avoid inconsistencies with those in the LLVM IR
2498 // module.
2500 collectDebugExpressions(MAI, Expressions);
2501 for (const DIExpression *Expr : Expressions)
2502 if (auto ExprReg = emitDebugExpression(Expr, VoidTypeReg, I32TypeReg,
2503 ExtInstSetReg, MAI))
2504 DebugExpressionRegs[Expr] = *ExprReg;
2505
2506 // Emit DebugGlobalVariable for each collected DIGlobalVariable.
2507 for (const auto &[GV, Info] : GlobalVariableDebugInfoMap)
2508 emitDebugGlobalVariable(GV, Info, VoidTypeReg, I32TypeReg, ExtInstSetReg,
2509 MAI);
2510
2511 // Emit DebugInlinedAt allowing recursive inlining.
2512 for (const DILocation *DL : UniqueDebugLocations)
2513 if (const DILocation *IA = DL->getInlinedAt())
2514 getOrEmitDebugInlinedAt(IA, VoidTypeReg, I32TypeReg, ExtInstSetReg, MAI);
2515
2516 // Repeating the lookups emitDebugBinding() performs emits a type and a
2517 // constant only for an assignment that will reach a DebugValue.
2518 for (const MachineInstr *MI : MAI.DebugValueMIs) {
2519 std::optional<std::pair<const DIBasicType *, uint64_t>> Const =
2521 if (!Const)
2522 continue;
2523 if (!DebugLocalVariableRegs.contains(MI->getDebugVariable()) ||
2524 !DebugExpressionRegs.contains(MI->getDebugExpression()))
2525 continue;
2526 auto [It, Inserted] = ConstantValueRegs.try_emplace(*Const, MCRegister());
2527 if (Inserted)
2528 It->second = findOrEmitScalarConstant(Const->first, Const->second, MAI);
2529 if (!It->second.isValid())
2530 ConstantValueRegs.erase(It);
2531 }
2532
2533 for (const DILocation *DL : UniqueDebugLocations) {
2534 emitOpConstantI32(DL->getLine(), I32TypeReg, MAI);
2535 emitOpConstantI32(DL->getColumn(), I32TypeReg, MAI);
2536 emitOpConstantI32(DL->getColumn() + 1, I32TypeReg, MAI);
2537 MCRegister FileStrReg =
2538 getCachedScopePathOpStringReg(DL->getScope(),
2539 /*UseEmptyPathIfNullScope=*/true);
2540 getOrEmitDebugSourceForFileStrReg(FileStrReg, VoidTypeReg, ExtInstSetReg,
2541 MAI);
2542 }
2543
2544 GlobalNSDIEnabled = true;
2545}
2546
2548SPIRVNonSemanticDebugHandler::getDebugFullPath(const DIScope *Scope) const {
2549 SmallString<128> Out;
2550 if (!Scope)
2551 return Out;
2552 StringRef Filename = Scope->getFilename();
2553 const auto Style = sys::path::Style::native;
2554 if (sys::path::is_absolute(Filename, Style))
2555 Out.assign(Filename.begin(), Filename.end());
2556 else {
2557 StringRef Dir = Scope->getDirectory();
2558 Out.assign(Dir.begin(), Dir.end());
2559 sys::path::append(Out, Style, Filename);
2560 }
2561 return Out;
2562}
2563
2564MCRegister SPIRVNonSemanticDebugHandler::getOrEmitDebugSourceForFileStrReg(
2565 MCRegister FileStrReg, MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
2567 const unsigned Key = FileStrReg.id();
2568 auto It = DebugSourceRegByFileStr.find(Key);
2569 if (It != DebugSourceRegByFileStr.end())
2570 return It->second;
2571
2572 MCRegister DS = emitExtInst(SPIRV::NonSemanticExtInst::DebugSource,
2573 VoidTypeReg, ExtInstSetReg, {FileStrReg}, MAI);
2574 DebugSourceRegByFileStr[Key] = DS;
2575 return DS;
2576}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static Error unsupported(const char *Str, const Triple &T)
Definition MachO.cpp:79
BitTracker BT
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains constants used for implementing Dwarf debug support.
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
static NVPTX::Scope resolveScope(NVPTX::Scope S, const NVPTXSubtarget *T)
static constexpr StringLiteral Filename
#define P(N)
SI Fold Operands
static const MachineInstr * findAdjacentEmittedInstruction(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI, bool Forward)
static std::optional< SmallVector< uint32_t, 3 > > mapExprOperand(const DIExpression::ExprOperand &Op)
static bool scalarTypeNeedsCapability(const DIBasicType *BT)
static bool isBooleanType(const DIBasicType *BT)
static bool constantHasValue(const MachineInstr &MI, uint64_t Value, bool IsWide)
static void collectLexicalBlockChain(const DIScope *S, SetVector< const DIScope * > &Out)
static bool isMergeInstruction(unsigned Opcode)
static std::optional< std::pair< const DIBasicType *, uint64_t > > getConstantDbgValueBits(const MachineInstr &MI)
static MCRegister getResultId(const MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI)
static bool isEmitted(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI)
static std::optional< Register > getDebugValueReg(const MachineInstr &MI)
static bool isDebugLocTarget(const MachineInstr *MI, SPIRV::ModuleAnalysisInfo &MAI)
static uint64_t constantBits(uint64_t Value, const DIBasicType *BT)
static std::optional< Register > getDebugDeclareStorageReg(const MachineInstr &MI)
static std::optional< NonSemanticDebugOp > mapDwarfOpToNonSemanticOp(uint64_t DwarfOp)
static const DIBasicType * stripToScalarType(const DIType *Ty)
static void collectDebugLocationsAndLocalVariables(const Module &M, SetVector< const DILocation * > &Locations, SetVector< const DILocalVariable * > &LVs)
spirv structurize SPIRV
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:558
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines less commonly used SmallVector utilities.
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:95
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:110
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
Basic type, like 'int' or 'float'.
A lightweight wrapper around an expression operand.
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
A pair of DIGlobalVariable and DIExpression.
DIDerivedType * getStaticDataMemberDeclaration() const
StringRef getLinkageName() const
Debug lexical block.
DILocalScope * getScope() const
Get the local scope for this variable.
Debug lexical block.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
DIFlags
Debug info flags.
Base class for scope-like contexts.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
Base class for types.
DIFile * getFile() const
DIScope * getScope() const
DIType * getType() const
unsigned getLine() const
StringRef getName() const
Base class for non-instruction debug metadata records that have positions within IR.
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
void beginModule(Module *M) override
Utility to find all debug info in a module.
Definition DebugInfo.h:102
LLVM_ABI void processModule(const Module &M)
Process entire module and collect debug info anchors.
iterator_range< global_variable_expression_iterator > global_variables() const
Definition DebugInfo.h:152
iterator_range< subprogram_iterator > subprograms() const
Definition DebugInfo.h:150
iterator_range< type_iterator > types() const
Definition DebugInfo.h:156
iterator_range< scope_iterator > scopes() const
Definition DebugInfo.h:158
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
DISubprogram * getSubprogram() const
Get the attached subprogram.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void setFlags(unsigned F)
Definition MCInst.h:204
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
constexpr unsigned id() const
Definition MCRegister.h:82
Metadata node.
Definition Metadata.h:1081
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
bool equalsStr(StringRef Str) const
Definition Metadata.h:924
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1800
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void emitNonSemanticDebugStrings(SPIRV::ModuleAnalysisInfo &MAI)
Emit OpString instructions for all NSDI file paths and basic type names into the debug section (secti...
void beginModule(Module *M) override
Collect compile-unit metadata from the module.
void endFunctionImpl(const MachineFunction *MF) override
void beginFunctionImpl(const MachineFunction *MF) override
void emitNonSemanticGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &MAI)
Emit module-scope NSDI instructions (DebugSource, DebugCompilationUnit, DebugTypeBasic,...
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 endInstruction() override
Process end of an instruction.
void notifyEntryLabelEmitted(const MachineFunction &MF)
Called after the synthesized entry OpLabel has been emitted.
A vector that has set insertion semantics.
Definition SetVector.h:57
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
iterator begin() const
Definition StringRef.h:114
iterator end() const
Definition StringRef.h:116
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
constexpr std::underlying_type_t< E > Underlying(E Val)
Check that Val is in range for E, and return Val cast to E's underlying type.
@ Entry
Definition COFF.h:862
constexpr MCPhysReg SP
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void addStringImm(StringRef Str, MCInst &Inst)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1807
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
#define N
MCRegister getExtInstSetReg(unsigned SetNum)
DenseMap< unsigned, MCRegister > ExtInstSetMap
InstrList & getMSInstrs(unsigned MSType)
MCRegister getRegisterAlias(const MachineFunction *MF, Register Reg)
bool getSkipEmission(const MachineInstr *MI)
MCRegister getGlobalObjReg(const GlobalObject *GO)
SmallVector< const MachineInstr * > DebugValueMIs
void addExtension(Extension::Extension ToAdd)