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