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