1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing Microsoft CodeView debug info.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
24 #include "llvm/CodeGen/DebugHandlerBase.h"
25 #include "llvm/DebugInfo/CodeView/CodeView.h"
26 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
27 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/Compiler.h"
35 #include <unordered_map>
49 class MachineFunction
;
51 /// Collects and handles line tables information in a CodeView format.
52 class LLVM_LIBRARY_VISIBILITY CodeViewDebug
: public DebugHandlerBase
{
55 /// Indicates that variable data is stored in memory relative to the
56 /// specified register.
59 /// Offset of variable data in memory.
62 /// Non-zero if this is a piece of an aggregate.
63 uint16_t IsSubfield
: 1;
65 /// Offset into aggregate.
66 uint16_t StructOffset
: 15;
68 /// Register containing the data or the register base of the memory
69 /// location containing the data.
72 uint64_t static toOpaqueValue(const LocalVarDef DR
) {
74 std::memcpy(&Val
, &DR
, sizeof(Val
));
78 LocalVarDef
static createFromOpaqueValue(uint64_t Val
) {
80 std::memcpy(&DR
, &Val
, sizeof(Val
));
85 static_assert(sizeof(uint64_t) == sizeof(LocalVarDef
), "");
89 BumpPtrAllocator Allocator
;
90 codeview::GlobalTypeTableBuilder TypeTable
;
92 /// Whether to emit type record hashes into .debug$H.
93 bool EmitDebugGlobalHashes
= false;
95 /// The codeview CPU type used by the translation unit.
96 codeview::CPUType TheCPU
;
98 static LocalVarDef
createDefRangeMem(uint16_t CVRegister
, int Offset
);
100 /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
101 struct LocalVariable
{
102 const DILocalVariable
*DIVar
= nullptr;
103 MapVector
<LocalVarDef
,
104 SmallVector
<std::pair
<const MCSymbol
*, const MCSymbol
*>, 1>>
106 bool UseReferenceType
= false;
109 struct CVGlobalVariable
{
110 const DIGlobalVariable
*DIGV
;
111 PointerUnion
<const GlobalVariable
*, const DIExpression
*> GVInfo
;
115 SmallVector
<LocalVariable
, 1> InlinedLocals
;
116 SmallVector
<const DILocation
*, 1> ChildSites
;
117 const DISubprogram
*Inlinee
= nullptr;
119 /// The ID of the inline site or function used with .cv_loc. Not a type
121 unsigned SiteFuncId
= 0;
124 // Combines information from DILexicalBlock and LexicalScope.
125 struct LexicalBlock
{
126 SmallVector
<LocalVariable
, 1> Locals
;
127 SmallVector
<CVGlobalVariable
, 1> Globals
;
128 SmallVector
<LexicalBlock
*, 1> Children
;
129 const MCSymbol
*Begin
;
134 // For each function, store a vector of labels to its instructions, as well as
135 // to the end of the function.
136 struct FunctionInfo
{
137 FunctionInfo() = default;
140 FunctionInfo(const FunctionInfo
&FI
) = delete;
142 /// Map from inlined call site to inlined instructions and child inlined
143 /// call sites. Listed in program order.
144 std::unordered_map
<const DILocation
*, InlineSite
> InlineSites
;
146 /// Ordered list of top-level inlined call sites.
147 SmallVector
<const DILocation
*, 1> ChildSites
;
149 SmallVector
<LocalVariable
, 1> Locals
;
150 SmallVector
<CVGlobalVariable
, 1> Globals
;
152 std::unordered_map
<const DILexicalBlockBase
*, LexicalBlock
> LexicalBlocks
;
154 // Lexical blocks containing local variables.
155 SmallVector
<LexicalBlock
*, 1> ChildBlocks
;
157 std::vector
<std::pair
<MCSymbol
*, MDNode
*>> Annotations
;
158 std::vector
<std::tuple
<const MCSymbol
*, const MCSymbol
*, const DIType
*>>
161 const MCSymbol
*Begin
= nullptr;
162 const MCSymbol
*End
= nullptr;
164 unsigned LastFileId
= 0;
166 /// Number of bytes allocated in the prologue for all local stack objects.
167 unsigned FrameSize
= 0;
169 /// Number of bytes of parameters on the stack.
170 unsigned ParamSize
= 0;
172 /// Number of bytes pushed to save CSRs.
173 unsigned CSRSize
= 0;
175 /// Adjustment to apply on x86 when using the VFRAME frame pointer.
176 int OffsetAdjustment
= 0;
178 /// Two-bit value indicating which register is the designated frame pointer
179 /// register for local variables. Included in S_FRAMEPROC.
180 codeview::EncodedFramePtrReg EncodedLocalFramePtrReg
=
181 codeview::EncodedFramePtrReg::None
;
183 /// Two-bit value indicating which register is the designated frame pointer
184 /// register for stack parameters. Included in S_FRAMEPROC.
185 codeview::EncodedFramePtrReg EncodedParamFramePtrReg
=
186 codeview::EncodedFramePtrReg::None
;
188 codeview::FrameProcedureOptions FrameProcOpts
;
190 bool HasStackRealignment
= false;
192 bool HaveLineInfo
= false;
194 FunctionInfo
*CurFn
= nullptr;
196 codeview::SourceLanguage CurrentSourceLanguage
=
197 codeview::SourceLanguage::Masm
;
199 // This map records the constant offset in DIExpression of the
200 // DIGlobalVariableExpression referencing the DIGlobalVariable.
201 DenseMap
<const DIGlobalVariable
*, uint64_t> CVGlobalVariableOffsets
;
203 // Map used to seperate variables according to the lexical scope they belong
204 // in. This is populated by recordLocalVariable() before
205 // collectLexicalBlocks() separates the variables between the FunctionInfo
206 // and LexicalBlocks.
207 DenseMap
<const LexicalScope
*, SmallVector
<LocalVariable
, 1>> ScopeVariables
;
209 // Map to separate global variables according to the lexical scope they
210 // belong in. A null local scope represents the global scope.
211 typedef SmallVector
<CVGlobalVariable
, 1> GlobalVariableList
;
212 DenseMap
<const DIScope
*, std::unique_ptr
<GlobalVariableList
> > ScopeGlobals
;
214 // Array of global variables which need to be emitted into a COMDAT section.
215 SmallVector
<CVGlobalVariable
, 1> ComdatVariables
;
217 // Array of non-COMDAT global variables.
218 SmallVector
<CVGlobalVariable
, 1> GlobalVariables
;
220 /// List of static const data members to be emitted as S_CONSTANTs.
221 SmallVector
<const DIDerivedType
*, 4> StaticConstMembers
;
223 /// The set of comdat .debug$S sections that we've seen so far. Each section
224 /// must start with a magic version number that must only be emitted once.
225 /// This set tracks which sections we've already opened.
226 DenseSet
<MCSectionCOFF
*> ComdatDebugSections
;
228 /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
229 /// of an emitted global value, is in a comdat COFF section, this will switch
230 /// to a new .debug$S section in that comdat. This method ensures that the
231 /// section starts with the magic version number on first use. If GVSym is
232 /// null, uses the main .debug$S section.
233 void switchToDebugSectionForSymbol(const MCSymbol
*GVSym
);
235 /// The next available function index for use with our .cv_* directives. Not
236 /// to be confused with type indices for LF_FUNC_ID records.
237 unsigned NextFuncId
= 0;
239 InlineSite
&getInlineSite(const DILocation
*InlinedAt
,
240 const DISubprogram
*Inlinee
);
242 codeview::TypeIndex
getFuncIdForSubprogram(const DISubprogram
*SP
);
244 void calculateRanges(LocalVariable
&Var
,
245 const DbgValueHistoryMap::Entries
&Entries
);
247 /// Remember some debug info about each function. Keep it in a stable order to
248 /// emit at the end of the TU.
249 MapVector
<const Function
*, std::unique_ptr
<FunctionInfo
>> FnDebugInfo
;
251 /// Map from full file path to .cv_file id. Full paths are built from DIFiles
252 /// and are stored in FileToFilepathMap;
253 DenseMap
<StringRef
, unsigned> FileIdMap
;
255 /// All inlined subprograms in the order they should be emitted.
256 SmallSetVector
<const DISubprogram
*, 4> InlinedSubprograms
;
258 /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
259 /// be nullptr, to CodeView type indices. Primarily indexed by
260 /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
262 /// The second entry in the key is needed for methods as DISubroutineType
263 /// representing static method type are shared with non-method function type.
264 DenseMap
<std::pair
<const DINode
*, const DIType
*>, codeview::TypeIndex
>
267 /// Map from DICompositeType* to complete type index. Non-record types are
268 /// always looked up in the normal TypeIndices map.
269 DenseMap
<const DICompositeType
*, codeview::TypeIndex
> CompleteTypeIndices
;
271 /// Complete record types to emit after all active type lowerings are
273 SmallVector
<const DICompositeType
*, 4> DeferredCompleteTypes
;
275 /// Number of type lowering frames active on the stack.
276 unsigned TypeEmissionLevel
= 0;
278 codeview::TypeIndex VBPType
;
280 const DISubprogram
*CurrentSubprogram
= nullptr;
282 // The UDTs we have seen while processing types; each entry is a pair of type
283 // index and type name.
284 std::vector
<std::pair
<std::string
, const DIType
*>> LocalUDTs
;
285 std::vector
<std::pair
<std::string
, const DIType
*>> GlobalUDTs
;
287 using FileToFilepathMapTy
= std::map
<const DIFile
*, std::string
>;
288 FileToFilepathMapTy FileToFilepathMap
;
290 StringRef
getFullFilepath(const DIFile
*File
);
292 unsigned maybeRecordFile(const DIFile
*F
);
294 void maybeRecordLocation(const DebugLoc
&DL
, const MachineFunction
*MF
);
298 void setCurrentSubprogram(const DISubprogram
*SP
) {
299 CurrentSubprogram
= SP
;
303 /// Emit the magic version number at the start of a CodeView type or symbol
304 /// section. Appears at the front of every .debug$S or .debug$T or .debug$P
306 void emitCodeViewMagicVersion();
308 void emitTypeInformation();
310 void emitTypeGlobalHashes();
314 void emitCompilerInformation();
316 void emitBuildInfo();
318 void emitInlineeLinesSubsection();
320 void emitDebugInfoForThunk(const Function
*GV
,
324 void emitDebugInfoForFunction(const Function
*GV
, FunctionInfo
&FI
);
326 void emitDebugInfoForRetainedTypes();
328 void emitDebugInfoForUDTs(
329 const std::vector
<std::pair
<std::string
, const DIType
*>> &UDTs
);
331 void collectDebugInfoForGlobals();
332 void emitDebugInfoForGlobals();
333 void emitGlobalVariableList(ArrayRef
<CVGlobalVariable
> Globals
);
334 void emitConstantSymbolRecord(const DIType
*DTy
, APSInt
&Value
,
335 const std::string
&QualifiedName
);
336 void emitDebugInfoForGlobal(const CVGlobalVariable
&CVGV
);
337 void emitStaticConstMemberList();
339 /// Opens a subsection of the given kind in a .debug$S codeview section.
340 /// Returns an end label for use with endCVSubsection when the subsection is
342 MCSymbol
*beginCVSubsection(codeview::DebugSubsectionKind Kind
);
343 void endCVSubsection(MCSymbol
*EndLabel
);
345 /// Opens a symbol record of the given kind. Returns an end label for use with
347 MCSymbol
*beginSymbolRecord(codeview::SymbolKind Kind
);
348 void endSymbolRecord(MCSymbol
*SymEnd
);
350 /// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records
351 /// are empty, so we emit them with a simpler assembly sequence that doesn't
353 void emitEndSymbolRecord(codeview::SymbolKind EndKind
);
355 void emitInlinedCallSite(const FunctionInfo
&FI
, const DILocation
*InlinedAt
,
356 const InlineSite
&Site
);
358 using InlinedEntity
= DbgValueHistoryMap::InlinedEntity
;
360 void collectGlobalVariableInfo();
361 void collectVariableInfo(const DISubprogram
*SP
);
363 void collectVariableInfoFromMFTable(DenseSet
<InlinedEntity
> &Processed
);
365 // Construct the lexical block tree for a routine, pruning emptpy lexical
366 // scopes, and populate it with local variables.
367 void collectLexicalBlockInfo(SmallVectorImpl
<LexicalScope
*> &Scopes
,
368 SmallVectorImpl
<LexicalBlock
*> &Blocks
,
369 SmallVectorImpl
<LocalVariable
> &Locals
,
370 SmallVectorImpl
<CVGlobalVariable
> &Globals
);
371 void collectLexicalBlockInfo(LexicalScope
&Scope
,
372 SmallVectorImpl
<LexicalBlock
*> &ParentBlocks
,
373 SmallVectorImpl
<LocalVariable
> &ParentLocals
,
374 SmallVectorImpl
<CVGlobalVariable
> &ParentGlobals
);
376 /// Records information about a local variable in the appropriate scope. In
377 /// particular, locals from inlined code live inside the inlining site.
378 void recordLocalVariable(LocalVariable
&&Var
, const LexicalScope
*LS
);
380 /// Emits local variables in the appropriate order.
381 void emitLocalVariableList(const FunctionInfo
&FI
,
382 ArrayRef
<LocalVariable
> Locals
);
384 /// Emits an S_LOCAL record and its associated defined ranges.
385 void emitLocalVariable(const FunctionInfo
&FI
, const LocalVariable
&Var
);
387 /// Emits a sequence of lexical block scopes and their children.
388 void emitLexicalBlockList(ArrayRef
<LexicalBlock
*> Blocks
,
389 const FunctionInfo
& FI
);
391 /// Emit a lexical block scope and its children.
392 void emitLexicalBlock(const LexicalBlock
&Block
, const FunctionInfo
& FI
);
394 /// Translates the DIType to codeview if necessary and returns a type index
396 codeview::TypeIndex
getTypeIndex(const DIType
*Ty
,
397 const DIType
*ClassTy
= nullptr);
400 getTypeIndexForThisPtr(const DIDerivedType
*PtrTy
,
401 const DISubroutineType
*SubroutineTy
);
403 codeview::TypeIndex
getTypeIndexForReferenceTo(const DIType
*Ty
);
405 codeview::TypeIndex
getMemberFunctionType(const DISubprogram
*SP
,
406 const DICompositeType
*Class
);
408 codeview::TypeIndex
getScopeIndex(const DIScope
*Scope
);
410 codeview::TypeIndex
getVBPTypeIndex();
412 void addToUDTs(const DIType
*Ty
);
414 void addUDTSrcLine(const DIType
*Ty
, codeview::TypeIndex TI
);
416 codeview::TypeIndex
lowerType(const DIType
*Ty
, const DIType
*ClassTy
);
417 codeview::TypeIndex
lowerTypeAlias(const DIDerivedType
*Ty
);
418 codeview::TypeIndex
lowerTypeArray(const DICompositeType
*Ty
);
419 codeview::TypeIndex
lowerTypeString(const DIStringType
*Ty
);
420 codeview::TypeIndex
lowerTypeBasic(const DIBasicType
*Ty
);
421 codeview::TypeIndex
lowerTypePointer(
422 const DIDerivedType
*Ty
,
423 codeview::PointerOptions PO
= codeview::PointerOptions::None
);
424 codeview::TypeIndex
lowerTypeMemberPointer(
425 const DIDerivedType
*Ty
,
426 codeview::PointerOptions PO
= codeview::PointerOptions::None
);
427 codeview::TypeIndex
lowerTypeModifier(const DIDerivedType
*Ty
);
428 codeview::TypeIndex
lowerTypeFunction(const DISubroutineType
*Ty
);
429 codeview::TypeIndex
lowerTypeVFTableShape(const DIDerivedType
*Ty
);
430 codeview::TypeIndex
lowerTypeMemberFunction(
431 const DISubroutineType
*Ty
, const DIType
*ClassTy
, int ThisAdjustment
,
433 codeview::FunctionOptions FO
= codeview::FunctionOptions::None
);
434 codeview::TypeIndex
lowerTypeEnum(const DICompositeType
*Ty
);
435 codeview::TypeIndex
lowerTypeClass(const DICompositeType
*Ty
);
436 codeview::TypeIndex
lowerTypeUnion(const DICompositeType
*Ty
);
438 /// Symbol records should point to complete types, but type records should
439 /// always point to incomplete types to avoid cycles in the type graph. Only
440 /// use this entry point when generating symbol records. The complete and
441 /// incomplete type indices only differ for record types. All other types use
443 codeview::TypeIndex
getCompleteTypeIndex(const DIType
*Ty
);
445 codeview::TypeIndex
lowerCompleteTypeClass(const DICompositeType
*Ty
);
446 codeview::TypeIndex
lowerCompleteTypeUnion(const DICompositeType
*Ty
);
448 struct TypeLoweringScope
;
450 void emitDeferredCompleteTypes();
452 void collectMemberInfo(ClassInfo
&Info
, const DIDerivedType
*DDTy
);
453 ClassInfo
collectClassInfo(const DICompositeType
*Ty
);
455 /// Common record member lowering functionality for record types, which are
456 /// structs, classes, and unions. Returns the field list index and the member
458 std::tuple
<codeview::TypeIndex
, codeview::TypeIndex
, unsigned, bool>
459 lowerRecordFieldList(const DICompositeType
*Ty
);
461 /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
462 codeview::TypeIndex
recordTypeIndexForDINode(const DINode
*Node
,
463 codeview::TypeIndex TI
,
464 const DIType
*ClassTy
= nullptr);
466 /// Collect the names of parent scopes, innermost to outermost. Return the
467 /// innermost subprogram scope if present. Ensure that parent type scopes are
468 /// inserted into the type table.
470 collectParentScopeNames(const DIScope
*Scope
,
471 SmallVectorImpl
<StringRef
> &ParentScopeNames
);
472 std::string
getFullyQualifiedName(const DIScope
*Scope
, StringRef Name
);
473 std::string
getFullyQualifiedName(const DIScope
*Scope
);
475 unsigned getPointerSizeInBytes();
478 /// Gather pre-function debug information.
479 void beginFunctionImpl(const MachineFunction
*MF
) override
;
481 /// Gather post-function debug information.
482 void endFunctionImpl(const MachineFunction
*) override
;
484 /// Check if the current module is in Fortran.
485 bool moduleIsInFortran() {
486 return CurrentSourceLanguage
== codeview::SourceLanguage::Fortran
;
490 CodeViewDebug(AsmPrinter
*AP
);
492 void beginModule(Module
*M
) override
;
494 void setSymbolSize(const MCSymbol
*, uint64_t) override
{}
496 /// Emit the COFF section that holds the line table information.
497 void endModule() override
;
499 /// Process beginning of an instruction.
500 void beginInstruction(const MachineInstr
*MI
) override
;
503 template <> struct DenseMapInfo
<CodeViewDebug::LocalVarDef
> {
505 static inline CodeViewDebug::LocalVarDef
getEmptyKey() {
506 return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL);
509 static inline CodeViewDebug::LocalVarDef
getTombstoneKey() {
510 return CodeViewDebug::LocalVarDef::createFromOpaqueValue(~0ULL - 1ULL);
513 static unsigned getHashValue(const CodeViewDebug::LocalVarDef
&DR
) {
514 return CodeViewDebug::LocalVarDef::toOpaqueValue(DR
) * 37ULL;
517 static bool isEqual(const CodeViewDebug::LocalVarDef
&LHS
,
518 const CodeViewDebug::LocalVarDef
&RHS
) {
519 return CodeViewDebug::LocalVarDef::toOpaqueValue(LHS
) ==
520 CodeViewDebug::LocalVarDef::toOpaqueValue(RHS
);
524 } // end namespace llvm
526 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H