LLVM 23.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"
26#include "llvm/ADT/StringMap.h"
29#include "llvm/MC/MCInst.h"
30#include "llvm/MC/MCRegister.h"
31#include <optional>
32
33namespace llvm {
34
35class SPIRVSubtarget;
36
37/// AsmPrinter handler that emits NonSemantic.Shader.DebugInfo.100 (NSDI)
38/// instructions for the SPIR-V backend. Registered with SPIRVAsmPrinter when
39/// the module contains debug info (llvm.dbg.cu).
40///
41/// Call sequence:
42/// beginModule() -- collect compile-unit metadata.
43/// prepareModuleOutput() -- add extension + ext inst set to MAI.
44/// emitNonSemanticDebugStrings() -- OpString for NSDI strings (sec. 7).
45/// emitNonSemanticGlobalDebugInfo() -- emit DebugSource,
46/// DebugCompilationUnit, DebugTypeBasic,
47/// DebugTypePointer, DebugTypeFunction.
48/// beginFunctionImpl() -- no-op (no per-function DI yet).
49/// endFunctionImpl() -- no-op.
51 struct CompileUnitInfo {
52 SmallString<128> FilePath;
53 unsigned SpirvSourceLanguage = 0; // NonSemantic.Shader.DebugInfo.100 source
54 // language code (section 4.3)
55 };
56 // TODO: When per-function NSDI emission is implemented, augment
57 // CompileUnitInfo with the originating DICompileUnit pointer so that
58 // Parent operands on DebugFunction and similar instructions can resolve
59 // the compile unit's result register.
61 int64_t DwarfVersion = 0;
62
63 // DI types partitioned from DebugInfoFinder.types() in beginModule()
64 // (basics, pointers, subroutine types NSDI v1 may emit).
68
69 // Filled in emitNonSemanticGlobalDebugInfo(): DI types to their result
70 // registers.
72
73 // Maps OpString contents to result id. Populated only by emitOpStringIfNew()
74 // during section 7; section 10 uses getCachedOpStringReg() (lookup only).
75 StringMap<MCRegister> OpStringContentCache;
76
77#ifndef NDEBUG // Only declare the variable for debugging purposes.
78 // True after emitNonSemanticDebugStrings() emitted the NSDI OpStrings for
79 // this module. SPIRVAsmPrinter calls that before
80 // emitNonSemanticGlobalDebugInfo().
81 bool NonSemanticOpStringsSectionEmitted = false;
82#endif
83
84 MCRegister CachedDebugInfoNoneReg;
85
86 MCRegister CachedOpTypeVoidReg;
87
88 MCRegister CachedOpTypeInt32Reg;
89
90 // Cache of already-emitted i32 constants, keyed by value. Prevents
91 // duplicate OpConstant instructions for the same integer value.
92 DenseMap<uint32_t, MCRegister> I32ConstantCache;
93
94 // Cache of already-emitted DebugTypeFunction instructions, keyed by operand
95 // ids (flags, return type, parameters).
96 DenseMap<SmallVector<MCRegister, 8>, MCRegister> DebugTypeFunctionCache;
97
98 // True once emitNonSemanticGlobalDebugInfo() has run. Both
99 // SPIRVAsmPrinter::emitFunctionHeader() and emitEndOfAsmFile() may call
100 // outputModuleSections(), each guarded by ModuleSectionsEmitted, so only
101 // one fires. This flag provides a secondary guard in case the call sites
102 // change.
103 bool GlobalDIEmitted = false;
104
105public:
107
108 /// Collect compile-unit metadata from the module. Called by
109 /// AsmPrinter::doInitialization() via the handler list. No emission.
110 void beginModule(Module *M) override;
111
112 /// Emit OpString instructions for all NSDI file paths and basic type names
113 /// into the debug section (section 7 of the SPIR-V module layout). Must be
114 /// called from SPIRVAsmPrinter::outputDebugSourceAndStrings(), after
115 /// prepareModuleOutput() has registered the ext inst set. Registers are
116 /// stored in OpStringContentCache; emitNonSemanticGlobalDebugInfo() resolves
117 /// them via getCachedOpStringReg().
119
120 /// Add SPV_KHR_non_semantic_info extension and
121 /// NonSemantic.Shader.DebugInfo.100 ext inst set entry to MAI. Must be called
122 /// before outputGlobalRequirements() and outputOpExtInstImports() in
123 /// SPIRVAsmPrinter::outputModuleSections().
124 void prepareModuleOutput(const SPIRVSubtarget &ST,
126
127 /// Emit module-scope NSDI instructions (DebugSource, DebugCompilationUnit,
128 /// DebugTypeBasic, DebugTypePointer, DebugTypeFunction). Called by
129 /// SPIRVAsmPrinter::outputModuleSections() at section 10 in place of
130 /// outputModuleSection(MB_NonSemanticGlobalDI). Requires
131 /// emitNonSemanticDebugStrings() to have run first when NSDI strings apply.
133
134protected:
135 // All module-level output is driven by emitNonSemanticGlobalDebugInfo(),
136 // called explicitly from SPIRVAsmPrinter::outputModuleSections(). Nothing
137 // needs to happen in the AsmPrinterHandler::endModule() callback.
138 void endModule() override {}
139
140 // DebugHandlerBase stores MMI as a pointer copy from Asm->MMI at construction
141 // time (DebugHandlerBase.cpp: `MMI(Asm->MMI)`). The handler is constructed
142 // before AsmPrinter::doInitialization() runs, so Asm->MMI is null at that
143 // point and MMI remains null for this handler's entire lifetime. The
144 // base-class beginInstruction/endInstruction dereference MMI to create temp
145 // symbols for label tracking and would crash. Override them as no-ops.
146 // When per-function NSDI is implemented, use Asm->OutStreamer->getContext()
147 // for MCContext access rather than MMI->getContext().
148 void beginInstruction(const MachineInstr *MI) override {}
149 void endInstruction() override {}
150
151 // TODO: Emit DebugFunction and DebugFunctionDefinition here once per-function
152 // NSDI emission is implemented. DebugHandlerBase::beginFunction() populates
153 // LScopes and DbgValues, which are needed for DebugLine emission. Do not
154 // override beginFunction() until that work is in place.
155 void beginFunctionImpl(const MachineFunction *MF) override {}
156 // TODO: Add per-function cleanup when DebugFunction emission is in place.
157 void endFunctionImpl(const MachineFunction *MF) override {}
158
159private:
160 void emitMCInst(MCInst &Inst);
161 MCRegister emitOpString(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
162
163 /// Section 7 only: emit OpString and cache it if not already present. Must
164 /// not be called after NonSemanticOpStringsSectionEmitted is set.
165 void emitOpStringIfNew(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
166
167 /// Section 10 only: lookup OpString id from cache; asserts if missing or if
168 /// section 7 did not complete.
169 MCRegister getCachedOpStringReg(StringRef S);
170 MCRegister emitOpConstantI32(uint32_t Value, MCRegister I32TypeReg,
172 MCRegister emitExtInst(SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
173 MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
174 ArrayRef<MCRegister> Operands,
176
177 /// Return a cached DebugTypeFunction id when \p Ops matches a prior emission,
178 /// otherwise emit and cache a new instruction.
179 MCRegister getOrEmitDebugTypeFunction(ArrayRef<MCRegister> Ops,
180 MCRegister VoidTypeReg,
181 MCRegister ExtInstSetReg,
183
184 /// Return OpTypeVoid id for this module (lazy lookup / emit, then cache).
185 MCRegister getOrEmitOpTypeVoidReg(SPIRV::ModuleAnalysisInfo &MAI);
186
187 /// Return OpTypeInt 32 0 id for this module (lazy lookup / emit, then cache).
188 MCRegister getOrEmitOpTypeInt32Reg(SPIRV::ModuleAnalysisInfo &MAI);
189
190 /// Find OpTypeVoid in the already-emitted TypeConstVars section, or emit one
191 /// if the module does not contain it (e.g. no void-returning functions).
192 MCRegister findOrEmitOpTypeVoid(SPIRV::ModuleAnalysisInfo &MAI);
193
194 /// Find OpTypeInt 32 0 in the already-emitted TypeConstVars section, or emit
195 /// one if the module does not contain it.
196 MCRegister findOrEmitOpTypeInt32(SPIRV::ModuleAnalysisInfo &MAI);
197
198 /// Emit \c DebugTypePointer for pointer metadata \p PT.
199 ///
200 /// \returns The result id register on success. Returns \c std::nullopt and
201 /// emits nothing if \p PT has no DWARF address space (needed to pick the
202 /// SPIR-V storage class), or if \p PT has a non-null base DI type that is not
203 /// yet in \c DebugTypeRegs (the pointee was not emitted as a debug type).
204 ///
205 /// Base Type operand: the register from \c DebugTypeRegs for \p PT's base
206 /// type when it is set and mapped; \c DebugInfoNone when there is no base
207 /// type (e.g. \c void * in IR), consistent with SPIRV-LLVM-Translator.
208 std::optional<MCRegister>
209 emitDebugTypePointer(const DIDerivedType *PT, MCRegister ExtInstSetReg,
211
212 /// Emit one DebugTypeFunction for ST when every DI operand maps to a debug
213 /// type id; otherwise emit nothing and return std::nullopt.
214 std::optional<MCRegister>
215 emitDebugTypeFunctionForSubroutineType(const DISubroutineType *ST,
216 MCRegister ExtInstSetReg,
218
219 /// Map a \c DISubroutineType::getTypeArray() element to an operand register
220 /// for
221 /// \c DebugTypeFunction. Non-null \p Ty resolves via \c DebugTypeRegs; if the
222 /// type was never emitted, returns \c std::nullopt.
223 ///
224 /// LLVM encodes a void return as a null first element (and may use null in
225 /// later slots). NonSemantic \c DebugTypeFunction
226 /// requires a concrete return-type operand, so when \p ReturnType is true and
227 /// \p Ty is null, this returns \p VoidTypeReg (\c OpTypeVoid). When
228 /// \p ReturnType is false and \p Ty is null, this returns
229 /// \c CachedDebugInfoNoneReg (\c DebugInfoNone).
230 std::optional<MCRegister> mapDISignatureTypeToReg(const DIType *Ty,
231 MCRegister VoidTypeReg,
232 bool ReturnType);
233
234 /// Map a DWARF source language code to a NonSemantic.Shader.DebugInfo.100
235 /// source language code.
236 static unsigned toNSDISrcLang(unsigned DwarfSrcLang);
237};
238
239} // namespace llvm
240
241#endif // LLVM_LIB_TARGET_SPIRV_SPIRVNONSEMANTICDEBUGHANDLER_H
This file defines the StringMap class.
This file defines the DenseMap class.
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
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:91
Type array for a subprogram.
Base class for types.
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
Representation of each machine instruction.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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 beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void beginFunctionImpl(const MachineFunction *MF) override
void endFunctionImpl(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.
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:133
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.