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