1 //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework ------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
17 #include "AsmPrinterHandler.h"
18 #include "DbgValueHistoryCalculator.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/FoldingSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/CodeGen/DIE.h"
29 #include "llvm/CodeGen/LexicalScopes.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DebugLoc.h"
33 #include "llvm/MC/MCDwarf.h"
34 #include "llvm/MC/MachineLocation.h"
35 #include "llvm/Support/Allocator.h"
45 class DwarfCompileUnit;
49 class MachineModuleInfo;
51 //===----------------------------------------------------------------------===//
52 /// This class is used to track local variable information.
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.
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.
62 /// Variables that have been optimized out use none of these fields.
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.
74 /// Construct a DbgVariable.
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) {}
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?");
87 assert((!E || E->isValid()) && "Expected valid expression");
88 assert(~FI && "Expected valid index");
91 FrameIndex.push_back(FI);
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?");
100 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
101 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
104 if (auto *E = DbgValue->getDebugExpression())
105 if (E->getNumElements())
110 const DILocalVariable *getVariable() const { return Var; }
111 const DILocation *getInlinedAt() const { return IA; }
112 ArrayRef<const DIExpression *> getExpression() const { return Expr; }
113 void setDIE(DIE &D) { TheDIE = &D; }
114 DIE *getDIE() const { return TheDIE; }
115 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
116 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
117 StringRef getName() const { return Var->getName(); }
118 const MachineInstr *getMInsn() const { return MInsn; }
119 ArrayRef<int> getFrameIndex() const { return FrameIndex; }
121 void addMMIEntry(const DbgVariable &V) {
122 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
123 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
124 assert(V.Var == Var && "conflicting variable");
125 assert(V.IA == IA && "conflicting inlined-at location");
127 assert(!FrameIndex.empty() && "Expected an MMI entry");
128 assert(!V.FrameIndex.empty() && "Expected an MMI entry");
129 assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
130 assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
132 Expr.append(V.Expr.begin(), V.Expr.end());
133 FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
134 assert(std::all_of(Expr.begin(), Expr.end(), [](const DIExpression *E) {
135 return E && E->isBitPiece();
136 }) && "conflicting locations for variable");
139 // Translate tag to proper Dwarf tag.
140 dwarf::Tag getTag() const {
141 // FIXME: Why don't we just infer this tag and store it all along?
142 if (Var->isParameter())
143 return dwarf::DW_TAG_formal_parameter;
145 return dwarf::DW_TAG_variable;
147 /// Return true if DbgVariable is artificial.
148 bool isArtificial() const {
149 if (Var->isArtificial())
151 if (getType()->isArtificial())
156 bool isObjectPointer() const {
157 if (Var->isObjectPointer())
159 if (getType()->isObjectPointer())
164 bool hasComplexAddress() const {
165 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
166 assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
168 (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
169 "Invalid Expr for DBG_VALUE");
170 return !Expr.empty();
172 bool isBlockByrefVariable() const;
173 const DIType *getType() const;
176 /// Look in the DwarfDebug map for the MDNode that
177 /// corresponds to the reference.
178 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
182 /// Helper used to pair up a symbol and its DWARF compile unit.
184 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
186 DwarfCompileUnit *CU;
189 /// Identify a debugger for "tuning" the debug info.
191 /// The "debugger tuning" concept allows us to present a more intuitive
192 /// interface that unpacks into different sets of defaults for the various
193 /// individual feature-flag settings, that suit the preferences of the
194 /// various debuggers. However, it's worth remembering that debuggers are
195 /// not the only consumers of debug info, and some variations in DWARF might
196 /// better be treated as target/platform issues. Fundamentally,
197 /// o if the feature is useful (or not) to a particular debugger, regardless
198 /// of the target, that's a tuning decision;
199 /// o if the feature is useful (or not) on a particular platform, regardless
200 /// of the debugger, that's a target decision.
201 /// It's not impossible to see both factors in some specific case.
203 /// The "tuning" should be used to set defaults for individual feature flags
204 /// in DwarfDebug; if a given feature has a more specific command-line option,
205 /// that option should take precedence over the tuning.
206 enum class DebuggerKind {
207 Default, // No specific tuning requested.
208 GDB, // Tune debug info for gdb.
209 LLDB, // Tune debug info for lldb.
210 SCE // Tune debug info for SCE targets (e.g. PS4).
213 /// Collects and handles dwarf debug information.
214 class DwarfDebug : public AsmPrinterHandler {
215 /// Target of Dwarf emission.
218 /// Collected machine module information.
219 MachineModuleInfo *MMI;
221 /// All DIEValues are allocated through this allocator.
222 BumpPtrAllocator DIEValueAllocator;
224 /// Maps MDNode with its corresponding DwarfCompileUnit.
225 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
227 /// Maps subprogram MDNode with its corresponding DwarfCompileUnit.
228 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
230 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
231 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
233 /// List of all labels used in aranges generation.
234 std::vector<SymbolCU> ArangeLabels;
236 /// Size of each symbol emitted (for those symbols that have a specific size).
237 DenseMap<const MCSymbol *, uint64_t> SymSize;
239 LexicalScopes LScopes;
241 /// Collection of abstract variables.
242 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
243 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
245 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
246 /// can refer to them in spite of insertions into this list.
247 DebugLocStream DebugLocs;
249 /// This is a collection of subprogram MDNodes that are processed to
251 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
253 /// Maps instruction with label emitted before instruction.
254 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
256 /// Maps instruction with label emitted after instruction.
257 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
259 /// History of DBG_VALUE and clobber instructions for each user
260 /// variable. Variables are listed in order of appearance.
261 DbgValueHistoryMap DbgValues;
263 /// Previous instruction's location information. This is used to
264 /// determine label location to indicate scope boundries in dwarf
266 DebugLoc PrevInstLoc;
269 /// This location indicates end of function prologue and beginning of
271 DebugLoc PrologEndLoc;
273 /// If nonnull, stores the current machine function we're processing.
274 const MachineFunction *CurFn;
276 /// If nonnull, stores the current machine instruction we're processing.
277 const MachineInstr *CurMI;
279 /// If nonnull, stores the CU in which the previous subprogram was contained.
280 const DwarfCompileUnit *PrevCU;
282 /// As an optimization, there is no need to emit an entry in the directory
283 /// table for the same directory as DW_AT_comp_dir.
284 StringRef CompilationDir;
286 /// Holder for the file specific debug information.
287 DwarfFile InfoHolder;
289 /// Holders for the various debug information flags that we might need to
290 /// have exposed. See accessor functions below for description.
292 /// Holder for imported entities.
293 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
295 ImportedEntityMap ScopesWithImportedEntities;
297 /// Map from MDNodes for user-defined types to the type units that
299 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
302 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
303 TypeUnitsUnderConstruction;
305 /// Whether to emit the pubnames/pubtypes sections.
306 bool HasDwarfPubSections;
308 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
309 bool UseGNUTLSOpcode;
311 /// Whether to emit DW_AT_[MIPS_]linkage_name.
312 bool UseLinkageNames;
314 /// Version of dwarf we're emitting.
315 unsigned DwarfVersion;
317 /// Maps from a type identifier to the actual MDNode.
318 DITypeIdentifierMap TypeIdentifierMap;
320 /// DWARF5 Experimental Options
322 bool HasDwarfAccelTables;
325 /// Separated Dwarf Variables
326 /// In general these will all be for bits that are left in the
327 /// original object file, rather than things that are meant
328 /// to be in the .dwo sections.
330 /// Holder for the skeleton information.
331 DwarfFile SkeletonHolder;
333 /// Store file names for type units under fission in a line table
334 /// header that will be emitted into debug_line.dwo.
335 // FIXME: replace this with a map from comp_dir to table so that we
336 // can emit multiple tables during LTO each of which uses directory
337 // 0, referencing the comp_dir of all the type units that use it.
338 MCDwarfDwoLineTable SplitTypeUnitFileTable;
341 /// True iff there are multiple CUs in this module.
345 AddressPool AddrPool;
347 DwarfAccelTable AccelNames;
348 DwarfAccelTable AccelObjC;
349 DwarfAccelTable AccelNamespace;
350 DwarfAccelTable AccelTypes;
352 DenseMap<const Function *, DISubprogram *> FunctionDIs;
354 // Identify a debugger for "tuning" the debug info.
355 DebuggerKind DebuggerTuning;
357 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
359 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
360 return InfoHolder.getUnits();
363 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
365 /// Find abstract variable associated with Var.
366 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
367 const DILocalVariable *&Cleansed);
368 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
369 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
370 void ensureAbstractVariableIsCreated(InlinedVariable Var,
371 const MDNode *Scope);
372 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
373 const MDNode *Scope);
375 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
377 /// Construct a DIE for this abstract scope.
378 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
380 /// Collect info for variables that were optimized out.
381 void collectDeadVariables();
383 void finishVariableDefinitions();
385 void finishSubprogramDefinitions();
387 /// Finish off debug information after all functions have been
389 void finalizeModuleInfo();
391 /// Emit the debug info section.
392 void emitDebugInfo();
394 /// Emit the abbreviation section.
395 void emitAbbreviations();
397 /// Emit a specified accelerator table.
398 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
399 StringRef TableName);
401 /// Emit visible names into a hashed accelerator table section.
402 void emitAccelNames();
404 /// Emit objective C classes and categories into a hashed
405 /// accelerator table section.
406 void emitAccelObjC();
408 /// Emit namespace dies into a hashed accelerator table.
409 void emitAccelNamespaces();
411 /// Emit type dies into a hashed accelerator table.
412 void emitAccelTypes();
414 /// Emit visible names into a debug pubnames section.
415 /// \param GnuStyle determines whether or not we want to emit
416 /// additional information into the table ala newer gcc for gdb
418 void emitDebugPubNames(bool GnuStyle = false);
420 /// Emit visible types into a debug pubtypes section.
421 /// \param GnuStyle determines whether or not we want to emit
422 /// additional information into the table ala newer gcc for gdb
424 void emitDebugPubTypes(bool GnuStyle = false);
426 void emitDebugPubSection(
427 bool GnuStyle, MCSection *PSec, StringRef Name,
428 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
430 /// Emit visible names into a debug str section.
433 /// Emit visible names into a debug loc section.
436 /// Emit visible names into a debug loc dwo section.
437 void emitDebugLocDWO();
439 /// Emit visible names into a debug aranges section.
440 void emitDebugARanges();
442 /// Emit visible names into a debug ranges section.
443 void emitDebugRanges();
445 /// DWARF 5 Experimental Split Dwarf Emitters
447 /// Initialize common features of skeleton units.
448 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
449 std::unique_ptr<DwarfUnit> NewU);
451 /// Construct the split debug info compile unit for the debug info
453 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
455 /// Emit the debug info dwo section.
456 void emitDebugInfoDWO();
458 /// Emit the debug abbrev dwo section.
459 void emitDebugAbbrevDWO();
461 /// Emit the debug line dwo section.
462 void emitDebugLineDWO();
464 /// Emit the debug str dwo section.
465 void emitDebugStrDWO();
467 /// Flags to let the linker know we have emitted new style pubnames. Only
468 /// emit it here if we don't have a skeleton CU for split dwarf.
469 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
471 /// Create new DwarfCompileUnit for the given metadata node with tag
472 /// DW_TAG_compile_unit.
473 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
475 /// Construct imported_module or imported_declaration DIE.
476 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
477 const DIImportedEntity *N);
479 /// Register a source line with debug info. Returns the unique
480 /// label that was emitted and which provides correspondence to the
481 /// source line list.
482 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
485 /// Indentify instructions that are marking the beginning of or
486 /// ending of a scope.
487 void identifyScopeMarkers();
489 /// Populate LexicalScope entries with variables' info.
490 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
491 DenseSet<InlinedVariable> &ProcessedVars);
493 /// Build the location list for all DBG_VALUEs in the
494 /// function that describe the same variable.
495 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
496 const DbgValueHistoryMap::InstrRanges &Ranges);
498 /// Collect variable information from the side table maintained
500 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
502 /// Ensure that a label will be emitted before MI.
503 void requestLabelBeforeInsn(const MachineInstr *MI) {
504 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
507 /// Ensure that a label will be emitted after MI.
508 void requestLabelAfterInsn(const MachineInstr *MI) {
509 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
513 //===--------------------------------------------------------------------===//
514 // Main entry points.
516 DwarfDebug(AsmPrinter *A, Module *M);
518 ~DwarfDebug() override;
520 /// Emit all Dwarf sections that should come prior to the
524 /// Emit all Dwarf sections that should come after the content.
525 void endModule() override;
527 /// Gather pre-function debug information.
528 void beginFunction(const MachineFunction *MF) override;
530 /// Gather and emit post-function debug information.
531 void endFunction(const MachineFunction *MF) override;
533 /// Process beginning of an instruction.
534 void beginInstruction(const MachineInstr *MI) override;
536 /// Process end of an instruction.
537 void endInstruction() override;
539 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
540 static uint64_t makeTypeSignature(StringRef Identifier);
542 /// Add a DIE to the set of types that we're going to pull into
544 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
545 DIE &Die, const DICompositeType *CTy);
547 /// Add a label so that arange data can be generated for it.
548 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
550 /// For symbols that have a size designated (e.g. common symbols),
551 /// this tracks that size.
552 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
556 /// Returns whether to emit DW_AT_[MIPS_]linkage_name.
557 bool useLinkageNames() const { return UseLinkageNames; }
559 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
560 /// standard DW_OP_form_tls_address opcode
561 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
563 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
565 /// Returns whether we are "tuning" for a given debugger.
567 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
568 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
569 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
572 // Experimental DWARF5 features.
574 /// Returns whether or not to emit tables that dwarf consumers can
575 /// use to accelerate lookup.
576 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
578 /// Returns whether or not to change the current debug info for the
579 /// split dwarf proposal support.
580 bool useSplitDwarf() const { return HasSplitDwarf; }
582 /// Returns the Dwarf Version.
583 unsigned getDwarfVersion() const { return DwarfVersion; }
585 /// Returns the previous CU that was being updated
586 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
587 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
589 /// Returns the entries for the .debug_loc section.
590 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
592 /// Emit an entry for the debug loc section. This can be used to
593 /// handle an entry that's going to be emitted into the debug loc section.
594 void emitDebugLocEntry(ByteStreamer &Streamer,
595 const DebugLocStream::Entry &Entry);
597 /// Emit the location for a debug loc entry, including the size header.
598 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
600 /// Find the MDNode for the given reference.
601 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
602 return Ref.resolve(TypeIdentifierMap);
605 /// Return the TypeIdentifierMap.
606 const DITypeIdentifierMap &getTypeIdentifierMap() const {
607 return TypeIdentifierMap;
610 /// Find the DwarfCompileUnit for the given CU Die.
611 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
612 return CUDieMap.lookup(CU);
615 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
617 AddressPool &getAddressPool() { return AddrPool; }
619 void addAccelName(StringRef Name, const DIE &Die);
621 void addAccelObjC(StringRef Name, const DIE &Die);
623 void addAccelNamespace(StringRef Name, const DIE &Die);
625 void addAccelType(StringRef Name, const DIE &Die, char Flags);
627 const MachineFunction *getCurrentFunction() const { return CurFn; }
629 iterator_range<ImportedEntityMap::const_iterator>
630 findImportedEntitiesForScope(const MDNode *Scope) const {
631 return make_range(std::equal_range(
632 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
633 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
637 /// A helper function to check whether the DIE for a given Scope is
638 /// going to be null.
639 bool isLexicalScopeDIENull(LexicalScope *Scope);
641 /// Return Label preceding the instruction.
642 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
644 /// Return Label immediately following the instruction.
645 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
647 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
649 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
650 return ProcessedSPNodes;
653 } // End of namespace llvm