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
21#include "MCTargetDesc/SPIRVBaseInfo.h"
22#include "SPIRVModuleAnalysis.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/CodeGen/DebugHandlerBase.h"
28#include "llvm/IR/DebugInfoMetadata.h"
29#include "llvm/MC/MCInst.h"
30#include "llvm/MC/MCRegister.h"
31#include <optional>
32
33namespace llvm {
34
35class GlobalVariable;
36class SPIRVSubtarget;
37
38/// AsmPrinter handler that emits NonSemantic.Shader.DebugInfo.100 (NSDI)
39/// instructions for the SPIR-V backend. Registered with SPIRVAsmPrinter when
40/// the module contains debug info (llvm.dbg.cu).
41///
42/// Call sequence:
43/// beginModule() -- collect compile-unit metadata.
44/// prepareModuleOutput() -- add extension + ext inst set to MAI.
45/// emitNonSemanticDebugStrings() -- OpString for NSDI strings (sec. 7).
46/// emitNonSemanticGlobalDebugInfo() -- emit DebugSource,
47/// DebugCompilationUnit, DebugTypeBasic,
48/// DebugTypePointer, DebugTypeFunction,
49/// DebugFunctionDeclaration.
50/// beginFunctionImpl() -- no-op (no per-function DI yet).
51/// endFunctionImpl() -- no-op.
52class SPIRVNonSemanticDebugHandler : public DebugHandlerBase {
53 struct CompileUnitInfo {
54 const DICompileUnit *TheCU = nullptr;
55 SmallString<128> FilePath;
56 unsigned SpirvSourceLanguage = 0; // NonSemantic.Shader.DebugInfo.100 source
57 // language code (section 4.3)
58 };
59 SmallVector<CompileUnitInfo> CompileUnits;
60 int64_t DwarfVersion = 0;
61
62 // DI types partitioned from DebugInfoFinder.types() in beginModule()
63 // (basics, pointers, vectors, subroutine types NSDI v1 may emit).
64 SmallVector<const DIBasicType *> BasicTypes;
65 SmallVector<const DIDerivedType *> PointerTypes;
66 SmallVector<const DISubroutineType *> SubroutineTypes;
67 // DICompositeType nodes with DW_TAG_array_type and DINode::FlagVector,
68 // partitioned from DebugInfoFinder.types() in beginModule().
69 SmallVector<const DICompositeType *> VectorTypes;
70
71 // Filled in emitNonSemanticGlobalDebugInfo(): DI types to their result
72 // registers.
73 DenseMap<const DIType *, MCRegister> DebugTypeRegs;
74
75 // DISubprogram nodes that are declarations only (!isDefinition()), collected
76 // in beginModule() for DebugFunctionDeclaration emission.
77 SmallVector<const DISubprogram *> SubprogramDeclarations;
78
79 struct GlobalVariableDebugInfo {
80 const DIExpression *Expr = nullptr;
81 const GlobalVariable *LLVMGV = nullptr;
82 };
83 DenseMap<const DIGlobalVariable *, GlobalVariableDebugInfo>
84 GlobalVariableDebugInfoMap;
85
86 // DebugFunctionDeclaration result id per emitted declaration DISubprogram
87 // (only entries where emission succeeded).
88 DenseMap<const DISubprogram *, MCRegister> DebugFunctionDeclarationRegs;
89
90 // Path \c OpString result id per \c DIScope (CU, \c DIFile, declaration
91 // \c DISubprogram, …). Filled during \c emitNonSemanticDebugStrings() using
92 // \c getDebugFullPath + \c emitOpStringIfNew; section 10 uses it for
93 // \c DebugSource without recomputing path text.
94 DenseMap<const DIScope *, MCRegister> ScopeToPathOpStringReg;
95
96 // DebugCompilationUnit result id per DICompileUnit (for Parent operands).
97 DenseMap<const DICompileUnit *, MCRegister> CUToCompilationUnitDbgReg;
98
99 // DebugSource result id keyed by path \c OpString id (\c MCRegister::id()),
100 // deduplicating when the same file string is reused.
101 DenseMap<unsigned, MCRegister> DebugSourceRegByFileStr;
102
103 // Maps OpString contents to result id. Populated only by emitOpStringIfNew()
104 // during section 7; section 10 uses getCachedOpStringReg() (lookup only).
105 StringMap<MCRegister> OpStringContentCache;
106
107#ifndef NDEBUG // Only declare the variable for debugging purposes.
108 // True after emitNonSemanticDebugStrings() emitted the NSDI OpStrings for
109 // this module. SPIRVAsmPrinter calls that before
110 // emitNonSemanticGlobalDebugInfo().
111 bool NonSemanticOpStringsSectionEmitted = false;
112#endif
113
114 MCRegister CachedEmptyStringReg;
115
116 MCRegister CachedDebugInfoNoneReg;
117
118 MCRegister CachedOpTypeVoidReg;
119
120 MCRegister CachedOpTypeInt32Reg;
121
122 // Cache of already-emitted i32 constants, keyed by value. Prevents
123 // duplicate OpConstant instructions for the same integer value.
124 DenseMap<uint32_t, MCRegister> I32ConstantCache;
125
126 // Cache of already-emitted DebugTypeFunction instructions, keyed by operand
127 // ids (flags, return type, parameters).
128 DenseMap<SmallVector<MCRegister, 8>, MCRegister> DebugTypeFunctionCache;
129
130 // True once emitNonSemanticGlobalDebugInfo() has run. Both
131 // SPIRVAsmPrinter::emitFunctionHeader() and emitEndOfAsmFile() may call
132 // outputModuleSections(), each guarded by ModuleSectionsEmitted, so only
133 // one fires. This flag provides a secondary guard in case the call sites
134 // change.
135 bool GlobalDIEmitted = false;
136
137public:
138 explicit SPIRVNonSemanticDebugHandler(AsmPrinter &AP);
139
140 /// Collect compile-unit metadata from the module. Called by
141 /// AsmPrinter::doInitialization() via the handler list. No emission.
142 void beginModule(Module *M) override;
143
144 /// Emit OpString instructions for all NSDI file paths and basic type names
145 /// into the debug section (section 7 of the SPIR-V module layout). Must be
146 /// called from SPIRVAsmPrinter::outputDebugSourceAndStrings(), after
147 /// prepareModuleOutput() has registered the ext inst set. Registers are
148 /// stored in \c OpStringContentCache and \c ScopeToPathOpStringReg;
149 /// \c emitNonSemanticGlobalDebugInfo() resolves them via
150 /// \c getCachedOpStringReg() and path maps.
151 void emitNonSemanticDebugStrings(SPIRV::ModuleAnalysisInfo &MAI);
152
153 /// Add SPV_KHR_non_semantic_info extension and
154 /// NonSemantic.Shader.DebugInfo.100 ext inst set entry to MAI. Must be called
155 /// before outputGlobalRequirements() and outputOpExtInstImports() in
156 /// SPIRVAsmPrinter::outputModuleSections().
157 void prepareModuleOutput(const SPIRVSubtarget &ST,
158 SPIRV::ModuleAnalysisInfo &MAI);
159
160 /// Emit module-scope NSDI instructions (DebugSource, DebugCompilationUnit,
161 /// DebugTypeBasic, DebugTypePointer, DebugTypeFunction,
162 /// DebugFunctionDeclaration). Called by
163 /// SPIRVAsmPrinter::outputModuleSections() at section 10 in place of
164 /// outputModuleSection(MB_NonSemanticGlobalDI). Requires
165 /// emitNonSemanticDebugStrings() to have run first when NSDI strings apply.
166 void emitNonSemanticGlobalDebugInfo(SPIRV::ModuleAnalysisInfo &MAI);
167
168protected:
169 // All module-level output is driven by emitNonSemanticGlobalDebugInfo(),
170 // called explicitly from SPIRVAsmPrinter::outputModuleSections(). Nothing
171 // needs to happen in the AsmPrinterHandler::endModule() callback.
172 void endModule() override {}
173
174 // DebugHandlerBase stores MMI as a pointer copy from Asm->MMI at construction
175 // time (DebugHandlerBase.cpp: `MMI(Asm->MMI)`). The handler is constructed
176 // before AsmPrinter::doInitialization() runs, so Asm->MMI is null at that
177 // point and MMI remains null for this handler's entire lifetime. The
178 // base-class beginInstruction/endInstruction dereference MMI to create temp
179 // symbols for label tracking and would crash. Override them as no-ops.
180 // When per-function NSDI is implemented, use Asm->OutStreamer->getContext()
181 // for MCContext access rather than MMI->getContext().
182 void beginInstruction(const MachineInstr *MI) override {}
183 void endInstruction() override {}
184
185 // TODO: Emit DebugFunction and DebugFunctionDefinition here once per-function
186 // NSDI emission is implemented. DebugHandlerBase::beginFunction() populates
187 // LScopes and DbgValues, which are needed for DebugLine emission. Do not
188 // override beginFunction() until that work is in place.
189 void beginFunctionImpl(const MachineFunction *MF) override {}
190 // TODO: Add per-function cleanup when DebugFunction emission is in place.
191 void endFunctionImpl(const MachineFunction *MF) override {}
192
193private:
194 void emitMCInst(MCInst &Inst);
195 MCRegister emitOpString(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
196
197 /// Section 7 only: emit OpString and cache it if not already present. Must
198 /// not be called after NonSemanticOpStringsSectionEmitted is set. Returns
199 /// the path (or string) \c OpString result id.
200 MCRegister emitOpStringIfNew(StringRef S, SPIRV::ModuleAnalysisInfo &MAI);
201
202 /// Section 10 only: lookup OpString id from cache; asserts if missing or if
203 /// section 7 did not complete.
204 MCRegister getCachedOpStringReg(StringRef S);
205
206 /// Section 10 only: lookup path \c OpString id for \p Scope from
207 /// \c ScopeToPathOpStringReg; asserts if missing or invalid. When
208 /// \p UseEmptyPathIfNullScope is true and \p Scope is null, returns
209 /// \c CachedEmptyStringReg instead.
210 MCRegister
211 getCachedScopePathOpStringReg(const DIScope *Scope,
212 bool UseEmptyPathIfNullScope = false);
213 MCRegister emitOpConstantI32(uint32_t Value, MCRegister I32TypeReg,
214 SPIRV::ModuleAnalysisInfo &MAI);
215 MCRegister emitExtInst(SPIRV::NonSemanticExtInst::NonSemanticExtInst Opcode,
216 MCRegister VoidTypeReg, MCRegister ExtInstSetReg,
217 ArrayRef<MCRegister> Operands,
218 SPIRV::ModuleAnalysisInfo &MAI);
219
220 /// Return a cached DebugTypeFunction id when \p Ops matches a prior emission,
221 /// otherwise emit and cache a new instruction.
222 MCRegister getOrEmitDebugTypeFunction(ArrayRef<MCRegister> Ops,
223 MCRegister VoidTypeReg,
224 MCRegister ExtInstSetReg,
225 SPIRV::ModuleAnalysisInfo &MAI);
226
227 /// Return OpTypeVoid id for this module (lazy lookup / emit, then cache).
228 MCRegister getOrEmitOpTypeVoidReg(SPIRV::ModuleAnalysisInfo &MAI);
229
230 /// Return OpTypeInt 32 0 id for this module (lazy lookup / emit, then cache).
231 MCRegister getOrEmitOpTypeInt32Reg(SPIRV::ModuleAnalysisInfo &MAI);
232
233 /// Find OpTypeVoid in the already-emitted TypeConstVars section, or emit one
234 /// if the module does not contain it (e.g. no void-returning functions).
235 MCRegister findOrEmitOpTypeVoid(SPIRV::ModuleAnalysisInfo &MAI);
236
237 /// Find OpTypeInt 32 0 in the already-emitted TypeConstVars section, or emit
238 /// one if the module does not contain it.
239 MCRegister findOrEmitOpTypeInt32(SPIRV::ModuleAnalysisInfo &MAI);
240
241 /// Emit \c DebugTypePointer for pointer metadata \p PT.
242 ///
243 /// \returns The result id register on success. Returns \c std::nullopt and
244 /// emits nothing if \p PT has no DWARF address space (needed to pick the
245 /// SPIR-V storage class), or if \p PT has a non-null base DI type that is not
246 /// yet in \c DebugTypeRegs (the pointee was not emitted as a debug type).
247 ///
248 /// Base Type operand: the register from \c DebugTypeRegs for \p PT's base
249 /// type when it is set and mapped; \c DebugInfoNone when there is no base
250 /// type (e.g. \c void * in IR), consistent with SPIRV-LLVM-Translator.
251 std::optional<MCRegister>
252 emitDebugTypePointer(const DIDerivedType *PT, MCRegister ExtInstSetReg,
253 SPIRV::ModuleAnalysisInfo &MAI);
254
255 /// Emit one DebugTypeFunction for ST when every DI operand maps to a debug
256 /// type id; otherwise emit nothing and return std::nullopt.
257 std::optional<MCRegister>
258 emitDebugTypeFunctionForSubroutineType(const DISubroutineType *ST,
259 MCRegister ExtInstSetReg,
260 SPIRV::ModuleAnalysisInfo &MAI);
261
262 /// Emit \c DebugFunctionDeclaration for a \c DISubprogram that is not a
263 /// definition (\p SP must satisfy \c !isDefinition()).
264 ///
265 /// \returns The result id register on success. Returns \c std::nullopt and
266 /// emits nothing if \p SP is null, is a definition, has no \c
267 /// DISubroutineType type, the signature type was not emitted in \c
268 /// DebugTypeRegs, no path
269 /// \c OpString was recorded for \p SP in section 7, or
270 /// \c resolveDebugFunctionDeclarationParent returns no id for the \c Parent
271 /// operand.
272 std::optional<MCRegister>
273 emitDebugFunctionDeclaration(const DISubprogram *SP, MCRegister VoidTypeReg,
274 MCRegister I32TypeReg, MCRegister ExtInstSetReg,
275 SPIRV::ModuleAnalysisInfo &MAI);
276
277 /// Emit \c DebugGlobalVariable for the source global variable \p GV.
278 ///
279 /// (\c SPIRVDebug::Operand::GlobalVariable): Name, Type, Source, Line,
280 /// Column, Parent, Linkage Name, Variable, Flags, and an optional Static
281 /// Member Declaration. Line, Column, and Flags are emitted as \c OpConstant
282 /// ids as required for non-semantic debug info.
283 ///
284 /// \c DebugInfoNone is used for two operands when LLVM has no value to
285 /// supply:
286 /// \c Type when \p GV is a declaration with no DI type (e.g. \c extern void;
287 /// valid IR, \c isDefinition: false); \c Variable when no \c
288 /// llvm::GlobalVariable in this module carries \p GV in its \c !dbg metadata.
289 ///
290 /// \returns The result id register on success. Returns \c std::nullopt and
291 /// emits nothing if a non-null \p GV type was not emitted in \c
292 /// DebugTypeRegs, or \p GV has a static data member declaration that was not
293 /// emitted in \c DebugTypeRegs.
294 std::optional<MCRegister> emitDebugGlobalVariable(
295 const DIGlobalVariable *GV, const GlobalVariableDebugInfo &Info,
296 MCRegister VoidTypeReg, MCRegister I32TypeReg, MCRegister ExtInstSetReg,
297 SPIRV::ModuleAnalysisInfo &MAI);
298
299 /// Resolve the \c Parent operand for \c DebugGlobalVariable.
300 MCRegister resolveGlobalVariableParent(const DIGlobalVariable *GV) const;
301
302 /// Emit \c DebugExpression for \p Expr. Unimplemented: defined as a no-op
303 /// (\returns \c std::nullopt, emits nothing) so \c emitDebugGlobalVariable
304 /// can complete Variable-operand resolution for the opcodes we support today.
305 std::optional<MCRegister> emitDebugExpression(const DIExpression *Expr,
306 MCRegister VoidTypeReg,
307 MCRegister ExtInstSetReg,
308 SPIRV::ModuleAnalysisInfo &MAI);
309
310 /// Emit \c DebugTypeVector for the vector composite type \p VT.
311 ///
312 /// \returns The result id register on success. Returns \c std::nullopt and
313 /// emits nothing if \p VT has no \c DIBasicType base type, if the base type
314 /// has not been emitted yet, if \p VT has more than one \c DISubrange
315 /// element, or if the component count is not a compile-time constant.
316 std::optional<MCRegister> emitDebugTypeVector(const DICompositeType *VT,
317 MCRegister ExtInstSetReg,
318 SPIRV::ModuleAnalysisInfo &MAI);
319
320 /// Map a \c DISubroutineType::getTypeArray() element to an operand register
321 /// for
322 /// \c DebugTypeFunction. Non-null \p Ty resolves via \c DebugTypeRegs; if the
323 /// type was never emitted, returns \c std::nullopt.
324 ///
325 /// LLVM encodes a void return as a null first element (and may use null in
326 /// later slots). NonSemantic \c DebugTypeFunction
327 /// requires a concrete return-type operand, so when \p ReturnType is true and
328 /// \p Ty is null, this returns \p VoidTypeReg (\c OpTypeVoid). When
329 /// \p ReturnType is false and \p Ty is null, this returns
330 /// \c CachedDebugInfoNoneReg (\c DebugInfoNone).
331 std::optional<MCRegister> mapDISignatureTypeToReg(const DIType *Ty,
332 MCRegister VoidTypeReg,
333 bool ReturnType);
334
335 /// Map a DWARF source language code to a NonSemantic.Shader.DebugInfo.100
336 /// source language code.
337 static unsigned toNSDISrcLang(unsigned DwarfSrcLang);
338
339 /// Build a full path from debug \p Scope for OpString / DebugSource, matching
340 /// SPIRV-LLVM-Translator \c getFullPath (OCLUtil.h): \c DIScope::getFilename,
341 /// \c getDirectory, and \c sys::path::Style::native. Works for any \c DIScope
342 /// that carries file path fields (e.g. \c DIFile, \c DISubprogram,
343 /// \c DICompileUnit). Returns an empty path when \p Scope is null.
344 SmallString<128> getDebugFullPath(const DIScope *Scope) const;
345
346 /// Return an existing \c DebugSource id for file path \c OpString \p
347 /// FileStrReg or emit \c DebugSource and cache it (keyed by \p FileStrReg
348 /// id).
349 MCRegister getOrEmitDebugSourceForFileStrReg(MCRegister FileStrReg,
350 MCRegister VoidTypeReg,
351 MCRegister ExtInstSetReg,
352 SPIRV::ModuleAnalysisInfo &MAI);
353
354 /// Resolve the \c Parent operand for \c DebugFunctionDeclaration: an emitted
355 /// debug type id when \c SP->getScope() is a \c DIType in \c DebugTypeRegs,
356 /// otherwise \c DebugCompilationUnit for \c SP->getUnit() (or the first
357 /// module CU when \c unit: is absent).
358 /// \returns \c std::nullopt when the scope requires a parent we cannot supply
359 /// (non-file scope that is not a mapped \c DIType) or the CU has no emitted
360 /// id.
361 std::optional<MCRegister>
362 resolveDebugFunctionDeclarationParent(const DISubprogram *SP) const;
363};
364
365} // namespace llvm
366
367#endif // LLVM_LIB_TARGET_SPIRV_SPIRVNONSEMANTICDEBUGHANDLER_H
368