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 /// Map from MDNodes for user-defined types to the type units that
294 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
297 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
298 TypeUnitsUnderConstruction;
300 /// Whether to emit the pubnames/pubtypes sections.
301 bool HasDwarfPubSections;
303 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
304 bool UseGNUTLSOpcode;
306 /// Whether to emit DW_AT_[MIPS_]linkage_name.
307 bool UseLinkageNames;
309 /// Version of dwarf we're emitting.
310 unsigned DwarfVersion;
312 /// Maps from a type identifier to the actual MDNode.
313 DITypeIdentifierMap TypeIdentifierMap;
315 /// DWARF5 Experimental Options
317 bool HasDwarfAccelTables;
320 /// Separated Dwarf Variables
321 /// In general these will all be for bits that are left in the
322 /// original object file, rather than things that are meant
323 /// to be in the .dwo sections.
325 /// Holder for the skeleton information.
326 DwarfFile SkeletonHolder;
328 /// Store file names for type units under fission in a line table
329 /// header that will be emitted into debug_line.dwo.
330 // FIXME: replace this with a map from comp_dir to table so that we
331 // can emit multiple tables during LTO each of which uses directory
332 // 0, referencing the comp_dir of all the type units that use it.
333 MCDwarfDwoLineTable SplitTypeUnitFileTable;
336 /// True iff there are multiple CUs in this module.
340 AddressPool AddrPool;
342 DwarfAccelTable AccelNames;
343 DwarfAccelTable AccelObjC;
344 DwarfAccelTable AccelNamespace;
345 DwarfAccelTable AccelTypes;
347 DenseMap<const Function *, DISubprogram *> FunctionDIs;
349 // Identify a debugger for "tuning" the debug info.
350 DebuggerKind DebuggerTuning;
352 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
354 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
355 return InfoHolder.getUnits();
358 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
360 /// Find abstract variable associated with Var.
361 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
362 const DILocalVariable *&Cleansed);
363 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
364 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
365 void ensureAbstractVariableIsCreated(InlinedVariable Var,
366 const MDNode *Scope);
367 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
368 const MDNode *Scope);
370 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
372 /// Construct a DIE for this abstract scope.
373 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
375 /// Collect info for variables that were optimized out.
376 void collectDeadVariables();
378 void finishVariableDefinitions();
380 void finishSubprogramDefinitions();
382 /// Finish off debug information after all functions have been
384 void finalizeModuleInfo();
386 /// Emit the debug info section.
387 void emitDebugInfo();
389 /// Emit the abbreviation section.
390 void emitAbbreviations();
392 /// Emit a specified accelerator table.
393 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
394 StringRef TableName);
396 /// Emit visible names into a hashed accelerator table section.
397 void emitAccelNames();
399 /// Emit objective C classes and categories into a hashed
400 /// accelerator table section.
401 void emitAccelObjC();
403 /// Emit namespace dies into a hashed accelerator table.
404 void emitAccelNamespaces();
406 /// Emit type dies into a hashed accelerator table.
407 void emitAccelTypes();
409 /// Emit visible names into a debug pubnames section.
410 /// \param GnuStyle determines whether or not we want to emit
411 /// additional information into the table ala newer gcc for gdb
413 void emitDebugPubNames(bool GnuStyle = false);
415 /// Emit visible types into a debug pubtypes section.
416 /// \param GnuStyle determines whether or not we want to emit
417 /// additional information into the table ala newer gcc for gdb
419 void emitDebugPubTypes(bool GnuStyle = false);
421 void emitDebugPubSection(
422 bool GnuStyle, MCSection *PSec, StringRef Name,
423 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
425 /// Emit visible names into a debug str section.
428 /// Emit visible names into a debug loc section.
431 /// Emit visible names into a debug loc dwo section.
432 void emitDebugLocDWO();
434 /// Emit visible names into a debug aranges section.
435 void emitDebugARanges();
437 /// Emit visible names into a debug ranges section.
438 void emitDebugRanges();
440 /// DWARF 5 Experimental Split Dwarf Emitters
442 /// Initialize common features of skeleton units.
443 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
444 std::unique_ptr<DwarfUnit> NewU);
446 /// Construct the split debug info compile unit for the debug info
448 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
450 /// Emit the debug info dwo section.
451 void emitDebugInfoDWO();
453 /// Emit the debug abbrev dwo section.
454 void emitDebugAbbrevDWO();
456 /// Emit the debug line dwo section.
457 void emitDebugLineDWO();
459 /// Emit the debug str dwo section.
460 void emitDebugStrDWO();
462 /// Flags to let the linker know we have emitted new style pubnames. Only
463 /// emit it here if we don't have a skeleton CU for split dwarf.
464 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
466 /// Create new DwarfCompileUnit for the given metadata node with tag
467 /// DW_TAG_compile_unit.
468 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
470 /// Construct imported_module or imported_declaration DIE.
471 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
472 const DIImportedEntity *N);
474 /// Register a source line with debug info. Returns the unique
475 /// label that was emitted and which provides correspondence to the
476 /// source line list.
477 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
480 /// Indentify instructions that are marking the beginning of or
481 /// ending of a scope.
482 void identifyScopeMarkers();
484 /// Populate LexicalScope entries with variables' info.
485 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
486 DenseSet<InlinedVariable> &ProcessedVars);
488 /// Build the location list for all DBG_VALUEs in the
489 /// function that describe the same variable.
490 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
491 const DbgValueHistoryMap::InstrRanges &Ranges);
493 /// Collect variable information from the side table maintained
495 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
497 /// Ensure that a label will be emitted before MI.
498 void requestLabelBeforeInsn(const MachineInstr *MI) {
499 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
502 /// Ensure that a label will be emitted after MI.
503 void requestLabelAfterInsn(const MachineInstr *MI) {
504 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
508 //===--------------------------------------------------------------------===//
509 // Main entry points.
511 DwarfDebug(AsmPrinter *A, Module *M);
513 ~DwarfDebug() override;
515 /// Emit all Dwarf sections that should come prior to the
519 /// Emit all Dwarf sections that should come after the content.
520 void endModule() override;
522 /// Gather pre-function debug information.
523 void beginFunction(const MachineFunction *MF) override;
525 /// Gather and emit post-function debug information.
526 void endFunction(const MachineFunction *MF) override;
528 /// Process beginning of an instruction.
529 void beginInstruction(const MachineInstr *MI) override;
531 /// Process end of an instruction.
532 void endInstruction() override;
534 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
535 static uint64_t makeTypeSignature(StringRef Identifier);
537 /// Add a DIE to the set of types that we're going to pull into
539 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
540 DIE &Die, const DICompositeType *CTy);
542 /// Add a label so that arange data can be generated for it.
543 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
545 /// For symbols that have a size designated (e.g. common symbols),
546 /// this tracks that size.
547 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
551 /// Returns whether to emit DW_AT_[MIPS_]linkage_name.
552 bool useLinkageNames() const { return UseLinkageNames; }
554 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
555 /// standard DW_OP_form_tls_address opcode
556 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
558 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
560 /// Returns whether we are "tuning" for a given debugger.
562 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
563 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
564 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
567 // Experimental DWARF5 features.
569 /// Returns whether or not to emit tables that dwarf consumers can
570 /// use to accelerate lookup.
571 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
573 /// Returns whether or not to change the current debug info for the
574 /// split dwarf proposal support.
575 bool useSplitDwarf() const { return HasSplitDwarf; }
577 /// Returns the Dwarf Version.
578 unsigned getDwarfVersion() const { return DwarfVersion; }
580 /// Returns the previous CU that was being updated
581 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
582 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
584 /// Returns the entries for the .debug_loc section.
585 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
587 /// Emit an entry for the debug loc section. This can be used to
588 /// handle an entry that's going to be emitted into the debug loc section.
589 void emitDebugLocEntry(ByteStreamer &Streamer,
590 const DebugLocStream::Entry &Entry);
592 /// Emit the location for a debug loc entry, including the size header.
593 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
595 /// Find the MDNode for the given reference.
596 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
597 return Ref.resolve(TypeIdentifierMap);
600 /// Return the TypeIdentifierMap.
601 const DITypeIdentifierMap &getTypeIdentifierMap() const {
602 return TypeIdentifierMap;
605 /// Find the DwarfCompileUnit for the given CU Die.
606 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
607 return CUDieMap.lookup(CU);
610 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
612 AddressPool &getAddressPool() { return AddrPool; }
614 void addAccelName(StringRef Name, const DIE &Die);
616 void addAccelObjC(StringRef Name, const DIE &Die);
618 void addAccelNamespace(StringRef Name, const DIE &Die);
620 void addAccelType(StringRef Name, const DIE &Die, char Flags);
622 const MachineFunction *getCurrentFunction() const { return CurFn; }
624 /// A helper function to check whether the DIE for a given Scope is
625 /// going to be null.
626 bool isLexicalScopeDIENull(LexicalScope *Scope);
628 /// Return Label preceding the instruction.
629 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
631 /// Return Label immediately following the instruction.
632 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
634 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
636 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
637 return ProcessedSPNodes;
640 } // End of namespace llvm