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