LLVM 24.0.0git
SPIRVNonSemanticDebugHandler.h
Go to the documentation of this file.
1//===-- SPIRVNonSemanticDebugHandler.h - 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//
10// This file declares SPIRVNonSemanticDebugHandler, a DebugHandlerBase subclass
11// that emits NonSemantic.Shader.DebugInfo.100 instructions in the SPIR-V
12// AsmPrinter. It replaces SPIRVEmitNonSemanticDI, which was a
13// MachineFunctionPass, with a handler that controls instruction placement
14// directly instead of routing through SPIRVModuleAnalysis.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_LIB_TARGET_SPIRV_SPIRVNONSEMANTICDEBUGHANDLER_H
19#define LLVM_LIB_TARGET_SPIRV_SPIRVNONSEMANTICDEBUGHANDLER_H
20
22#include "SPIRVModuleAnalysis.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/StringMap.h"
32#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCRegister.h"
34#include <optional>
35#include <type_traits>
36#include <utility>
37
38namespace llvm {
39
40class GlobalVariable;
42class SPIRVSubtarget;
44
45/// AsmPrinter handler that emits NonSemantic.Shader.DebugInfo.100 (NSDI)
46/// instructions for the SPIR-V backend. Registered with SPIRVAsmPrinter when
47/// the module contains debug info (llvm.dbg.cu).
48///
49/// Call sequence:
50/// - beginModule() collects compile-unit metadata.
51/// - prepareModuleOutput() adds the extension and ext-inst set to MAI.
52/// - generateModuleDebugInfo() buffers the module-scope NSDI and adds
53/// SPV_KHR_relaxed_extended_instruction if it used a forward reference.
54/// - emitNonSemanticDebugStrings() flushes the NSDI OpStrings in section 7.
55/// - emitNonSemanticGlobalDebugInfo() flushes the module-scope NSDI in
56/// section 10.
57/// - beginFunctionImpl() prepares per-function DebugFunctionDefinition state
58/// and runs analyzeDebugRecords() over the whole function.
59/// - endInstruction() emits DebugFunctionDefinition after the last function-
60/// level OpVariable; SPIRVAsmPrinter calls notifyEntryLabelEmitted() after
61/// the synthesized entry OpLabel when there are no OpVariables.
62/// - beginInstruction() emits the DebugScope and DebugLine for the instruction
63/// being printed, and the DebugDeclare and DebugValue anchored on it.
64/// - endFunctionImpl() resets per-function state.
66 bool UseLexicalBlockDiscriminatorScope = false;
67 bool UseDebugScopeForwardRefs = false;
68 bool AllowDebugDeclareUntypedVariable = false;
69
70 static constexpr unsigned NSSet = static_cast<unsigned>(
71 SPIRV::InstructionSet::NonSemantic_Shader_DebugInfo_100);
72
73 struct CompileUnitInfo {
74 const DICompileUnit *TheCU = nullptr;
75 SmallString<128> FilePath;
76 unsigned SpirvSourceLanguage = 0; // NonSemantic.Shader.DebugInfo.100 source
77 // language code (section 4.3)
78 };
80 int64_t DwarfVersion = 0;
81
83
84 // Compile unit whose enums list names each enum. DIBuilder gives a file-scope
85 // enum a null scope, so this list is the only record of its unit.
87
88 // NonSemantic debug instruction result id per emitted scope.
90
91 enum class EmitStatus {
92 Emitted,
93 Unsupported,
94 InProgress,
95 };
96
97 // One scope instruction, built but not yet emitted. getOrCreateDebugScope
98 // is the only place that emits it.
99 struct PreparedScope {
100 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode{};
102
103 PreparedScope() = default;
104 PreparedScope(SPIRV::NonSemanticExtInst::NonSemanticExtInst Op,
106 : Opcode(Op), Operands(Ops.begin(), Ops.end()) {}
107 };
108
109 // Status plus a payload. Value is set only when the status is Emitted, so
110 // InProgress and Unsupported carry no id and no PreparedScope. The payload
111 // is an id for a scope that already exists, and a PreparedScope for an
112 // instruction that getOrCreateDebugScope has not emitted yet.
113 template <typename T> struct EmitResult {
114 EmitStatus Status = EmitStatus::Unsupported;
115 std::optional<T> Value;
116
117 static EmitResult emitted(T V) {
118 EmitResult R;
119 R.Status = EmitStatus::Emitted;
120 R.Value = std::move(V);
121 return R;
122 }
123 static EmitResult unsupported() { return {}; }
124 static EmitResult inProgress() {
125 EmitResult R;
126 R.Status = EmitStatus::InProgress;
127 return R;
128 }
129
130 template <typename U>
131 static EmitResult failure(const EmitResult<U> &Other) {
132 assert(!Other && "failure() requires a non-emitted result");
133 EmitResult R;
134 R.Status = Other.Status;
135 return R;
136 }
137
138 explicit operator bool() const {
139 assert(Value.has_value() == (Status == EmitStatus::Emitted) &&
140 "payload is set exactly when the result is emitted");
141 if constexpr (std::is_same_v<T, MCRegister>)
142 assert(!Value || Value->isValid());
143 return Status == EmitStatus::Emitted;
144 }
145 };
146
147 // Used to track which scopes are in progress, and which operands are used by
148 // a forward references. Operands must be later defined even if the scope
149 // fails to emit.
150 struct InProgressScope {
151 MCRegister Id;
152 bool ForwardReferenced = false;
153 };
154
155 // Types and scopes whose instruction is currently being built.
157
158 // True when UseDebugScopeForwardRefs is set and prepareModuleOutput saw
159 // that SPV_KHR_relaxed_extended_instruction may be used.
160 bool CanUseForwardRefs = false;
161
162 // True once an OpExtInstWithForwardRefsKHR was built.
163 bool UsedForwardRefs = false;
164
165 SmallVector<MCInst> PendingStrings;
166 SmallVector<MCInst> PendingGlobalDI;
167 SmallVector<MCInst> *PendingSink = nullptr;
168
169 // Types and scopes that are not supported.
171
172 // DISubprogram nodes collected in beginModule().
174
175 // Distinct DILocations from instruction !dbg attachments and debug program
176 // records (#dbg_declare, #dbg_value, #dbg_assign, #dbg_label).
177 SetVector<const DILocation *> UniqueDebugLocations;
178
179 struct GlobalVariableDebugInfo {
180 const DIExpression *Expr = nullptr;
181 const GlobalVariable *LLVMGV = nullptr;
182 };
184 GlobalVariableDebugInfoMap;
185
186 // Distinct DILocalVariable nodes collected in beginModule() from dbg records
187 // and from DISubprogram retained nodes.
189
190 // DebugLocalVariable result id per variable that module-scope emission
191 // actually emitted. DebugDeclare needs it for its Local Variable operand; a
192 // variable missing here (skipped type or scope) gets no declare.
194
195 // DebugExpression result id per DIExpression that could be lowered. An
196 // expression missing here uses operations with no NonSemantic counterpart,
197 // so declares referencing it are skipped rather than described wrongly.
199
200 // Distinct DILexicalBlock, DINamespace, and DILexicalBlockFile scopes,
201 // parent-before-child order, collected in beginModule().
202 SetVector<const DIScope *> LexicalBlocks;
203
204 // DebugInlinedAt result id per DILocation used as an inlined-at chain link.
206
207 // Path \c OpString result id per \c DIScope (CU, \c DIFile, declaration
208 // \c DISubprogram, …). Filled during \c generateDebugStrings() using
209 // \c getDebugFullPath + \c emitOpStringIfNew; section 10 uses it for
210 // \c DebugSource without recomputing path text.
211 DenseMap<const DIScope *, MCRegister> ScopeToPathOpStringReg;
212
213 // DebugSource result id keyed by path \c OpString id (\c MCRegister::id()),
214 // deduplicating when the same file string is reused.
215 DenseMap<unsigned, MCRegister> DebugSourceRegByFileStr;
216
217 // Maps OpString contents to result id. Populated only by emitOpStringIfNew()
218 // during generateDebugStrings(); section 10 uses getCachedOpStringReg()
219 // (lookup only).
220 StringMap<MCRegister> OpStringContentCache;
221
222#ifndef NDEBUG // Only declare the variable for debugging purposes.
223 // True after generateDebugStrings() built the NSDI OpStrings for this
224 // module. generateModuleDebugInfo() calls that before
225 // generateGlobalDebugInfo().
226 bool DebugStringsGenerated = false;
227#endif
228
229 MCRegister CachedEmptyStringReg;
230
231 MCRegister CachedDebugInfoNoneReg;
232
233 MCRegister CachedOpTypeVoidReg;
234
235 MCRegister CachedOpTypeInt32Reg;
236
237 // Result id per SPIR-V scalar type this handler needed, keyed by opcode and
238 // width. MB_TypeConstVars holds only what module analysis collected, so a
239 // type emitted here has to be remembered separately to stay unique.
241
242 // Result id per scalar constant, keyed by its type's id and its bits. Keying
243 // on the type lets two DIBasicTypes describing it share a constant.
245
246 // Result id per collected constant, keyed by its type and bits. Filled
247 // during module-scope emission, since an OpConstant has to precede every
248 // function body that names it.
250 ConstantValueRegs;
251
252 // Cache of already-emitted DebugOperation instructions, keyed by NonSemantic
253 // opcode followed by the 32-bit operation arguments. Inline size 3 is the
254 // spec maximum (opcode plus at most two operands: BitPiece, Fragment).
255 DenseMap<SmallVector<uint32_t, 3>, MCRegister> DebugOperationCache;
256
257 // Cache of already-emitted DebugExpression instructions, keyed by the
258 // DebugOperation result ids in operand order. Useful for debug values
259 // and global-variable init expressions.
260 DenseMap<SmallVector<MCRegister>, MCRegister> DebugExpressionCache;
261
262 // True once generateModuleDebugInfo() has run. Both
263 // SPIRVAsmPrinter::emitFunctionHeader() and emitEndOfAsmFile() may call
264 // outputModuleSections(), each guarded by ModuleSectionsEmitted, so only
265 // one fires. This flag provides a secondary guard in case the call sites
266 // change.
267 bool GlobalDIEmitted = false;
268
269 // True when generateGlobalDebugInfo() completed module-scope NSDI
270 // generation for this module.
271 bool GlobalNSDIEnabled = false;
272
273 SPIRV::ModuleAnalysisInfo *CurrentMAI = nullptr;
274
275 const MachineFunction *CurrentMF = nullptr;
276
277 const MachineInstr *LastFunctionOpVariable = nullptr;
278
279 bool DebugFunctionDefinitionEmitted = false;
280
281 // Instruction that opened the DebugLine / DebugScope region currently in
282 // effect, or nullptr when no region is open. The two are tracked separately
283 // because a DebugScope region usually spans several DebugLine regions, and
284 // either one can skip emission on a cache miss.
285 const MachineInstr *LastLineMI = nullptr;
286 const MachineInstr *LastScopeMI = nullptr;
287
288 // Result ids in MB_TypeConstVars, which precedes every function body. Filled
289 // once per module in prepareModuleOutput().
290 DenseSet<MCRegister> ModuleScopeIds;
291
292 /// A DebugDeclare or DebugValue waiting for its anchor to be printed.
293 struct DebugRecord {
294 const MachineInstr *MI; ///< The DBG_VALUE this came from.
295 SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode;
296 MCRegister LocationReg; ///< The Variable or Value operand.
297 };
298
299 // Records to emit before their anchor is printed, built once per function by
300 // analyzeDebugRecords() and only read afterwards.
302
303 /// Resolve each NSDI option from its command-line flag, falling back to the
304 /// default for the target triple when the flag is not given.
305 void initOptions(const SPIRVTargetMachine &TM);
306
307public:
309
310 /// Collect compile-unit metadata from the module. Called by
311 /// AsmPrinter::doInitialization() via the handler list. No emission.
312 void beginModule(Module *M) override;
313
314 /// Output the NSDI OpStrings built by generateModuleDebugInfo() into the
315 /// debug section (section 7 of the SPIR-V module layout). Must be called
316 /// from SPIRVAsmPrinter::outputDebugSourceAndStrings().
318
319 /// Add SPV_KHR_non_semantic_info extension and
320 /// NonSemantic.Shader.DebugInfo.100 ext inst set entry to MAI. Must be called
321 /// before outputGlobalRequirements() and outputOpExtInstImports() in
322 /// SPIRVAsmPrinter::outputModuleSections().
323 void prepareModuleOutput(const SPIRVSubtarget &ST,
325
326 /// Buffer the module-scope NSDI and add SPV_KHR_relaxed_extended_instruction
327 /// to MAI if a forward reference was built. Must be called between
328 /// prepareModuleOutput() and outputGlobalRequirements().
330
331 /// Output the module-scope NSDI built by generateModuleDebugInfo(). Called
332 /// by SPIRVAsmPrinter::outputModuleSections() at section 10 in place of
333 /// outputModuleSection(MB_NonSemanticGlobalDI).
335
336 /// Called after the synthesized entry \c OpLabel has been emitted.
338
339protected:
340 // All module-level output is driven by generateModuleDebugInfo() and the
341 // emit* calls in SPIRVAsmPrinter::outputModuleSections(). Nothing
342 // needs to happen in the AsmPrinterHandler::endModule() callback.
343 void endModule() override {}
344
345 // DebugHandlerBase stores MMI as a pointer copy from Asm->MMI at construction
346 // time (DebugHandlerBase.cpp: `MMI(Asm->MMI)`). The handler is constructed
347 // before AsmPrinter::doInitialization() runs, so Asm->MMI is null at that
348 // point and MMI remains null for this handler's entire lifetime. Do not call
349 // the base-class beginInstruction/endInstruction — they dereference MMI to
350 // create temp symbols for label tracking and would crash.
351 // Future local NSDI that needs MCContext must use
352 // Asm->OutStreamer->getContext() rather than MMI->getContext().
353 void beginInstruction(const MachineInstr *MI) override;
354 void endInstruction() override;
355
356 // Override beginFunctionImpl(), not beginFunction():
357 // DebugHandlerBase::beginFunction() populates LScopes and DbgValues needed
358 // for future DebugLine emission.
359 void beginFunctionImpl(const MachineFunction *MF) override;
360 void endFunctionImpl(const MachineFunction *MF) override;
361
362private:
363 void emitDebugFunctionDefinition(MCRegister DebugFunctionReg,
364 MCRegister OpFunctionReg,
366
367 void resetPerFunctionDebugState();
368
369 /// Resolve the instruction that a per-instruction DebugLine/DebugScope
370 /// update should attach to: \p MI adjusted forward past a merge
371 /// instruction to its terminator, or \c std::nullopt if \p MI is not a
372 /// valid attachment point (skip-emission, or one of the structural opcodes
373 /// that can never carry DebugLine/DebugScope: OpFunction,
374 /// OpFunctionParameter, OpFunctionEnd, OpLabel, OpPhi).
375 std::optional<const MachineInstr *>
376 resolveDebugLocTarget(const MachineInstr *MI);
377
378 /// Open the DebugScope region \p MI belongs to, closing the previous one.
379 ///
380 /// \returns False when \p MI's scope has no \c DebugScope, or its chain no
381 /// \c DebugInlinedAt, leaving the open region someone else's.
382 bool emitDebugScopeForInstruction(const MachineInstr *MI);
383 void emitDebugLineForInstruction(const MachineInstr *MI);
384 void preparePerFunctionDebug(const MachineFunction *MF);
385 void tryEmitDebugFunctionDefinition(SPIRV::ModuleAnalysisInfo &MAI);
386
387 /// Build the NSDI OpStrings, caching their ids in \c OpStringContentCache and
388 /// \c ScopeToPathOpStringReg.
389 void generateDebugStrings(SPIRV::ModuleAnalysisInfo &MAI);
390
391 /// Build the section 10 NSDI. Requires generateDebugStrings() first.
392 void generateGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &MAI);
393
394 /// Output and clear \p Insts.
395 void flushPendingInsts(SmallVectorImpl<MCInst> &Insts);
396
397 void emitMCInst(MCInst &Inst);
398 MCRegister emitOpString(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
399
400 /// generateDebugStrings() only: emit OpString and cache it if not already
401 /// present. Must not be called after DebugStringsGenerated is set. Returns
402 /// the path (or string) \c OpString result id.
403 MCRegister emitOpStringIfNew(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
404
405 /// Section 10 only: lookup OpString id from cache; asserts if missing or if
406 /// generateDebugStrings() did not complete.
407 MCRegister getCachedOpStringReg(StringRef S);
408
409 /// generateDebugStrings() only: emit the path \c OpString for \p Scope and
410 /// cache it under \p Scope. Returns the \c OpString result id. A \p Scope
411 /// already seen returns the cached id without rebuilding the path. A null
412 /// \p Scope maps to the empty path and is cached like any other, though
413 /// section 10 reads it through \c getCachedScopePathOpStringReg, which
414 /// handles null separately.
415 MCRegister emitAndCacheScopePathOpStringReg(const DIScope *Scope,
417
418 /// Section 10 only: lookup path \c OpString id for \p Scope from
419 /// \c ScopeToPathOpStringReg; asserts if missing or invalid. When
420 /// \p UseEmptyPathIfNullScope is true and \p Scope is null, returns
421 /// \c CachedEmptyStringReg instead.
423 getCachedScopePathOpStringReg(const DIScope *Scope,
424 bool UseEmptyPathIfNullScope = false);
425 MCRegister emitOpConstantI32(uint32_t Value, MCRegister I32TypeReg,
427
428 /// Mark in-progress scopes named by \p Operands. Return true when any
429 /// operand is such an id. A marked id needs a definition if that scope fails.
430 bool markForwardReferencedOperands(ArrayRef<MCRegister> Operands);
431
432 MCRegister emitExtInst(SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
433 MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
436 std::optional<MCRegister> ResultReg = std::nullopt);
437
438 /// Return OpTypeVoid id for this module (lazy lookup / emit, then cache).
439 MCRegister getOrEmitOpTypeVoidReg(SPIRV::ModuleAnalysisInfo &MAI);
440
441 /// Return OpTypeInt 32 0 id for this module (lazy lookup / emit, then cache).
442 MCRegister getOrEmitOpTypeInt32Reg(SPIRV::ModuleAnalysisInfo &MAI);
443
444 /// Find OpTypeVoid in the already-emitted TypeConstVars section, or emit one
445 /// if the module does not contain it (e.g. no void-returning functions).
446 MCRegister findOrEmitOpTypeVoid(SPIRV::ModuleAnalysisInfo &MAI);
447
448 /// Find OpTypeInt 32 0 in the already-emitted TypeConstVars section, or emit
449 /// one if the module does not contain it.
450 MCRegister findOrEmitOpTypeInt32(SPIRV::ModuleAnalysisInfo &MAI);
451
452 /// Return the id for the type or scope \p S, emitting it and the types and
453 /// scopes it names first. One already in \c DebugScopeRegs is Emitted. A null
454 /// \p S or one in \c FailedScopes is Unsupported. Entering a scope reserves
455 /// its result id. A back edge (\p S already in \c ScopesInProgress) returns
456 /// that id when \c CanUseForwardRefs is set, and InProgress otherwise. If
457 /// emission fails after an emitted instruction used that id, it is defined as
458 /// DebugInfoNone. An id that nothing named stays undefined. An Unsupported
459 /// result is recorded in \c FailedScopes; an InProgress one is not, so a
460 /// later walk can retry it.
461 EmitResult<MCRegister> getOrCreateDebugScope(const DIScope *S);
462
463 /// Like \c getOrCreateDebugScope, but a null \p Ty (e.g. the base of a
464 /// \c void*) is Emitted as \c DebugInfoNone.
465 EmitResult<MCRegister> getOrCreateDebugTypeOrNone(const DIType *Ty);
466
467 /// Build the instruction for \p S. Only \c getOrCreateDebugScope calls this
468 /// and emits it.
469 EmitResult<PreparedScope> emitDebugScope(const DIScope *S);
470
471 /// Build the \c DebugType* instruction for \p CT, picked by its tag.
472 EmitResult<PreparedScope> emitDebugTypeForCompositeType(
473 const DICompositeType *CT, MCRegister VoidTypeReg, MCRegister I32TypeReg,
474 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI);
475
476 /// Build the \c DebugType* instruction for \p DT, picked by its tag.
477 EmitResult<PreparedScope>
478 emitDebugTypeForDerivedType(const DIDerivedType *DT, MCRegister VoidTypeReg,
479 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
481
482 /// Build \c DebugTypeBasic for \p BT. Unsupported when the size does not fit
483 /// in 32 bits.
484 EmitResult<PreparedScope> emitDebugTypeBasic(const DIBasicType *BT,
485 MCRegister I32TypeReg,
487
488 /// Build \c DebugTypePointer for \p PT. Unsupported without a DWARF address
489 /// space, which gives the storage class.
490 EmitResult<PreparedScope>
491 emitDebugTypePointer(const DIDerivedType *PT, SPIRV::ModuleAnalysisInfo &MAI);
492
493 /// Build \c DebugTypeQualifier with Type Qualifier value \p Qualifier for
494 /// the qualified type \p QT. Uses \c DebugInfoNone as Base Type when \p QT
495 /// has none.
496 ///
497 /// \returns The base's status if it fails.
498 EmitResult<PreparedScope>
499 emitDebugTypeQualifier(const DIDerivedType *QT, uint32_t Qualifier,
501
502 /// Build one DebugTypeFunction for ST when every DI operand maps to a debug
503 /// type id; otherwise build nothing and return the first failing slot's
504 /// status.
505 EmitResult<PreparedScope>
506 emitDebugTypeFunctionForSubroutineType(const DISubroutineType *ST,
508
509 /// Build \c DebugFunctionDeclaration for the non-defining subprogram \p SP.
510 EmitResult<PreparedScope>
511 emitDebugFunctionDeclaration(const DISubprogram *SP, MCRegister VoidTypeReg,
512 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
514
515 /// Build \c DebugFunction for the defining subprogram \p SP.
516 EmitResult<PreparedScope> emitDebugFunction(const DISubprogram *SP,
517 MCRegister VoidTypeReg,
518 MCRegister I32TypeReg,
519 MCRegister ExtInstSetReg,
521
522 /// Emit \c DebugLocalVariable for the source local variable \p LV:
523 /// Name, Type, Source, Line, Column, Parent, Flags, and an optional Arg
524 /// Number. Line, Column, Flags, and Arg Number are emitted as \c OpConstant
525 /// ids as required for non-semantic debug info. Column is always 0:
526 /// \c DILocalVariable has no column field.
527 ///
528 /// Arg Number is appended when \p LV is a parameter.
529 ///
530 /// \returns The result id register on success. Returns \c std::nullopt and
531 /// emits nothing if \p LV's scope is not an emitted local scope,
532 /// if a non-null type was not emitted in \c DebugScopeRegs, or if
533 /// \c resolveScope returns no id for the Parent operand.
534 std::optional<MCRegister>
535 emitDebugLocalVariable(const DILocalVariable *LV, MCRegister VoidTypeReg,
536 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
538
539 /// Emit \c DebugGlobalVariable for the source global variable \p GV.
540 ///
541 /// (\c SPIRVDebug::Operand::GlobalVariable): Name, Type, Source, Line,
542 /// Column, Parent, Linkage Name, Variable, Flags, and an optional Static
543 /// Member Declaration. Line, Column, and Flags are emitted as \c OpConstant
544 /// ids as required for non-semantic debug info.
545 ///
546 /// \c DebugInfoNone is used for two operands when LLVM has no value to
547 /// supply:
548 /// \c Type when \p GV is a declaration with no DI type (e.g. \c extern void;
549 /// valid IR, \c isDefinition: false); \c Variable when no \c
550 /// llvm::GlobalVariable in this module carries \p GV in its \c !dbg metadata.
551 ///
552 /// \returns The result id register on success. Returns \c std::nullopt and
553 /// emits nothing if a non-null \p GV type was not emitted in \c
554 /// DebugScopeRegs, or \p GV has a static data member declaration that was not
555 /// emitted in \c DebugScopeRegs.
556 std::optional<MCRegister> emitDebugGlobalVariable(
557 const DIGlobalVariable *GV, const GlobalVariableDebugInfo &Info,
558 MCRegister VoidTypeReg, MCRegister I32TypeReg, MCRegister ExtInstSetReg,
560
561 /// Collect the \c DIExpression of every debug value in the module
562 /// (\c DBG_VALUE, \c DBG_VALUE_LIST, \c DBG_INSTR_REF), in MIR order.
563 ///
564 /// Reads MIR rather than IR because only MIR shows which debug values
565 /// survived codegen and in what form, and because an expression synthesized
566 /// during lowering never appears in the IR at all. Must be called from
567 /// module-scope emission, which is where the resulting \c DebugExpression
568 /// instructions have to be emitted. The debug values come from
569 /// \c SPIRVModuleAnalysis, which sees every \c MachineFunction.
570 ///
571 /// Deliberately independent of what the consumers can currently emit, so
572 /// that adding an instruction that needs an expression (\c DebugValue) needs
573 /// no change here. The cost is a \c DebugExpression that nothing references
574 /// yet, for a debug value no instruction is emitted for.
575 void collectDebugExpressions(const SPIRV::ModuleAnalysisInfo &MAI,
577
578 /// Emit one \c DebugOperation for \p Op, reusing a cached result id when the
579 /// same opcode and arguments were already emitted.
580 ///
581 /// \returns The result id register on success. Returns \c std::nullopt and
582 /// emits nothing if \p Op has no NonSemantic counterpart, or carries an
583 /// argument too large for the 32-bit \c OpConstant operands this set
584 /// requires.
585 std::optional<MCRegister>
586 emitDebugOperation(const DIExpression::ExprOperand &Op,
587 MCRegister VoidTypeReg, MCRegister I32TypeReg,
588 MCRegister ExtInstSetReg, SPIRV::ModuleAnalysisInfo &MAI);
589
590 /// Emit one \c DebugOperation per element of \p Expr followed by the
591 /// \c DebugExpression that lists them. Reuses a cached \c DebugExpression
592 /// when that sequence of \c DebugOperation ids was already emitted. An
593 /// empty \p Expr yields a \c DebugExpression with no operands, which is
594 /// what a plain \c !DIExpression() means.
595 ///
596 /// Must be called from module-scope emission only: \c DebugExpression and
597 /// \c DebugOperation are not in the spec's list of instructions allowed
598 /// inside a function, and forward references were removed in Rev 2.
599 ///
600 /// \returns The result id register on success. Returns \c std::nullopt and
601 /// does not emit the \c DebugExpression if any element has no NonSemantic
602 /// counterpart, or carries an argument too large for the 32-bit \c OpConstant
603 /// operands this set requires.
604 std::optional<MCRegister> emitDebugExpression(const DIExpression *Expr,
605 MCRegister VoidTypeReg,
606 MCRegister I32TypeReg,
607 MCRegister ExtInstSetReg,
609
610 /// Fill \c Records from the debug records in \p MF.
611 ///
612 /// Where a record may legally sit is a property of the whole function, and
613 /// emission is unbuffered, so it is settled here rather than while printing.
614 void analyzeDebugRecords(const MachineFunction &MF);
615
616 /// Place the single record \p MI. \p LastEmitted is the nearest preceding
617 /// instruction in this block that reaches the output, or null when there is
618 /// none.
619 ///
620 /// Places nothing when this backend cannot name the record: an unavailable
621 /// location, a declare whose storage is not an \c OpVariable, a constant
622 /// with no module-scope id, a physical register, a variadic value, an
623 /// instruction reference, or a definition that does not dominate \p MI.
624 void resolveDebugRecord(const MachineInstr &MI,
625 const MachineInstr *LastEmitted,
626 const MachineDominatorTree &DomTree);
627
628 /// Store \p MI on \p Anchor, to emit before \p Anchor is printed.
629 void placeRecord(SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
630 const MachineInstr &MI, MCRegister LocationReg,
631 const MachineInstr *Anchor);
632
633 void emitAnalyzedRecords(const MachineInstr *Anchor);
634
635 /// The \c OpConstant id for the constant \p MI assigns, or \c std::nullopt
636 /// when \p MI assigns no constant this backend emitted.
637 std::optional<MCRegister> getConstantValueReg(const MachineInstr &MI) const;
638
639 /// Result id of the constant \p Opcode of type \p TypeReg holding
640 /// \p Value in \c MB_TypeConstVars, or an invalid register when the module
641 /// does not already define it.
642 MCRegister findModuleConstant(unsigned Opcode, MCRegister TypeReg,
643 uint64_t Value, bool IsBool, bool IsWide,
645
646 /// Result id of the SPIR-V type for \p BT, reusing one from
647 /// \c MB_TypeConstVars when the module already defines it. Invalid when
648 /// declaring it would require a capability the module does not have, since
649 /// debug info must not change what the module requires.
650 MCRegister findOrEmitScalarType(const DIBasicType *BT,
652
653 /// Result id of the constant \p Value, with \p BT giving both the SPIR-V
654 /// type and the opcode. Invalid when the type may not be created.
655 MCRegister findOrEmitScalarConstant(const DIBasicType *BT, uint64_t Value,
657
658 /// Result id of the constant \p Value of type \p TypeReg, reusing one from
659 /// \c MB_TypeConstVars or from an earlier call when either already has it.
660 MCRegister findOrEmitConstant(unsigned Opcode, MCRegister TypeReg,
661 uint64_t Value, unsigned Width,
663
664 /// Emit \p Opcode naming \p MI's variable, \p LocationReg and \p MI's
665 /// expression, after \p MI's own \c DebugScope and \c DebugLine. Emits
666 /// nothing when \p MI's variable has no \c DebugLocalVariable, its
667 /// expression no \c DebugExpression, or its scope no id.
668 void emitDebugBinding(SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
669 const MachineInstr *MI, MCRegister LocationReg);
670
671 /// Build \c DebugTypeVector for the vector composite type \p VT.
672 ///
673 /// \returns Emitted when the operands are ready. Unsupported, building
674 /// nothing, if \p VT has no \c DIBasicType base type, if \p VT has more than
675 /// one \c DISubrange element, or if the component count is not a
676 /// compile-time constant. If the base cannot be emitted, returns its status.
677 EmitResult<PreparedScope> emitDebugTypeVector(const DICompositeType *VT,
679
680 /// Build \c DebugTypeArray for the array composite type \p AT.
681 ///
682 /// Operands are the element (base) type id followed by one Component Count
683 /// per \c DISubrange, in DWARF subrange order. A count that is not a
684 /// compile-time constant is 0, matching \c OpTypeRuntimeArray. A matrix
685 /// arrives here as a multi-subrange array and is built with one count per
686 /// dimension.
687 ///
688 /// \returns Emitted when the operands are ready. If \p AT's element type
689 /// cannot be emitted, builds nothing and returns the element's status.
690 EmitResult<PreparedScope> emitDebugTypeArray(const DICompositeType *AT,
692
693 /// Build \c DebugTypeMember for the data member \p M (a \c DIDerivedType with
694 /// \c DW_TAG_member). Operands: Name, Type, Source, Line, Column, Offset,
695 /// Size, Flags. NonSemantic \c DebugTypeMember carries no Parent operand: the
696 /// enclosing \c DebugTypeComposite references its members, not the reverse.
697 ///
698 /// \returns Emitted when the operands are ready. Returns the base's status
699 /// and builds nothing if \p M's type cannot be emitted.
700 EmitResult<PreparedScope> emitDebugTypeMember(const DIDerivedType *M,
701 MCRegister VoidTypeReg,
702 MCRegister I32TypeReg,
703 MCRegister ExtInstSetReg,
705
706 /// Build \c DebugTypeComposite for the struct, class, or union \p CT, after a
707 /// \c DebugTypeMember for each data member whose type can be emitted. A
708 /// forward declaration uses \c DebugInfoNone for Size and no members.
709 ///
710 /// \returns Emitted when the operands are ready. Builds nothing and returns
711 /// the parent's status if the Parent scope cannot be resolved, or
712 /// Unsupported if the size does not fit in 32 bits. Both are checked before
713 /// any member is streamed. A member whose type fails is dropped, whatever
714 /// the reason, and does not fail the composite.
715 EmitResult<PreparedScope>
716 emitDebugTypeComposite(const DICompositeType *CT, MCRegister VoidTypeReg,
717 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
719
720 /// Build \c DebugTypeEnum for the enumeration type \p ET. Operands: Name,
721 /// Underlying Type, Source, Line, Column, Parent, Size, Flags, then a Value
722 /// and Name pair per enumerator. Uses \c DebugInfoNone for Underlying Type
723 /// when \p ET has no base type, and drops an enumerator whose value does not
724 /// fit in a 32-bit integer.
725 ///
726 /// \returns An Emitted result when the operands are ready. An Unsupported
727 /// result, building nothing, if the size is 0 or does not fit in 32 bits.
728 /// If the base or Parent fail, it returns code for the one that failed.
729 EmitResult<PreparedScope> emitDebugTypeEnum(const DICompositeType *ET,
730 MCRegister VoidTypeReg,
731 MCRegister I32TypeReg,
732 MCRegister ExtInstSetReg,
734
735 /// Build \c DebugTypedef for the typedef derived type \p TD (a \c
736 /// DIDerivedType with \c DW_TAG_typedef). Operands: Name, Base Type, Source,
737 /// Line, Column, Parent. Parent is the enclosing type when \c TD->getScope()
738 /// is an emitted \c DIType, otherwise the first module \c
739 /// DebugCompilationUnit.
740 ///
741 /// \returns The base's or Parent's status if either fails.
742 EmitResult<PreparedScope> emitDebugTypedef(const DIDerivedType *TD,
743 MCRegister VoidTypeReg,
744 MCRegister I32TypeReg,
745 MCRegister ExtInstSetReg,
747
748 /// Map a subroutine type element to a \c DebugTypeFunction operand. A null
749 /// return type is void, so it maps to \p VoidTypeReg.
750 EmitResult<MCRegister> mapDISignatureTypeToReg(const DIType *Ty,
751 MCRegister VoidTypeReg,
752 bool ReturnType);
753
754 /// Map a DWARF source language code to a NonSemantic.Shader.DebugInfo.100
755 /// source language code.
756 static unsigned toNSDISrcLang(unsigned DwarfSrcLang);
757
758 /// Build a full path from debug \p Scope for OpString / DebugSource, matching
759 /// SPIRV-LLVM-Translator \c getFullPath (OCLUtil.h): \c DIScope::getFilename,
760 /// \c getDirectory, and \c sys::path::Style::native. Works for any \c DIScope
761 /// that carries file path fields (e.g. \c DIFile, \c DISubprogram,
762 /// \c DICompileUnit). Returns an empty path when \p Scope is null.
763 SmallString<128> getDebugFullPath(const DIScope *Scope) const;
764
765 /// Return an existing \c DebugSource id for file path \c OpString \p
766 /// FileStrReg or emit \c DebugSource and cache it (keyed by \p FileStrReg
767 /// id).
768 MCRegister getOrEmitDebugSourceForFileStrReg(MCRegister FileStrReg,
769 MCRegister VoidTypeReg,
770 MCRegister ExtInstSetReg,
772
773 /// Map \p Scope to the NonSemantic debug id used as a \c Parent operand.
774 ///
775 /// A \c DIType, \c DILexicalBlock, \c DINamespace, or \c DISubprogram scope
776 /// is created through \c getOrCreateDebugScope. When
777 /// \c UseLexicalBlockDiscriminatorScope is set, a
778 /// \c DILexicalBlockFile is also created this way, becoming a
779 /// \c DebugLexicalBlockDiscriminator; otherwise it is unwrapped to its
780 /// enclosing scope first. When \p Scope is null, a \c DIFile, or another
781 /// scope without a dedicated debug instruction, it falls back to
782 /// \p FallbackCU or the first module \c DebugCompilationUnit recorded in
783 /// \c DebugScopeRegs; no such compile unit is Unsupported.
784 EmitResult<MCRegister>
785 resolveScope(const DIScope *Scope, const DICompileUnit *FallbackCU = nullptr);
786
787 /// Build \c DebugLexicalBlock for \p S, which must be a \c DILexicalBlock or
788 /// a \c DINamespace. A \c DILexicalBlock supplies Line/Column
789 /// from \c getLine()/getColumn(); a \c DINamespace has neither, so both are
790 /// 0, and its Name is appended as an extra \c OpString operand.
791 ///
792 /// \returns Emitted when the operands are ready. If \c resolveScope cannot
793 /// emit \c S->getScope(), builds nothing and returns that status.
794 EmitResult<PreparedScope>
795 emitDebugLexicalBlock(const DIScope *S, MCRegister VoidTypeReg,
796 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
798
799 /// Build \c DebugLexicalBlockDiscriminator for \p LBF.
800 /// Operands are Source, Discriminator, and Parent (\c LBF->getScope()).
801 EmitResult<PreparedScope> emitDebugLexicalBlockDiscriminator(
802 const DILexicalBlockFile *LBF, MCRegister VoidTypeReg,
803 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
805
806 /// Return a cached \c DebugInlinedAt id for \p IA, or emit one (recursing
807 /// into \c IA->getInlinedAt() first for the optional Inlined operand, so
808 /// outer frames are always emitted before the inner frame that references
809 /// them). Must run after \c DebugScopeRegs is populated, since the Scope
810 /// operand is resolved through \c resolveScope. \c DebugInlinedAt is not in
811 /// the spec's in-block instruction list, so this is only ever called from
812 /// module-scope emission (\c generateGlobalDebugInfo), never from
813 /// per-instruction emission.
814 ///
815 /// \returns An invalid (default-constructed) \c MCRegister, and emits
816 /// nothing, if \p IA's Scope does not resolve.
817 MCRegister getOrEmitDebugInlinedAt(const DILocation *IA,
818 MCRegister VoidTypeReg,
819 MCRegister I32TypeReg,
820 MCRegister ExtInstSetReg,
822};
823
824} // namespace llvm
825
826#endif // LLVM_LIB_TARGET_SPIRV_SPIRVNONSEMANTICDEBUGHANDLER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
static Error unsupported(const char *Str, const Triple &T)
Definition MachO.cpp:79
BitTracker BT
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define T
static NVPTX::Scope resolveScope(NVPTX::Scope S, const NVPTXSubtarget *T)
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
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:93
Basic type, like 'int' or 'float'.
A lightweight wrapper around an expression operand.
DWARF expression.
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
Base class for types.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Representation of each machine instruction.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void endModule() override
Emit all sections that should come after the content.
void beginModule(Module *M) override
Collect compile-unit metadata from the module.
void emitNonSemanticGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &)
Output the module-scope NSDI built by generateModuleDebugInfo().
void emitNonSemanticDebugStrings(SPIRV::ModuleAnalysisInfo &)
Output the NSDI OpStrings built by generateModuleDebugInfo() into the debug section (section 7 of the...
void endFunctionImpl(const MachineFunction *MF) override
void beginFunctionImpl(const MachineFunction *MF) override
void prepareModuleOutput(const SPIRVSubtarget &ST, SPIRV::ModuleAnalysisInfo &MAI)
Add SPV_KHR_non_semantic_info extension and NonSemantic.Shader.DebugInfo.100 ext inst set entry to MA...
void generateModuleDebugInfo(SPIRV::ModuleAnalysisInfo &MAI)
Buffer the module-scope NSDI and add SPV_KHR_relaxed_extended_instruction to MAI if a forward referen...
void 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
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
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
LogicalResult failure(bool IsFailure=true)
Utility function to generate a LogicalResult.
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op