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