1 //===- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework --------*- 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 dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
16 
17 #include "AddressPool.h"
18 #include "DbgValueHistoryCalculator.h"
19 #include "DebugHandlerBase.h"
20 #include "DebugLocStream.h"
21 #include "DwarfAccelTable.h"
22 #include "DwarfFile.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/BinaryFormat/Dwarf.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/MC/MCDwarf.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <limits>
44 #include <memory>
45 #include <utility>
46 #include <vector>
47 
48 namespace llvm {
49 
50 class AsmPrinter;
51 class ByteStreamer;
52 class DebugLocEntry;
53 class DIE;
54 class DwarfCompileUnit;
55 class DwarfTypeUnit;
56 class DwarfUnit;
57 class LexicalScope;
58 class MachineFunction;
59 class MCSection;
60 class MCSymbol;
61 class MDNode;
62 class Module;
63 
64 //===----------------------------------------------------------------------===//
65 /// This class is used to track local variable information.
66 ///
67 /// Variables can be created from allocas, in which case they're generated from
68 /// the MMI table.  Such variables can have multiple expressions and frame
69 /// indices.
70 ///
71 /// Variables can be created from \c DBG_VALUE instructions.  Those whose
72 /// location changes over time use \a DebugLocListIndex, while those with a
73 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
74 ///
75 /// Variables that have been optimized out use none of these fields.
76 class DbgVariable {
77   const DILocalVariable *Var;                /// Variable Descriptor.
78   const DILocation *IA;                      /// Inlined at location.
79   DIE *TheDIE = nullptr;                     /// Variable DIE.
80   unsigned DebugLocListIndex = ~0u;          /// Offset in DebugLocs.
81   const MachineInstr *MInsn = nullptr;       /// DBG_VALUE instruction.
82 
83   struct FrameIndexExpr {
84     int FI;
85     const DIExpression *Expr;
86   };
87   mutable SmallVector<FrameIndexExpr, 1>
88       FrameIndexExprs; /// Frame index + expression.
89 
90 public:
91   /// Construct a DbgVariable.
92   ///
93   /// Creates a variable without any DW_AT_location.  Call \a initializeMMI()
94   /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
95   DbgVariable(const DILocalVariable *V, const DILocation *IA)
96       : Var(V), IA(IA) {}
97 
98   /// Initialize from the MMI table.
99   void initializeMMI(const DIExpression *E, int FI) {
100     assert(FrameIndexExprs.empty() && "Already initialized?");
101     assert(!MInsn && "Already initialized?");
102 
103     assert((!E || E->isValid()) && "Expected valid expression");
104     assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
105 
106     FrameIndexExprs.push_back({FI, E});
107   }
108 
109   /// Initialize from a DBG_VALUE instruction.
110   void initializeDbgValue(const MachineInstr *DbgValue) {
111     assert(FrameIndexExprs.empty() && "Already initialized?");
112     assert(!MInsn && "Already initialized?");
113 
114     assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
115     assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
116 
117     MInsn = DbgValue;
118     if (auto *E = DbgValue->getDebugExpression())
119       if (E->getNumElements())
120         FrameIndexExprs.push_back({0, E});
121   }
122 
123   // Accessors.
124   const DILocalVariable *getVariable() const { return Var; }
125   const DILocation *getInlinedAt() const { return IA; }
126 
127   const DIExpression *getSingleExpression() const {
128     assert(MInsn && FrameIndexExprs.size() <= 1);
129     return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
130   }
131 
132   void setDIE(DIE &D) { TheDIE = &D; }
133   DIE *getDIE() const { return TheDIE; }
134   void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
135   unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
136   StringRef getName() const { return Var->getName(); }
137   const MachineInstr *getMInsn() const { return MInsn; }
138   /// Get the FI entries, sorted by fragment offset.
139   ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
140   bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
141 
142   void addMMIEntry(const DbgVariable &V) {
143     assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
144     assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
145     assert(V.Var == Var && "conflicting variable");
146     assert(V.IA == IA && "conflicting inlined-at location");
147 
148     assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
149     assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
150 
151     if (FrameIndexExprs.size()) {
152       auto *Expr = FrameIndexExprs.back().Expr;
153       // Get rid of duplicate non-fragment entries. More than one non-fragment
154       // dbg.declare makes no sense so ignore all but the first.
155       if (!Expr || !Expr->isFragment())
156         return;
157     }
158     FrameIndexExprs.append(V.FrameIndexExprs.begin(), V.FrameIndexExprs.end());
159     assert(llvm::all_of(FrameIndexExprs,
160                         [](FrameIndexExpr &FIE) {
161                           return FIE.Expr && FIE.Expr->isFragment();
162                         }) &&
163            "conflicting locations for variable");
164   }
165 
166   // Translate tag to proper Dwarf tag.
167   dwarf::Tag getTag() const {
168     // FIXME: Why don't we just infer this tag and store it all along?
169     if (Var->isParameter())
170       return dwarf::DW_TAG_formal_parameter;
171 
172     return dwarf::DW_TAG_variable;
173   }
174 
175   /// Return true if DbgVariable is artificial.
176   bool isArtificial() const {
177     if (Var->isArtificial())
178       return true;
179     if (getType()->isArtificial())
180       return true;
181     return false;
182   }
183 
184   bool isObjectPointer() const {
185     if (Var->isObjectPointer())
186       return true;
187     if (getType()->isObjectPointer())
188       return true;
189     return false;
190   }
191 
192   bool hasComplexAddress() const {
193     assert(MInsn && "Expected DBG_VALUE, not MMI variable");
194     assert((FrameIndexExprs.empty() ||
195             (FrameIndexExprs.size() == 1 &&
196              FrameIndexExprs[0].Expr->getNumElements())) &&
197            "Invalid Expr for DBG_VALUE");
198     return !FrameIndexExprs.empty();
199   }
200 
201   bool isBlockByrefVariable() const;
202   const DIType *getType() const;
203 
204 private:
205   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
206     return Ref.resolve();
207   }
208 };
209 
210 /// Helper used to pair up a symbol and its DWARF compile unit.
211 struct SymbolCU {
212   SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
213 
214   const MCSymbol *Sym;
215   DwarfCompileUnit *CU;
216 };
217 
218 /// Collects and handles dwarf debug information.
219 class DwarfDebug : public DebugHandlerBase {
220   /// All DIEValues are allocated through this allocator.
221   BumpPtrAllocator DIEValueAllocator;
222 
223   /// Maps MDNode with its corresponding DwarfCompileUnit.
224   MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
225 
226   /// Maps a CU DIE with its corresponding DwarfCompileUnit.
227   DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
228 
229   /// List of all labels used in aranges generation.
230   std::vector<SymbolCU> ArangeLabels;
231 
232   /// Size of each symbol emitted (for those symbols that have a specific size).
233   DenseMap<const MCSymbol *, uint64_t> SymSize;
234 
235   /// Collection of abstract variables.
236   SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
237 
238   /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
239   /// can refer to them in spite of insertions into this list.
240   DebugLocStream DebugLocs;
241 
242   /// This is a collection of subprogram MDNodes that are processed to
243   /// create DIEs.
244   SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
245             SmallPtrSet<const DISubprogram *, 16>>
246       ProcessedSPNodes;
247 
248   /// If nonnull, stores the current machine function we're processing.
249   const MachineFunction *CurFn = nullptr;
250 
251   /// If nonnull, stores the CU in which the previous subprogram was contained.
252   const DwarfCompileUnit *PrevCU;
253 
254   /// As an optimization, there is no need to emit an entry in the directory
255   /// table for the same directory as DW_AT_comp_dir.
256   StringRef CompilationDir;
257 
258   /// Holder for the file specific debug information.
259   DwarfFile InfoHolder;
260 
261   /// Holders for the various debug information flags that we might need to
262   /// have exposed. See accessor functions below for description.
263 
264   /// Map from MDNodes for user-defined types to their type signatures. Also
265   /// used to keep track of which types we have emitted type units for.
266   DenseMap<const MDNode *, uint64_t> TypeSignatures;
267 
268   SmallVector<
269       std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
270       TypeUnitsUnderConstruction;
271 
272   /// Whether to use the GNU TLS opcode (instead of the standard opcode).
273   bool UseGNUTLSOpcode;
274 
275   /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
276   bool UseDWARF2Bitfields;
277 
278   /// Whether to emit all linkage names, or just abstract subprograms.
279   bool UseAllLinkageNames;
280 
281   /// DWARF5 Experimental Options
282   /// @{
283   bool HasDwarfAccelTables;
284   bool HasAppleExtensionAttributes;
285   bool HasSplitDwarf;
286 
287   /// Separated Dwarf Variables
288   /// In general these will all be for bits that are left in the
289   /// original object file, rather than things that are meant
290   /// to be in the .dwo sections.
291 
292   /// Holder for the skeleton information.
293   DwarfFile SkeletonHolder;
294 
295   /// Store file names for type units under fission in a line table
296   /// header that will be emitted into debug_line.dwo.
297   // FIXME: replace this with a map from comp_dir to table so that we
298   // can emit multiple tables during LTO each of which uses directory
299   // 0, referencing the comp_dir of all the type units that use it.
300   MCDwarfDwoLineTable SplitTypeUnitFileTable;
301   /// @}
302 
303   /// True iff there are multiple CUs in this module.
304   bool SingleCU;
305   bool IsDarwin;
306 
307   AddressPool AddrPool;
308 
309   DwarfAccelTable AccelNames;
310   DwarfAccelTable AccelObjC;
311   DwarfAccelTable AccelNamespace;
312   DwarfAccelTable AccelTypes;
313 
314   // Identify a debugger for "tuning" the debug info.
315   DebuggerKind DebuggerTuning = DebuggerKind::Default;
316 
317   MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
318 
319   const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
320     return InfoHolder.getUnits();
321   }
322 
323   using InlinedVariable = DbgValueHistoryMap::InlinedVariable;
324 
325   void ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable Var,
326                                        const MDNode *Scope);
327   void ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU, InlinedVariable Var,
328                                                const MDNode *Scope);
329 
330   DbgVariable *createConcreteVariable(DwarfCompileUnit &TheCU,
331                                       LexicalScope &Scope, InlinedVariable IV);
332 
333   /// Construct a DIE for this abstract scope.
334   void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
335 
336   void finishVariableDefinitions();
337 
338   void finishSubprogramDefinitions();
339 
340   /// Finish off debug information after all functions have been
341   /// processed.
342   void finalizeModuleInfo();
343 
344   /// Emit the debug info section.
345   void emitDebugInfo();
346 
347   /// Emit the abbreviation section.
348   void emitAbbreviations();
349 
350   /// Emit a specified accelerator table.
351   void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
352                  StringRef TableName);
353 
354   /// Emit visible names into a hashed accelerator table section.
355   void emitAccelNames();
356 
357   /// Emit objective C classes and categories into a hashed
358   /// accelerator table section.
359   void emitAccelObjC();
360 
361   /// Emit namespace dies into a hashed accelerator table.
362   void emitAccelNamespaces();
363 
364   /// Emit type dies into a hashed accelerator table.
365   void emitAccelTypes();
366 
367   /// Emit visible names and types into debug pubnames and pubtypes sections.
368   void emitDebugPubSections();
369 
370   void emitDebugPubSection(bool GnuStyle, StringRef Name,
371                            DwarfCompileUnit *TheU,
372                            const StringMap<const DIE *> &Globals);
373 
374   /// Emit null-terminated strings into a debug str section.
375   void emitDebugStr();
376 
377   /// Emit variable locations into a debug loc section.
378   void emitDebugLoc();
379 
380   /// Emit variable locations into a debug loc dwo section.
381   void emitDebugLocDWO();
382 
383   /// Emit address ranges into a debug aranges section.
384   void emitDebugARanges();
385 
386   /// Emit address ranges into a debug ranges section.
387   void emitDebugRanges();
388 
389   /// Emit macros into a debug macinfo section.
390   void emitDebugMacinfo();
391   void emitMacro(DIMacro &M);
392   void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
393   void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
394 
395   /// DWARF 5 Experimental Split Dwarf Emitters
396 
397   /// Initialize common features of skeleton units.
398   void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
399                         std::unique_ptr<DwarfCompileUnit> NewU);
400 
401   /// Construct the split debug info compile unit for the debug info
402   /// section.
403   DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
404 
405   /// Emit the debug info dwo section.
406   void emitDebugInfoDWO();
407 
408   /// Emit the debug abbrev dwo section.
409   void emitDebugAbbrevDWO();
410 
411   /// Emit the debug line dwo section.
412   void emitDebugLineDWO();
413 
414   /// Emit the debug str dwo section.
415   void emitDebugStrDWO();
416 
417   /// Flags to let the linker know we have emitted new style pubnames. Only
418   /// emit it here if we don't have a skeleton CU for split dwarf.
419   void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
420 
421   /// Create new DwarfCompileUnit for the given metadata node with tag
422   /// DW_TAG_compile_unit.
423   DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
424 
425   /// Construct imported_module or imported_declaration DIE.
426   void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
427                                         const DIImportedEntity *N);
428 
429   /// Register a source line with debug info. Returns the unique
430   /// label that was emitted and which provides correspondence to the
431   /// source line list.
432   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
433                         unsigned Flags);
434 
435   /// Populate LexicalScope entries with variables' info.
436   void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
437                            DenseSet<InlinedVariable> &ProcessedVars);
438 
439   /// Build the location list for all DBG_VALUEs in the
440   /// function that describe the same variable.
441   void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
442                          const DbgValueHistoryMap::InstrRanges &Ranges);
443 
444   /// Collect variable information from the side table maintained by MF.
445   void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
446                                       DenseSet<InlinedVariable> &P);
447 
448 protected:
449   /// Gather pre-function debug information.
450   void beginFunctionImpl(const MachineFunction *MF) override;
451 
452   /// Gather and emit post-function debug information.
453   void endFunctionImpl(const MachineFunction *MF) override;
454 
455   void skippedNonDebugFunction() override;
456 
457 public:
458   //===--------------------------------------------------------------------===//
459   // Main entry points.
460   //
461   DwarfDebug(AsmPrinter *A, Module *M);
462 
463   ~DwarfDebug() override;
464 
465   /// Emit all Dwarf sections that should come prior to the
466   /// content.
467   void beginModule();
468 
469   /// Emit all Dwarf sections that should come after the content.
470   void endModule() override;
471 
472   /// Process beginning of an instruction.
473   void beginInstruction(const MachineInstr *MI) override;
474 
475   /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
476   static uint64_t makeTypeSignature(StringRef Identifier);
477 
478   /// Add a DIE to the set of types that we're going to pull into
479   /// type units.
480   void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
481                             DIE &Die, const DICompositeType *CTy);
482 
483   /// Add a label so that arange data can be generated for it.
484   void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
485 
486   /// For symbols that have a size designated (e.g. common symbols),
487   /// this tracks that size.
488   void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
489     SymSize[Sym] = Size;
490   }
491 
492   /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
493   /// If not, we still might emit certain cases.
494   bool useAllLinkageNames() const { return UseAllLinkageNames; }
495 
496   /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
497   /// standard DW_OP_form_tls_address opcode
498   bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
499 
500   /// Returns whether to use the DWARF2 format for bitfields instyead of the
501   /// DWARF4 format.
502   bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
503 
504   // Experimental DWARF5 features.
505 
506   /// Returns whether or not to emit tables that dwarf consumers can
507   /// use to accelerate lookup.
508   bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
509 
510   bool useAppleExtensionAttributes() const {
511     return HasAppleExtensionAttributes;
512   }
513 
514   /// Returns whether or not to change the current debug info for the
515   /// split dwarf proposal support.
516   bool useSplitDwarf() const { return HasSplitDwarf; }
517 
518   bool shareAcrossDWOCUs() const;
519 
520   /// Returns the Dwarf Version.
521   uint16_t getDwarfVersion() const;
522 
523   /// Returns the previous CU that was being updated
524   const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
525   void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
526 
527   /// Returns the entries for the .debug_loc section.
528   const DebugLocStream &getDebugLocs() const { return DebugLocs; }
529 
530   /// Emit an entry for the debug loc section. This can be used to
531   /// handle an entry that's going to be emitted into the debug loc section.
532   void emitDebugLocEntry(ByteStreamer &Streamer,
533                          const DebugLocStream::Entry &Entry);
534 
535   /// Emit the location for a debug loc entry, including the size header.
536   void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
537 
538   /// Find the MDNode for the given reference.
539   template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
540     return Ref.resolve();
541   }
542 
543   void addSubprogramNames(const DISubprogram *SP, DIE &Die);
544 
545   AddressPool &getAddressPool() { return AddrPool; }
546 
547   void addAccelName(StringRef Name, const DIE &Die);
548 
549   void addAccelObjC(StringRef Name, const DIE &Die);
550 
551   void addAccelNamespace(StringRef Name, const DIE &Die);
552 
553   void addAccelType(StringRef Name, const DIE &Die, char Flags);
554 
555   const MachineFunction *getCurrentFunction() const { return CurFn; }
556 
557   /// A helper function to check whether the DIE for a given Scope is
558   /// going to be null.
559   bool isLexicalScopeDIENull(LexicalScope *Scope);
560 
561   /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
562   ///
563   /// Returns whether we are "tuning" for a given debugger.
564   /// @{
565   bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
566   bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
567   bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
568   /// @}
569 };
570 
571 } // end namespace llvm
572 
573 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
574