1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
16 
17 #include "DbgEntityHistoryCalculator.h"
18 #include "DebugHandlerBase.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallVector.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   /// Represents the most general definition range.
58   struct LocalVarDefRange {
59     /// Indicates that variable data is stored in memory relative to the
60     /// specified register.
61     int InMemory : 1;
62 
63     /// Offset of variable data in memory.
64     int DataOffset : 31;
65 
66     /// Non-zero if this is a piece of an aggregate.
67     uint16_t IsSubfield : 1;
68 
69     /// Offset into aggregate.
70     uint16_t StructOffset : 15;
71 
72     /// Register containing the data or the register base of the memory
73     /// location containing the data.
74     uint16_t CVRegister;
75 
76     /// Compares all location fields. This includes all fields except the label
77     /// ranges.
78     bool isDifferentLocation(LocalVarDefRange &O) {
79       return InMemory != O.InMemory || DataOffset != O.DataOffset ||
80              IsSubfield != O.IsSubfield || StructOffset != O.StructOffset ||
81              CVRegister != O.CVRegister;
82     }
83 
84     SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1> Ranges;
85   };
86 
87   static LocalVarDefRange createDefRangeMem(uint16_t CVRegister, int Offset);
88 
89   /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
90   struct LocalVariable {
91     const DILocalVariable *DIVar = nullptr;
92     SmallVector<LocalVarDefRange, 1> DefRanges;
93     bool UseReferenceType = false;
94   };
95 
96   struct InlineSite {
97     SmallVector<LocalVariable, 1> InlinedLocals;
98     SmallVector<const DILocation *, 1> ChildSites;
99     const DISubprogram *Inlinee = nullptr;
100 
101     /// The ID of the inline site or function used with .cv_loc. Not a type
102     /// index.
103     unsigned SiteFuncId = 0;
104   };
105 
106   // Combines information from DILexicalBlock and LexicalScope.
107   struct LexicalBlock {
108     SmallVector<LocalVariable, 1> Locals;
109     SmallVector<LexicalBlock *, 1> Children;
110     const MCSymbol *Begin;
111     const MCSymbol *End;
112     StringRef Name;
113   };
114 
115   // For each function, store a vector of labels to its instructions, as well as
116   // to the end of the function.
117   struct FunctionInfo {
118     FunctionInfo() = default;
119 
120     // Uncopyable.
121     FunctionInfo(const FunctionInfo &FI) = delete;
122 
123     /// Map from inlined call site to inlined instructions and child inlined
124     /// call sites. Listed in program order.
125     std::unordered_map<const DILocation *, InlineSite> InlineSites;
126 
127     /// Ordered list of top-level inlined call sites.
128     SmallVector<const DILocation *, 1> ChildSites;
129 
130     SmallVector<LocalVariable, 1> Locals;
131 
132     std::unordered_map<const DILexicalBlockBase*, LexicalBlock> LexicalBlocks;
133 
134     // Lexical blocks containing local variables.
135     SmallVector<LexicalBlock *, 1> ChildBlocks;
136 
137     std::vector<std::pair<MCSymbol *, MDNode *>> Annotations;
138 
139     const MCSymbol *Begin = nullptr;
140     const MCSymbol *End = nullptr;
141     unsigned FuncId = 0;
142     unsigned LastFileId = 0;
143     bool HaveLineInfo = false;
144   };
145   FunctionInfo *CurFn = nullptr;
146 
147   // Map used to seperate variables according to the lexical scope they belong
148   // in.  This is populated by recordLocalVariable() before
149   // collectLexicalBlocks() separates the variables between the FunctionInfo
150   // and LexicalBlocks.
151   DenseMap<const LexicalScope *, SmallVector<LocalVariable, 1>> ScopeVariables;
152 
153   /// The set of comdat .debug$S sections that we've seen so far. Each section
154   /// must start with a magic version number that must only be emitted once.
155   /// This set tracks which sections we've already opened.
156   DenseSet<MCSectionCOFF *> ComdatDebugSections;
157 
158   /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
159   /// of an emitted global value, is in a comdat COFF section, this will switch
160   /// to a new .debug$S section in that comdat. This method ensures that the
161   /// section starts with the magic version number on first use. If GVSym is
162   /// null, uses the main .debug$S section.
163   void switchToDebugSectionForSymbol(const MCSymbol *GVSym);
164 
165   /// The next available function index for use with our .cv_* directives. Not
166   /// to be confused with type indices for LF_FUNC_ID records.
167   unsigned NextFuncId = 0;
168 
169   InlineSite &getInlineSite(const DILocation *InlinedAt,
170                             const DISubprogram *Inlinee);
171 
172   codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);
173 
174   void calculateRanges(LocalVariable &Var,
175                        const DbgValueHistoryMap::InstrRanges &Ranges);
176 
177   static void collectInlineSiteChildren(SmallVectorImpl<unsigned> &Children,
178                                         const FunctionInfo &FI,
179                                         const InlineSite &Site);
180 
181   /// Remember some debug info about each function. Keep it in a stable order to
182   /// emit at the end of the TU.
183   MapVector<const Function *, std::unique_ptr<FunctionInfo>> FnDebugInfo;
184 
185   /// Map from full file path to .cv_file id. Full paths are built from DIFiles
186   /// and are stored in FileToFilepathMap;
187   DenseMap<StringRef, unsigned> FileIdMap;
188 
189   /// All inlined subprograms in the order they should be emitted.
190   SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;
191 
192   /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
193   /// be nullptr, to CodeView type indices. Primarily indexed by
194   /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
195   ///
196   /// The second entry in the key is needed for methods as DISubroutineType
197   /// representing static method type are shared with non-method function type.
198   DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>
199       TypeIndices;
200 
201   /// Map from DICompositeType* to complete type index. Non-record types are
202   /// always looked up in the normal TypeIndices map.
203   DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;
204 
205   /// Complete record types to emit after all active type lowerings are
206   /// finished.
207   SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;
208 
209   /// Number of type lowering frames active on the stack.
210   unsigned TypeEmissionLevel = 0;
211 
212   codeview::TypeIndex VBPType;
213 
214   const DISubprogram *CurrentSubprogram = nullptr;
215 
216   // The UDTs we have seen while processing types; each entry is a pair of type
217   // index and type name.
218   std::vector<std::pair<std::string, const DIType *>> LocalUDTs;
219   std::vector<std::pair<std::string, const DIType *>> GlobalUDTs;
220 
221   using FileToFilepathMapTy = std::map<const DIFile *, std::string>;
222   FileToFilepathMapTy FileToFilepathMap;
223 
224   StringRef getFullFilepath(const DIFile *File);
225 
226   unsigned maybeRecordFile(const DIFile *F);
227 
228   void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);
229 
230   void clear();
231 
232   void setCurrentSubprogram(const DISubprogram *SP) {
233     CurrentSubprogram = SP;
234     LocalUDTs.clear();
235   }
236 
237   /// Emit the magic version number at the start of a CodeView type or symbol
238   /// section. Appears at the front of every .debug$S or .debug$T or .debug$P
239   /// section.
240   void emitCodeViewMagicVersion();
241 
242   void emitTypeInformation();
243 
244   void emitTypeGlobalHashes();
245 
246   void emitCompilerInformation();
247 
248   void emitInlineeLinesSubsection();
249 
250   void emitDebugInfoForThunk(const Function *GV,
251                              FunctionInfo &FI,
252                              const MCSymbol *Fn);
253 
254   void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);
255 
256   void emitDebugInfoForGlobals();
257 
258   void emitDebugInfoForRetainedTypes();
259 
260   void
261   emitDebugInfoForUDTs(ArrayRef<std::pair<std::string, const DIType *>> UDTs);
262 
263   void emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
264                               const GlobalVariable *GV, MCSymbol *GVSym);
265 
266   /// Opens a subsection of the given kind in a .debug$S codeview section.
267   /// Returns an end label for use with endCVSubsection when the subsection is
268   /// finished.
269   MCSymbol *beginCVSubsection(codeview::DebugSubsectionKind Kind);
270 
271   void endCVSubsection(MCSymbol *EndLabel);
272 
273   void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,
274                            const InlineSite &Site);
275 
276   using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
277 
278   void collectVariableInfo(const DISubprogram *SP);
279 
280   void collectVariableInfoFromMFTable(DenseSet<InlinedEntity> &Processed);
281 
282   // Construct the lexical block tree for a routine, pruning emptpy lexical
283   // scopes, and populate it with local variables.
284   void collectLexicalBlockInfo(SmallVectorImpl<LexicalScope *> &Scopes,
285                                SmallVectorImpl<LexicalBlock *> &Blocks,
286                                SmallVectorImpl<LocalVariable> &Locals);
287   void collectLexicalBlockInfo(LexicalScope &Scope,
288                                SmallVectorImpl<LexicalBlock *> &ParentBlocks,
289                                SmallVectorImpl<LocalVariable> &ParentLocals);
290 
291   /// Records information about a local variable in the appropriate scope. In
292   /// particular, locals from inlined code live inside the inlining site.
293   void recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS);
294 
295   /// Emits local variables in the appropriate order.
296   void emitLocalVariableList(ArrayRef<LocalVariable> Locals);
297 
298   /// Emits an S_LOCAL record and its associated defined ranges.
299   void emitLocalVariable(const LocalVariable &Var);
300 
301   /// Emits a sequence of lexical block scopes and their children.
302   void emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
303                             const FunctionInfo& FI);
304 
305   /// Emit a lexical block scope and its children.
306   void emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI);
307 
308   /// Translates the DIType to codeview if necessary and returns a type index
309   /// for it.
310   codeview::TypeIndex getTypeIndex(DITypeRef TypeRef,
311                                    DITypeRef ClassTyRef = DITypeRef());
312 
313   codeview::TypeIndex getTypeIndexForReferenceTo(DITypeRef TypeRef);
314 
315   codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,
316                                             const DICompositeType *Class);
317 
318   codeview::TypeIndex getScopeIndex(const DIScope *Scope);
319 
320   codeview::TypeIndex getVBPTypeIndex();
321 
322   void addToUDTs(const DIType *Ty);
323 
324   void addUDTSrcLine(const DIType *Ty, codeview::TypeIndex TI);
325 
326   codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);
327   codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);
328   codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);
329   codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);
330   codeview::TypeIndex lowerTypePointer(
331       const DIDerivedType *Ty,
332       codeview::PointerOptions PO = codeview::PointerOptions::None);
333   codeview::TypeIndex lowerTypeMemberPointer(
334       const DIDerivedType *Ty,
335       codeview::PointerOptions PO = codeview::PointerOptions::None);
336   codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);
337   codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);
338   codeview::TypeIndex lowerTypeVFTableShape(const DIDerivedType *Ty);
339   codeview::TypeIndex lowerTypeMemberFunction(const DISubroutineType *Ty,
340                                               const DIType *ClassTy,
341                                               int ThisAdjustment,
342                                               bool IsStaticMethod);
343   codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);
344   codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);
345   codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);
346 
347   /// Symbol records should point to complete types, but type records should
348   /// always point to incomplete types to avoid cycles in the type graph. Only
349   /// use this entry point when generating symbol records. The complete and
350   /// incomplete type indices only differ for record types. All other types use
351   /// the same index.
352   codeview::TypeIndex getCompleteTypeIndex(DITypeRef TypeRef);
353 
354   codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);
355   codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);
356 
357   struct TypeLoweringScope;
358 
359   void emitDeferredCompleteTypes();
360 
361   void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);
362   ClassInfo collectClassInfo(const DICompositeType *Ty);
363 
364   /// Common record member lowering functionality for record types, which are
365   /// structs, classes, and unions. Returns the field list index and the member
366   /// count.
367   std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>
368   lowerRecordFieldList(const DICompositeType *Ty);
369 
370   /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
371   codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,
372                                                codeview::TypeIndex TI,
373                                                const DIType *ClassTy = nullptr);
374 
375   unsigned getPointerSizeInBytes();
376 
377 protected:
378   /// Gather pre-function debug information.
379   void beginFunctionImpl(const MachineFunction *MF) override;
380 
381   /// Gather post-function debug information.
382   void endFunctionImpl(const MachineFunction *) override;
383 
384 public:
385   CodeViewDebug(AsmPrinter *AP);
386 
387   void setSymbolSize(const MCSymbol *, uint64_t) override {}
388 
389   /// Emit the COFF section that holds the line table information.
390   void endModule() override;
391 
392   /// Process beginning of an instruction.
393   void beginInstruction(const MachineInstr *MI) override;
394 };
395 
396 } // end namespace llvm
397 
398 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
399