LLVM 22.0.0git
CodeViewDebug.h
Go to the documentation of this file.
1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing Microsoft CodeView debug info.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
15
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
31#include "llvm/IR/DebugLoc.h"
34#include <cstdint>
35#include <map>
36#include <string>
37#include <tuple>
38#include <unordered_map>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44struct ClassInfo;
45class StringRef;
46class AsmPrinter;
47class Function;
48class GlobalVariable;
49class MCSectionCOFF;
50class MCStreamer;
51class MCSymbol;
52class MachineFunction;
53
54/// Collects and handles line tables information in a CodeView format.
56public:
57 struct LocalVarDef {
58 /// Indicates that variable data is stored in memory relative to the
59 /// specified register.
60 int InMemory : 1;
61
62 /// Offset of variable data in memory.
63 int DataOffset : 31;
64
65 /// Non-zero if this is a piece of an aggregate.
67
68 /// Offset into aggregate.
70
71 /// Register containing the data or the register base of the memory
72 /// location containing the data.
74
76 uint64_t Val = 0;
77 std::memcpy(&Val, &DR, sizeof(Val));
78 return Val;
79 }
80
82 LocalVarDef DR;
83 std::memcpy(&DR, &Val, sizeof(Val));
84 return DR;
85 }
86 };
87
88 static_assert(sizeof(uint64_t) == sizeof(LocalVarDef));
89
90private:
91 MCStreamer &OS;
94
95 /// Whether to emit type record hashes into .debug$H.
96 bool EmitDebugGlobalHashes = false;
97
98 /// The codeview CPU type used by the translation unit.
99 codeview::CPUType TheCPU;
100
101 const DICompileUnit *TheCU = nullptr;
102
103 /// The AsmPrinter used for emitting compiler metadata. When only compiler
104 /// info is being emitted, DebugHandlerBase::Asm may be null.
105 AsmPrinter *CompilerInfoAsm = nullptr;
106
107 static LocalVarDef createDefRangeMem(uint16_t CVRegister, int Offset);
108
109 /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
110 struct LocalVariable {
111 const DILocalVariable *DIVar = nullptr;
112 MapVector<LocalVarDef,
114 DefRanges;
115 bool UseReferenceType = false;
116 std::optional<APSInt> ConstantValue;
117 };
118
119 struct CVGlobalVariable {
120 const DIGlobalVariable *DIGV;
121 PointerUnion<const GlobalVariable *, const DIExpression *> GVInfo;
122 };
123
124 struct InlineSite {
125 SmallVector<LocalVariable, 1> InlinedLocals;
126 SmallVector<const DILocation *, 1> ChildSites;
127 const DISubprogram *Inlinee = nullptr;
128
129 /// The ID of the inline site or function used with .cv_loc. Not a type
130 /// index.
131 unsigned SiteFuncId = 0;
132 };
133
134 // Combines information from DILexicalBlock and LexicalScope.
135 struct LexicalBlock {
136 SmallVector<LocalVariable, 1> Locals;
137 SmallVector<CVGlobalVariable, 1> Globals;
138 SmallVector<LexicalBlock *, 1> Children;
139 const MCSymbol *Begin;
140 const MCSymbol *End;
141 StringRef Name;
142 };
143
144 struct JumpTableInfo {
145 codeview::JumpTableEntrySize EntrySize;
146 const MCSymbol *Base;
147 uint64_t BaseOffset;
148 const MCSymbol *Branch;
149 const MCSymbol *Table;
150 size_t TableSize;
151 std::vector<const MCSymbol *> Cases;
152 };
153
154 // For each function, store a vector of labels to its instructions, as well as
155 // to the end of the function.
156 struct FunctionInfo {
157 FunctionInfo() = default;
158
159 // Uncopyable.
160 FunctionInfo(const FunctionInfo &FI) = delete;
161
162 /// Map from inlined call site to inlined instructions and child inlined
163 /// call sites. Listed in program order.
164 std::unordered_map<const DILocation *, InlineSite> InlineSites;
165
166 /// Ordered list of top-level inlined call sites.
167 SmallVector<const DILocation *, 1> ChildSites;
168
169 /// Set of all functions directly inlined into this one.
170 SmallSet<codeview::TypeIndex, 1> Inlinees;
171
172 SmallVector<LocalVariable, 1> Locals;
173 SmallVector<CVGlobalVariable, 1> Globals;
174
175 std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks;
176
177 // Lexical blocks containing local variables.
178 SmallVector<LexicalBlock *, 1> ChildBlocks;
179
180 std::vector<std::pair<MCSymbol *, MDNode *>> Annotations;
181 std::vector<std::tuple<const MCSymbol *, const MCSymbol *, const DIType *>>
182 HeapAllocSites;
183
184 std::vector<JumpTableInfo> JumpTables;
185
186 const MCSymbol *Begin = nullptr;
187 const MCSymbol *End = nullptr;
188 unsigned FuncId = 0;
189 unsigned LastFileId = 0;
190
191 /// Number of bytes allocated in the prologue for all local stack objects.
192 unsigned FrameSize = 0;
193
194 /// Number of bytes of parameters on the stack.
195 unsigned ParamSize = 0;
196
197 /// Number of bytes pushed to save CSRs.
198 unsigned CSRSize = 0;
199
200 /// Adjustment to apply on x86 when using the VFRAME frame pointer.
201 int OffsetAdjustment = 0;
202
203 /// Two-bit value indicating which register is the designated frame pointer
204 /// register for local variables. Included in S_FRAMEPROC.
205 codeview::EncodedFramePtrReg EncodedLocalFramePtrReg =
206 codeview::EncodedFramePtrReg::None;
207
208 /// Two-bit value indicating which register is the designated frame pointer
209 /// register for stack parameters. Included in S_FRAMEPROC.
210 codeview::EncodedFramePtrReg EncodedParamFramePtrReg =
211 codeview::EncodedFramePtrReg::None;
212
213 codeview::FrameProcedureOptions FrameProcOpts;
214
215 bool HasStackRealignment = false;
216
217 bool HaveLineInfo = false;
218
219 bool HasFramePointer = false;
220 };
221 FunctionInfo *CurFn = nullptr;
222
223 codeview::SourceLanguage CurrentSourceLanguage =
224 codeview::SourceLanguage::Masm;
225
226 // This map records the constant offset in DIExpression of the
227 // DIGlobalVariableExpression referencing the DIGlobalVariable.
228 DenseMap<const DIGlobalVariable *, uint64_t> CVGlobalVariableOffsets;
229
230 // Map used to separate variables according to the lexical scope they belong
231 // in. This is populated by recordLocalVariable() before
232 // collectLexicalBlocks() separates the variables between the FunctionInfo
233 // and LexicalBlocks.
234 DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables;
235
236 // Map to separate global variables according to the lexical scope they
237 // belong in. A null local scope represents the global scope.
238 typedef SmallVector<CVGlobalVariable, 1> GlobalVariableList;
239 DenseMap<const DIScope*, std::unique_ptr<GlobalVariableList> > ScopeGlobals;
240
241 // Array of global variables which need to be emitted into a COMDAT section.
242 SmallVector<CVGlobalVariable, 1> ComdatVariables;
243
244 // Array of non-COMDAT global variables.
245 SmallVector<CVGlobalVariable, 1> GlobalVariables;
246
247 /// List of static const data members to be emitted as S_CONSTANTs.
248 SmallVector<const DIDerivedType *, 4> StaticConstMembers;
249
250 /// The set of comdat .debug$S sections that we've seen so far. Each section
251 /// must start with a magic version number that must only be emitted once.
252 /// This set tracks which sections we've already opened.
253 DenseSet<MCSectionCOFF *> ComdatDebugSections;
254
255 /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
256 /// of an emitted global value, is in a comdat COFF section, this will switch
257 /// to a new .debug$S section in that comdat. This method ensures that the
258 /// section starts with the magic version number on first use. If GVSym is
259 /// null, uses the main .debug$S section.
260 void switchToDebugSectionForSymbol(const MCSymbol *GVSym);
261
262 /// The next available function index for use with our .cv_* directives. Not
263 /// to be confused with type indices for LF_FUNC_ID records.
264 unsigned NextFuncId = 0;
265
266 InlineSite &getInlineSite(const DILocation *InlinedAt,
267 const DISubprogram *Inlinee);
268
269 codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);
270
271 void calculateRanges(LocalVariable &Var,
272 const DbgValueHistoryMap::Entries &Entries);
273
274 /// Remember some debug info about each function. Keep it in a stable order to
275 /// emit at the end of the TU.
276 MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo;
277
278 /// Map from full file path to .cv_file id. Full paths are built from DIFiles
279 /// and are stored in FileToFilepathMap;
280 DenseMap<StringRef, unsigned> FileIdMap;
281
282 /// All inlined subprograms in the order they should be emitted.
283 SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;
284
285 /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
286 /// be nullptr, to CodeView type indices. Primarily indexed by
287 /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
288 ///
289 /// The second entry in the key is needed for methods as DISubroutineType
290 /// representing static method type are shared with non-method function type.
291 DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>
292 TypeIndices;
293
294 /// Map from DICompositeType* to complete type index. Non-record types are
295 /// always looked up in the normal TypeIndices map.
296 DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;
297
298 /// Complete record types to emit after all active type lowerings are
299 /// finished.
300 SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;
301
302 /// Number of type lowering frames active on the stack.
303 unsigned TypeEmissionLevel = 0;
304
305 codeview::TypeIndex VBPType;
306
307 const DISubprogram *CurrentSubprogram = nullptr;
308
309 // The UDTs we have seen while processing types; each entry is a pair of type
310 // index and type name.
311 std::vector<std::pair<std::string, const DIType *>> LocalUDTs;
312 std::vector<std::pair<std::string, const DIType *>> GlobalUDTs;
313
314 using FileToFilepathMapTy = std::map<const DIFile *, std::string>;
315 FileToFilepathMapTy FileToFilepathMap;
316
317 StringRef getFullFilepath(const DIFile *File);
318
319 unsigned maybeRecordFile(const DIFile *F);
320
321 void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);
322
323 void clear();
324
325 void setCurrentSubprogram(const DISubprogram *SP) {
326 CurrentSubprogram = SP;
327 LocalUDTs.clear();
328 }
329
330 /// Emit the magic version number at the start of a CodeView type or symbol
331 /// section. Appears at the front of every .debug$S or .debug$T or .debug$P
332 /// section.
333 void emitCodeViewMagicVersion();
334
335 void emitTypeInformation();
336
337 void emitTypeGlobalHashes();
338
339 void emitObjName();
340
341 void emitCompilerInformation();
342
343 void emitSecureHotPatchInformation();
344
345 void emitBuildInfo();
346
347 void emitInlineeLinesSubsection();
348
349 void emitDebugInfoForThunk(const Function *GV,
350 FunctionInfo &FI,
351 const MCSymbol *Fn);
352
353 void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);
354
355 void emitDebugInfoForRetainedTypes();
356
357 void emitDebugInfoForUDTs(
358 const std::vector<std::pair<std::string, const DIType *>> &UDTs);
359
360 void collectDebugInfoForGlobals();
361 void emitDebugInfoForGlobals();
362 void emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals);
363 void emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
364 const std::string &QualifiedName);
365 void emitDebugInfoForGlobal(const CVGlobalVariable &CVGV);
366 void emitStaticConstMemberList();
367
368 /// Opens a subsection of the given kind in a .debug$S codeview section.
369 /// Returns an end label for use with endCVSubsection when the subsection is
370 /// finished.
371 MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind);
372 void endCVSubsection(MCSymbol *EndLabel);
373
374 /// Opens a symbol record of the given kind. Returns an end label for use with
375 /// endSymbolRecord.
376 MCSymbol *beginSymbolRecord(codeview::SymbolKind Kind);
377 void endSymbolRecord(MCSymbol *SymEnd);
378
379 /// Emits an S_END, S_INLINESITE_END, or S_PROC_ID_END record. These records
380 /// are empty, so we emit them with a simpler assembly sequence that doesn't
381 /// involve labels.
382 void emitEndSymbolRecord(codeview::SymbolKind EndKind);
383
384 void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,
385 const InlineSite &Site);
386
387 void emitInlinees(const SmallSet<codeview::TypeIndex, 1> &Inlinees);
388
389 using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
390
391 void collectGlobalVariableInfo();
392 void collectVariableInfo(const DISubprogram *SP);
393
394 void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed);
395
396 // Construct the lexical block tree for a routine, pruning emptpy lexical
397 // scopes, and populate it with local variables.
398 void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes,
399 SmallVectorImpl<LexicalBlock *> &Blocks,
400 SmallVectorImpl<LocalVariable> &Locals,
401 SmallVectorImpl<CVGlobalVariable> &Globals);
402 void collectLexicalBlockInfo(LexicalScope &Scope,
403 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
404 SmallVectorImpl<LocalVariable> &ParentLocals,
405 SmallVectorImpl<CVGlobalVariable> &ParentGlobals);
406
407 /// Records information about a local variable in the appropriate scope. In
408 /// particular, locals from inlined code live inside the inlining site.
409 void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS);
410
411 /// Emits local variables in the appropriate order.
412 void emitLocalVariableList(const FunctionInfo &FI,
413 ArrayRef<LocalVariable> Locals);
414
415 /// Emits an S_LOCAL record and its associated defined ranges.
416 void emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var);
417
418 /// Emits a sequence of lexical block scopes and their children.
419 void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
420 const FunctionInfo& FI);
421
422 /// Emit a lexical block scope and its children.
423 void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI);
424
425 /// Translates the DIType to codeview if necessary and returns a type index
426 /// for it.
427 codeview::TypeIndex getTypeIndex(const DIType *Ty,
428 const DIType *ClassTy = nullptr);
429
430 codeview::TypeIndex
431 getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
432 const DISubroutineType *SubroutineTy);
433
434 codeview::TypeIndex getTypeIndexForReferenceTo(const DIType *Ty);
435
436 codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,
437 const DICompositeType *Class);
438
439 codeview::TypeIndex getScopeIndex(const DIScope *Scope);
440
441 codeview::TypeIndex getVBPTypeIndex();
442
443 void addToUDTs(const DIType *Ty);
444
445 void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI);
446
447 codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);
448 codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);
449 codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);
450 codeview::TypeIndex lowerTypeString(const DIStringType *Ty);
451 codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);
452 codeview::TypeIndex lowerTypePointer(
453 const DIDerivedType *Ty,
454 codeview::PointerOptions PO = codeview::PointerOptions::None);
455 codeview::TypeIndex lowerTypeMemberPointer(
456 const DIDerivedType *Ty,
457 codeview::PointerOptions PO = codeview::PointerOptions::None);
458 codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);
459 codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);
460 codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty);
461 codeview::TypeIndex lowerTypeMemberFunction(
462 const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment,
463 bool IsStaticMethod,
464 codeview::FunctionOptions FO = codeview::FunctionOptions::None);
465 codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);
466 codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);
467 codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);
468
469 /// Symbol records should point to complete types, but type records should
470 /// always point to incomplete types to avoid cycles in the type graph. Only
471 /// use this entry point when generating symbol records. The complete and
472 /// incomplete type indices only differ for record types. All other types use
473 /// the same index.
474 codeview::TypeIndex getCompleteTypeIndex(const DIType *Ty);
475
476 codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);
477 codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);
478
479 struct TypeLoweringScope;
480
481 void emitDeferredCompleteTypes();
482
483 void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);
484 ClassInfo collectClassInfo(const DICompositeType *Ty);
485
486 /// Common record member lowering functionality for record types, which are
487 /// structs, classes, and unions. Returns the field list index and the member
488 /// count.
489 std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>
490 lowerRecordFieldList(const DICompositeType *Ty);
491
492 /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
493 codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,
494 codeview::TypeIndex TI,
495 const DIType *ClassTy = nullptr);
496
497 /// Collect the names of parent scopes, innermost to outermost. Return the
498 /// innermost subprogram scope if present. Ensure that parent type scopes are
499 /// inserted into the type table.
500 const DISubprogram *
501 collectParentScopeNames(const DIScope *Scope,
502 SmallVectorImpl<StringRef> &ParentScopeNames);
503 std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name);
504 std::string getFullyQualifiedName(const DIScope *Scope);
505
506 unsigned getPointerSizeInBytes();
507
508 void discoverJumpTableBranches(const MachineFunction *MF, bool isThumb);
509 void collectDebugInfoForJumpTables(const MachineFunction *MF, bool isThumb);
510 void emitDebugInfoForJumpTables(const FunctionInfo &FI);
511
512protected:
513 /// Gather pre-function debug information.
514 void beginFunctionImpl(const MachineFunction *MF) override;
515
516 /// Gather post-function debug information.
517 void endFunctionImpl(const MachineFunction *) override;
518
519 /// Check if the current module is in Fortran.
521 return CurrentSourceLanguage == codeview::SourceLanguage::Fortran;
522 }
523
524public:
526
527 void beginModule(Module *M) override;
528
529 /// Emit the COFF section that holds the line table information.
530 void endModule() override;
531
532 /// Process beginning of an instruction.
533 void beginInstruction(const MachineInstr *MI) override;
534};
535
556
557} // end namespace llvm
558
559#endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define LLVM_LIBRARY_VISIBILITY
Definition Compiler.h:137
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
This file implements a map that provides insertion order iteration.
This file defines the PointerUnion class, which is a discriminated union of pointer types.
Basic Register Allocator
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
This file defines the SmallVector class.
Value * RHS
Value * LHS
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:96
Collects and handles line tables information in a CodeView format.
CodeViewDebug(AsmPrinter *AP)
bool moduleIsInFortran()
Check if the current module is in Fortran.
This represents a section on Windows.
Streaming machine code generation interface.
Definition MCStreamer.h:220
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
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:36
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
CPUType
These values correspond to the CV_CPU_TYPE_e enumeration, and are documented here: https://msdn....
Definition CodeView.h:76
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
std::tuple< uint64_t, uint32_t > InlineSite
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
int DataOffset
Offset of variable data in memory.
static uint64_t toOpaqueValue(const LocalVarDef DR)
uint32_t IsSubfield
Non-zero if this is a piece of an aggregate.
int InMemory
Indicates that variable data is stored in memory relative to the specified register.
uint32_t StructOffset
Offset into aggregate.
static LocalVarDef createFromOpaqueValue(uint64_t Val)
uint32_t CVRegister
Register containing the data or the register base of the memory location containing the data.
static bool isEqual(const CodeViewDebug::LocalVarDef &LHS, const CodeViewDebug::LocalVarDef &RHS)
static CodeViewDebug::LocalVarDef getEmptyKey()
static unsigned getHashValue(const CodeViewDebug::LocalVarDef &DR)
static CodeViewDebug::LocalVarDef getTombstoneKey()
An information struct used to provide DenseMap with the various necessary components for a given valu...