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