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