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 /// \brief This class is used to record source line correspondence.
54 unsigned Line; // Source line number.
55 unsigned Column; // Source column.
56 unsigned SourceID; // Source ID number.
57 MCSymbol *Label; // Label in code ID number.
59 SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
60 : Line(L), Column(C), SourceID(S), Label(label) {}
63 unsigned getLine() const { return Line; }
64 unsigned getColumn() const { return Column; }
65 unsigned getSourceID() const { return SourceID; }
66 MCSymbol *getLabel() const { return Label; }
69 //===----------------------------------------------------------------------===//
70 /// This class is used to track local variable information.
72 /// Variables can be created from allocas, in which case they're generated from
73 /// the MMI table. Such variables can have multiple expressions and frame
74 /// indices. The \a Expr and \a FrameIndices array must match.
76 /// Variables can be created from \c DBG_VALUE instructions. Those whose
77 /// location changes over time use \a DebugLocListIndex, while those with a
78 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
80 /// Variables that have been optimized out use none of these fields.
82 const DILocalVariable *Var; /// Variable Descriptor.
83 const DILocation *IA; /// Inlined at location.
84 SmallVector<const DIExpression *, 1> Expr; /// Complex address.
85 DIE *TheDIE = nullptr; /// Variable DIE.
86 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
87 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
88 SmallVector<int, 1> FrameIndex; /// Frame index.
92 /// Construct a DbgVariable.
94 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
95 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
96 DbgVariable(const DILocalVariable *V, const DILocation *IA, DwarfDebug *DD)
97 : Var(V), IA(IA), DD(DD) {}
99 /// Initialize from the MMI table.
100 void initializeMMI(const DIExpression *E, int FI) {
101 assert(Expr.empty() && "Already initialized?");
102 assert(FrameIndex.empty() && "Already initialized?");
103 assert(!MInsn && "Already initialized?");
105 assert((!E || E->isValid()) && "Expected valid expression");
106 assert(~FI && "Expected valid index");
109 FrameIndex.push_back(FI);
112 /// Initialize from a DBG_VALUE instruction.
113 void initializeDbgValue(const MachineInstr *DbgValue) {
114 assert(Expr.empty() && "Already initialized?");
115 assert(FrameIndex.empty() && "Already initialized?");
116 assert(!MInsn && "Already initialized?");
118 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
119 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
122 if (auto *E = DbgValue->getDebugExpression())
123 if (E->getNumElements())
128 const DILocalVariable *getVariable() const { return Var; }
129 const DILocation *getInlinedAt() const { return IA; }
130 const ArrayRef<const DIExpression *> getExpression() const { return Expr; }
131 void setDIE(DIE &D) { TheDIE = &D; }
132 DIE *getDIE() const { return TheDIE; }
133 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
134 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
135 StringRef getName() const { return Var->getName(); }
136 const MachineInstr *getMInsn() const { return MInsn; }
137 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
139 void addMMIEntry(const DbgVariable &V) {
140 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
141 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
142 assert(V.Var == Var && "conflicting variable");
143 assert(V.IA == IA && "conflicting inlined-at location");
145 assert(!FrameIndex.empty() && "Expected an MMI entry");
146 assert(!V.FrameIndex.empty() && "Expected an MMI entry");
147 assert(Expr.size() == FrameIndex.size() && "Mismatched expressions");
148 assert(V.Expr.size() == V.FrameIndex.size() && "Mismatched expressions");
150 Expr.append(V.Expr.begin(), V.Expr.end());
151 FrameIndex.append(V.FrameIndex.begin(), V.FrameIndex.end());
152 assert(std::all_of(Expr.begin(), Expr.end(), [](const DIExpression *E) {
153 return E && E->isBitPiece();
154 }) && "conflicting locations for variable");
157 // Translate tag to proper Dwarf tag.
158 dwarf::Tag getTag() const {
159 if (Var->getTag() == dwarf::DW_TAG_arg_variable)
160 return dwarf::DW_TAG_formal_parameter;
162 return dwarf::DW_TAG_variable;
164 /// \brief Return true if DbgVariable is artificial.
165 bool isArtificial() const {
166 if (Var->isArtificial())
168 if (getType()->isArtificial())
173 bool isObjectPointer() const {
174 if (Var->isObjectPointer())
176 if (getType()->isObjectPointer())
181 bool hasComplexAddress() const {
182 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
183 assert(FrameIndex.empty() && "Expected DBG_VALUE, not MMI variable");
185 (Expr.empty() || (Expr.size() == 1 && Expr.back()->getNumElements())) &&
186 "Invalid Expr for DBG_VALUE");
187 return !Expr.empty();
189 bool isBlockByrefVariable() const;
190 const DIType *getType() const;
193 /// resolve - Look in the DwarfDebug map for the MDNode that
194 /// corresponds to the reference.
195 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const;
199 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
201 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
203 DwarfCompileUnit *CU;
206 /// \brief Collects and handles dwarf debug information.
207 class DwarfDebug : public AsmPrinterHandler {
208 // Target of Dwarf emission.
211 // Collected machine module information.
212 MachineModuleInfo *MMI;
214 // All DIEValues are allocated through this allocator.
215 BumpPtrAllocator DIEValueAllocator;
217 // Maps MDNode with its corresponding DwarfCompileUnit.
218 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
220 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
221 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
223 // Maps a CU DIE with its corresponding DwarfCompileUnit.
224 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
226 // List of all labels used in aranges generation.
227 std::vector<SymbolCU> ArangeLabels;
229 // Size of each symbol emitted (for those symbols that have a specific size).
230 DenseMap<const MCSymbol *, uint64_t> SymSize;
232 LexicalScopes LScopes;
234 // Collection of abstract variables.
235 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
236 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
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;
242 // This is a collection of subprogram MDNodes that are processed to
244 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
246 // Maps instruction with label emitted before instruction.
247 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
249 // Maps instruction with label emitted after instruction.
250 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
252 // History of DBG_VALUE and clobber instructions for each user variable.
253 // Variables are listed in order of appearance.
254 DbgValueHistoryMap DbgValues;
256 // Previous instruction's location information. This is used to determine
257 // label location to indicate scope boundries in dwarf debug info.
258 DebugLoc PrevInstLoc;
261 // This location indicates end of function prologue and beginning of function
263 DebugLoc PrologEndLoc;
265 // If nonnull, stores the current machine function we're processing.
266 const MachineFunction *CurFn;
268 // If nonnull, stores the current machine instruction we're processing.
269 const MachineInstr *CurMI;
271 // If nonnull, stores the CU in which the previous subprogram was contained.
272 const DwarfCompileUnit *PrevCU;
274 // As an optimization, there is no need to emit an entry in the directory
275 // table for the same directory as DW_AT_comp_dir.
276 StringRef CompilationDir;
278 // Holder for the file specific debug information.
279 DwarfFile InfoHolder;
281 // Holders for the various debug information flags that we might need to
282 // have exposed. See accessor functions below for description.
284 // Holder for imported entities.
285 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
287 ImportedEntityMap ScopesWithImportedEntities;
289 // Map from MDNodes for user-defined types to the type units that describe
291 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
294 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
295 TypeUnitsUnderConstruction;
297 // Whether to emit the pubnames/pubtypes sections.
298 bool HasDwarfPubSections;
300 // Whether or not to use AT_ranges for compilation units.
303 // Whether we emitted a function into a section other than the default
305 bool UsedNonDefaultText;
307 // Whether to use the GNU TLS opcode (instead of the standard opcode).
308 bool UseGNUTLSOpcode;
310 // Version of dwarf we're emitting.
311 unsigned DwarfVersion;
313 // Maps from a type identifier to the actual MDNode.
314 DITypeIdentifierMap TypeIdentifierMap;
316 // 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 header that
329 /// will be emitted into debug_line.dwo.
330 // FIXME: replace this with a map from comp_dir to table so that we can emit
331 // multiple tables during LTO each of which uses directory 0, referencing the
332 // comp_dir of all the type units that use it.
333 MCDwarfDwoLineTable SplitTypeUnitFileTable;
335 // 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 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
351 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
352 return InfoHolder.getUnits();
355 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
357 /// \brief Find abstract variable associated with Var.
358 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
359 const DILocalVariable *&Cleansed);
360 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
361 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
362 void ensureAbstractVariableIsCreated(InlinedVariable Var,
363 const MDNode *Scope);
364 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
365 const MDNode *Scope);
367 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
369 /// \brief Construct a DIE for this abstract scope.
370 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
372 /// \brief Compute the size and offset of a DIE given an incoming Offset.
373 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
375 /// \brief Compute the size and offset of all the DIEs.
376 void computeSizeAndOffsets();
378 /// \brief Collect info for variables that were optimized out.
379 void collectDeadVariables();
381 void finishVariableDefinitions();
383 void finishSubprogramDefinitions();
385 /// \brief Finish off debug information after all functions have been
387 void finalizeModuleInfo();
389 /// \brief Emit the debug info section.
390 void emitDebugInfo();
392 /// \brief Emit the abbreviation section.
393 void emitAbbreviations();
395 /// \brief Emit a specified accelerator table.
396 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
397 StringRef TableName);
399 /// \brief Emit visible names into a hashed accelerator table section.
400 void emitAccelNames();
402 /// \brief Emit objective C classes and categories into a hashed
403 /// accelerator table section.
404 void emitAccelObjC();
406 /// \brief Emit namespace dies into a hashed accelerator table.
407 void emitAccelNamespaces();
409 /// \brief Emit type dies into a hashed accelerator table.
410 void emitAccelTypes();
412 /// \brief Emit visible names into a debug pubnames section.
413 /// \param GnuStyle determines whether or not we want to emit
414 /// additional information into the table ala newer gcc for gdb
416 void emitDebugPubNames(bool GnuStyle = false);
418 /// \brief Emit visible types into a debug pubtypes section.
419 /// \param GnuStyle determines whether or not we want to emit
420 /// additional information into the table ala newer gcc for gdb
422 void emitDebugPubTypes(bool GnuStyle = false);
424 void emitDebugPubSection(
425 bool GnuStyle, MCSection *PSec, StringRef Name,
426 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
428 /// \brief Emit visible names into a debug str section.
431 /// \brief Emit visible names into a debug loc section.
434 /// \brief Emit visible names into a debug loc dwo section.
435 void emitDebugLocDWO();
437 /// \brief Emit visible names into a debug aranges section.
438 void emitDebugARanges();
440 /// \brief Emit visible names into a debug ranges section.
441 void emitDebugRanges();
443 /// \brief Emit inline info using custom format.
444 void emitDebugInlineInfo();
446 /// DWARF 5 Experimental Split Dwarf Emitters
448 /// \brief Initialize common features of skeleton units.
449 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
450 std::unique_ptr<DwarfUnit> NewU);
452 /// \brief Construct the split debug info compile unit for the debug info
454 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
456 /// \brief Construct the split debug info compile unit for the debug info
458 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
460 /// \brief Emit the debug info dwo section.
461 void emitDebugInfoDWO();
463 /// \brief Emit the debug abbrev dwo section.
464 void emitDebugAbbrevDWO();
466 /// \brief Emit the debug line dwo section.
467 void emitDebugLineDWO();
469 /// \brief Emit the debug str dwo section.
470 void emitDebugStrDWO();
472 /// Flags to let the linker know we have emitted new style pubnames. Only
473 /// emit it here if we don't have a skeleton CU for split dwarf.
474 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
476 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
477 /// DW_TAG_compile_unit.
478 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
480 /// \brief Construct imported_module or imported_declaration DIE.
481 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
482 const DIImportedEntity *N);
484 /// \brief Register a source line with debug info. Returns the unique
485 /// label that was emitted and which provides correspondence to the
486 /// source line list.
487 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
490 /// \brief Indentify instructions that are marking the beginning of or
491 /// ending of a scope.
492 void identifyScopeMarkers();
494 /// \brief Populate LexicalScope entries with variables' info.
495 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
496 DenseSet<InlinedVariable> &ProcessedVars);
498 /// \brief Build the location list for all DBG_VALUEs in the
499 /// function that describe the same variable.
500 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
501 const DbgValueHistoryMap::InstrRanges &Ranges);
503 /// \brief Collect variable information from the side table maintained
505 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
507 /// \brief Ensure that a label will be emitted before MI.
508 void requestLabelBeforeInsn(const MachineInstr *MI) {
509 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
512 /// \brief Ensure that a label will be emitted after MI.
513 void requestLabelAfterInsn(const MachineInstr *MI) {
514 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
518 //===--------------------------------------------------------------------===//
519 // Main entry points.
521 DwarfDebug(AsmPrinter *A, Module *M);
523 ~DwarfDebug() override;
525 /// \brief Emit all Dwarf sections that should come prior to the
529 /// \brief Emit all Dwarf sections that should come after the content.
530 void endModule() override;
532 /// \brief Gather pre-function debug information.
533 void beginFunction(const MachineFunction *MF) override;
535 /// \brief Gather and emit post-function debug information.
536 void endFunction(const MachineFunction *MF) override;
538 /// \brief Process beginning of an instruction.
539 void beginInstruction(const MachineInstr *MI) override;
541 /// \brief Process end of an instruction.
542 void endInstruction() override;
544 /// \brief Add a DIE to the set of types that we're going to pull into
546 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
547 DIE &Die, const DICompositeType *CTy);
549 /// \brief Add a label so that arange data can be generated for it.
550 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
552 /// \brief For symbols that have a size designated (e.g. common symbols),
553 /// this tracks that size.
554 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
558 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
559 /// standard DW_OP_form_tls_address opcode
560 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
562 // Experimental DWARF5 features.
564 /// \brief Returns whether or not to emit tables that dwarf consumers can
565 /// use to accelerate lookup.
566 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
568 /// \brief Returns whether or not to change the current debug info for the
569 /// split dwarf proposal support.
570 bool useSplitDwarf() const { return HasSplitDwarf; }
572 /// Returns the Dwarf Version.
573 unsigned getDwarfVersion() const { return DwarfVersion; }
575 /// Returns the previous CU that was being updated
576 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
577 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
579 /// Returns the entries for the .debug_loc section.
580 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
582 /// \brief Emit an entry for the debug loc section. This can be used to
583 /// handle an entry that's going to be emitted into the debug loc section.
584 void emitDebugLocEntry(ByteStreamer &Streamer,
585 const DebugLocStream::Entry &Entry);
587 /// Emit the location for a debug loc entry, including the size header.
588 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
590 /// Find the MDNode for the given reference.
591 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
592 return Ref.resolve(TypeIdentifierMap);
595 /// \brief Return the TypeIdentifierMap.
596 const DITypeIdentifierMap &getTypeIdentifierMap() const {
597 return TypeIdentifierMap;
600 /// Find the DwarfCompileUnit for the given CU Die.
601 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
602 return CUDieMap.lookup(CU);
604 /// isSubprogramContext - Return true if Context is either a subprogram
605 /// or another context nested inside a subprogram.
606 bool isSubprogramContext(const MDNode *Context);
608 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
610 AddressPool &getAddressPool() { return AddrPool; }
612 void addAccelName(StringRef Name, const DIE &Die);
614 void addAccelObjC(StringRef Name, const DIE &Die);
616 void addAccelNamespace(StringRef Name, const DIE &Die);
618 void addAccelType(StringRef Name, const DIE &Die, char Flags);
620 const MachineFunction *getCurrentFunction() const { return CurFn; }
622 iterator_range<ImportedEntityMap::const_iterator>
623 findImportedEntitiesForScope(const MDNode *Scope) const {
624 return make_range(std::equal_range(
625 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
626 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
630 /// \brief A helper function to check whether the DIE for a given Scope is
631 /// going to be null.
632 bool isLexicalScopeDIENull(LexicalScope *Scope);
634 /// \brief Return Label preceding the instruction.
635 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
637 /// \brief Return Label immediately following the instruction.
638 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
640 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
642 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
643 return ProcessedSPNodes;
646 } // End of namespace llvm