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 "DebugLocEntry.h"
20 #include "DebugLocList.h"
21 #include "DwarfAccelTable.h"
22 #include "DwarfFile.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/CodeGen/DIE.h"
30 #include "llvm/CodeGen/LexicalScopes.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DebugLoc.h"
34 #include "llvm/MC/MCDwarf.h"
35 #include "llvm/MC/MachineLocation.h"
36 #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 /// \brief This class is used to track local variable information.
72 /// - Variables whose location changes over time have a DotDebugLocOffset and
73 /// the other fields are not used.
75 /// - Variables that are described by multiple MMI table entries have multiple
76 /// expressions and frame indices.
78 DIVariable Var; /// Variable Descriptor.
79 DILocation IA; /// Inlined at location.
80 SmallVector<DIExpression, 1> Expr; /// Complex address location expression.
81 DIE *TheDIE; /// Variable DIE.
82 unsigned DotDebugLocOffset; /// Offset in DotDebugLocEntries.
83 const MachineInstr *MInsn; /// DBG_VALUE instruction of the variable.
84 SmallVector<int, 1> FrameIndex; /// Frame index of the variable.
88 /// Construct a DbgVariable from a DIVariable.
89 DbgVariable(DIVariable V, DILocation IA, DIExpression E, DwarfDebug *DD,
91 : Var(V), IA(IA), Expr(1, E), TheDIE(nullptr), DotDebugLocOffset(~0U),
92 MInsn(nullptr), DD(DD) {
93 FrameIndex.push_back(FI);
94 assert(!E || E->isValid());
97 /// Construct a DbgVariable from a DEBUG_VALUE.
98 /// AbstractVar may be NULL.
99 DbgVariable(const MachineInstr *DbgValue, DwarfDebug *DD)
100 : Var(DbgValue->getDebugVariable()),
101 IA(DbgValue->getDebugLoc() ? DbgValue->getDebugLoc()->getInlinedAt()
103 Expr(1, DbgValue->getDebugExpression()), TheDIE(nullptr),
104 DotDebugLocOffset(~0U), MInsn(DbgValue), DD(DD) {
105 FrameIndex.push_back(~0);
106 if (MDLocation *Loc = DbgValue->getDebugLoc())
107 IA = Loc->getInlinedAt();
111 DIVariable getVariable() const { return Var; }
112 DILocation getInlinedAt() const { return IA; }
113 const ArrayRef<DIExpression> getExpression() const { return Expr; }
114 void setDIE(DIE &D) { TheDIE = &D; }
115 DIE *getDIE() const { return TheDIE; }
116 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
117 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
118 StringRef getName() const { return Var->getName(); }
119 const MachineInstr *getMInsn() const { return MInsn; }
120 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
122 void addMMIEntry(const DbgVariable &V) {
123 assert( DotDebugLocOffset == ~0U && !MInsn && "not an MMI entry");
124 assert(V.DotDebugLocOffset == ~0U && !V.MInsn && "not an MMI entry");
125 assert(V.Var == Var && "conflicting DIVariable");
126 assert(V.IA == IA && "conflicting inlined-at location");
128 if (V.getFrameIndex().back() != ~0) {
129 auto E = V.getExpression();
130 auto FI = V.getFrameIndex();
131 Expr.append(E.begin(), E.end());
132 FrameIndex.append(FI.begin(), FI.end());
134 assert(Expr.size() > 1
135 ? std::all_of(Expr.begin(), Expr.end(),
136 [](DIExpression &E) { return E->isBitPiece(); })
137 : (true && "conflicting locations for variable"));
140 // Translate tag to proper Dwarf tag.
141 dwarf::Tag getTag() const {
142 if (Var->getTag() == dwarf::DW_TAG_arg_variable)
143 return dwarf::DW_TAG_formal_parameter;
145 return dwarf::DW_TAG_variable;
147 /// \brief 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 variableHasComplexAddress() const {
165 assert(Var && "Invalid complex DbgVariable!");
166 assert(Expr.size() == 1 &&
167 "variableHasComplexAddress() invoked on multi-FI variable");
168 return Expr.back()->getNumElements() > 0;
170 bool isBlockByrefVariable() const;
171 DIType getType() const;
174 /// resolve - Look in the DwarfDebug map for the MDNode that
175 /// corresponds to the reference.
176 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const;
180 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
182 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
184 DwarfCompileUnit *CU;
187 /// \brief Collects and handles dwarf debug information.
188 class DwarfDebug : public AsmPrinterHandler {
189 // Target of Dwarf emission.
192 // Collected machine module information.
193 MachineModuleInfo *MMI;
195 // All DIEValues are allocated through this allocator.
196 BumpPtrAllocator DIEValueAllocator;
198 // Maps MDNode with its corresponding DwarfCompileUnit.
199 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
201 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
202 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
204 // Maps a CU DIE with its corresponding DwarfCompileUnit.
205 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
207 // List of all labels used in aranges generation.
208 std::vector<SymbolCU> ArangeLabels;
210 // Size of each symbol emitted (for those symbols that have a specific size).
211 DenseMap<const MCSymbol *, uint64_t> SymSize;
213 LexicalScopes LScopes;
215 // Collection of abstract variables.
216 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
217 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
219 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
220 // can refer to them in spite of insertions into this list.
221 SmallVector<DebugLocList, 4> DotDebugLocEntries;
223 // This is a collection of subprogram MDNodes that are processed to
225 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
227 // Maps instruction with label emitted before instruction.
228 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
230 // Maps instruction with label emitted after instruction.
231 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
233 // History of DBG_VALUE and clobber instructions for each user variable.
234 // Variables are listed in order of appearance.
235 DbgValueHistoryMap DbgValues;
237 // Previous instruction's location information. This is used to determine
238 // label location to indicate scope boundries in dwarf debug info.
239 DebugLoc PrevInstLoc;
242 // This location indicates end of function prologue and beginning of function
244 DebugLoc PrologEndLoc;
246 // If nonnull, stores the current machine function we're processing.
247 const MachineFunction *CurFn;
249 // If nonnull, stores the current machine instruction we're processing.
250 const MachineInstr *CurMI;
252 // If nonnull, stores the CU in which the previous subprogram was contained.
253 const DwarfCompileUnit *PrevCU;
255 // As an optimization, there is no need to emit an entry in the directory
256 // table for the same directory as DW_AT_comp_dir.
257 StringRef CompilationDir;
259 // Holder for the file specific debug information.
260 DwarfFile InfoHolder;
262 // Holders for the various debug information flags that we might need to
263 // have exposed. See accessor functions below for description.
265 // Holder for imported entities.
266 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
268 ImportedEntityMap ScopesWithImportedEntities;
270 // Map from MDNodes for user-defined types to the type units that describe
272 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
274 SmallVector<std::pair<std::unique_ptr<DwarfTypeUnit>, DICompositeType>, 1>
275 TypeUnitsUnderConstruction;
277 // Whether to emit the pubnames/pubtypes sections.
278 bool HasDwarfPubSections;
280 // Whether or not to use AT_ranges for compilation units.
283 // Whether we emitted a function into a section other than the default
285 bool UsedNonDefaultText;
287 // Whether to use the GNU TLS opcode (instead of the standard opcode).
288 bool UseGNUTLSOpcode;
290 // Version of dwarf we're emitting.
291 unsigned DwarfVersion;
293 // Maps from a type identifier to the actual MDNode.
294 DITypeIdentifierMap TypeIdentifierMap;
296 // DWARF5 Experimental Options
297 bool HasDwarfAccelTables;
300 // Separated Dwarf Variables
301 // In general these will all be for bits that are left in the
302 // original object file, rather than things that are meant
303 // to be in the .dwo sections.
305 // Holder for the skeleton information.
306 DwarfFile SkeletonHolder;
308 /// Store file names for type units under fission in a line table header that
309 /// will be emitted into debug_line.dwo.
310 // FIXME: replace this with a map from comp_dir to table so that we can emit
311 // multiple tables during LTO each of which uses directory 0, referencing the
312 // comp_dir of all the type units that use it.
313 MCDwarfDwoLineTable SplitTypeUnitFileTable;
315 // True iff there are multiple CUs in this module.
320 AddressPool AddrPool;
322 DwarfAccelTable AccelNames;
323 DwarfAccelTable AccelObjC;
324 DwarfAccelTable AccelNamespace;
325 DwarfAccelTable AccelTypes;
327 DenseMap<const Function *, DISubprogram> FunctionDIs;
329 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
331 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
332 return InfoHolder.getUnits();
335 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
337 /// \brief Find abstract variable associated with Var.
338 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
339 DIVariable &Cleansed);
340 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
341 void createAbstractVariable(const DIVariable &DV, LexicalScope *Scope);
342 void ensureAbstractVariableIsCreated(InlinedVariable Var,
343 const MDNode *Scope);
344 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
345 const MDNode *Scope);
347 /// \brief Construct a DIE for this abstract scope.
348 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
350 /// \brief Compute the size and offset of a DIE given an incoming Offset.
351 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
353 /// \brief Compute the size and offset of all the DIEs.
354 void computeSizeAndOffsets();
356 /// \brief Collect info for variables that were optimized out.
357 void collectDeadVariables();
359 void finishVariableDefinitions();
361 void finishSubprogramDefinitions();
363 /// \brief Finish off debug information after all functions have been
365 void finalizeModuleInfo();
367 /// \brief Emit the debug info section.
368 void emitDebugInfo();
370 /// \brief Emit the abbreviation section.
371 void emitAbbreviations();
373 /// \brief Emit a specified accelerator table.
374 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
375 StringRef TableName);
377 /// \brief Emit visible names into a hashed accelerator table section.
378 void emitAccelNames();
380 /// \brief Emit objective C classes and categories into a hashed
381 /// accelerator table section.
382 void emitAccelObjC();
384 /// \brief Emit namespace dies into a hashed accelerator table.
385 void emitAccelNamespaces();
387 /// \brief Emit type dies into a hashed accelerator table.
388 void emitAccelTypes();
390 /// \brief Emit visible names into a debug pubnames section.
391 /// \param GnuStyle determines whether or not we want to emit
392 /// additional information into the table ala newer gcc for gdb
394 void emitDebugPubNames(bool GnuStyle = false);
396 /// \brief Emit visible types into a debug pubtypes section.
397 /// \param GnuStyle determines whether or not we want to emit
398 /// additional information into the table ala newer gcc for gdb
400 void emitDebugPubTypes(bool GnuStyle = false);
402 void emitDebugPubSection(
403 bool GnuStyle, const MCSection *PSec, StringRef Name,
404 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
406 /// \brief Emit visible names into a debug str section.
409 /// \brief Emit visible names into a debug loc section.
412 /// \brief Emit visible names into a debug loc dwo section.
413 void emitDebugLocDWO();
415 /// \brief Emit visible names into a debug aranges section.
416 void emitDebugARanges();
418 /// \brief Emit visible names into a debug ranges section.
419 void emitDebugRanges();
421 /// \brief Emit inline info using custom format.
422 void emitDebugInlineInfo();
424 /// DWARF 5 Experimental Split Dwarf Emitters
426 /// \brief Initialize common features of skeleton units.
427 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
428 std::unique_ptr<DwarfUnit> NewU);
430 /// \brief Construct the split debug info compile unit for the debug info
432 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
434 /// \brief Construct the split debug info compile unit for the debug info
436 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
438 /// \brief Emit the debug info dwo section.
439 void emitDebugInfoDWO();
441 /// \brief Emit the debug abbrev dwo section.
442 void emitDebugAbbrevDWO();
444 /// \brief Emit the debug line dwo section.
445 void emitDebugLineDWO();
447 /// \brief Emit the debug str dwo section.
448 void emitDebugStrDWO();
450 /// Flags to let the linker know we have emitted new style pubnames. Only
451 /// emit it here if we don't have a skeleton CU for split dwarf.
452 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
454 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
455 /// DW_TAG_compile_unit.
456 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
458 /// \brief Construct imported_module or imported_declaration DIE.
459 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
462 /// \brief Register a source line with debug info. Returns the unique
463 /// label that was emitted and which provides correspondence to the
464 /// source line list.
465 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
468 /// \brief Indentify instructions that are marking the beginning of or
469 /// ending of a scope.
470 void identifyScopeMarkers();
472 /// \brief Populate LexicalScope entries with variables' info.
473 void collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
474 DenseSet<InlinedVariable> &ProcessedVars);
476 /// \brief Build the location list for all DBG_VALUEs in the
477 /// function that describe the same variable.
478 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
479 const DbgValueHistoryMap::InstrRanges &Ranges);
481 /// \brief Collect variable information from the side table maintained
483 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
485 /// \brief Ensure that a label will be emitted before MI.
486 void requestLabelBeforeInsn(const MachineInstr *MI) {
487 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
490 /// \brief Ensure that a label will be emitted after MI.
491 void requestLabelAfterInsn(const MachineInstr *MI) {
492 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
496 //===--------------------------------------------------------------------===//
497 // Main entry points.
499 DwarfDebug(AsmPrinter *A, Module *M);
501 ~DwarfDebug() override;
503 /// \brief Emit all Dwarf sections that should come prior to the
507 /// \brief Emit all Dwarf sections that should come after the content.
508 void endModule() override;
510 /// \brief Gather pre-function debug information.
511 void beginFunction(const MachineFunction *MF) override;
513 /// \brief Gather and emit post-function debug information.
514 void endFunction(const MachineFunction *MF) override;
516 /// \brief Process beginning of an instruction.
517 void beginInstruction(const MachineInstr *MI) override;
519 /// \brief Process end of an instruction.
520 void endInstruction() override;
522 /// \brief Add a DIE to the set of types that we're going to pull into
524 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
525 DIE &Die, DICompositeType CTy);
527 /// \brief Add a label so that arange data can be generated for it.
528 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
530 /// \brief For symbols that have a size designated (e.g. common symbols),
531 /// this tracks that size.
532 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
536 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
537 /// standard DW_OP_form_tls_address opcode
538 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
540 // Experimental DWARF5 features.
542 /// \brief Returns whether or not to emit tables that dwarf consumers can
543 /// use to accelerate lookup.
544 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
546 /// \brief Returns whether or not to change the current debug info for the
547 /// split dwarf proposal support.
548 bool useSplitDwarf() const { return HasSplitDwarf; }
550 /// Returns the Dwarf Version.
551 unsigned getDwarfVersion() const { return DwarfVersion; }
553 /// Returns the previous CU that was being updated
554 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
555 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
557 /// Returns the entries for the .debug_loc section.
558 const SmallVectorImpl<DebugLocList> &
559 getDebugLocEntries() const {
560 return DotDebugLocEntries;
563 /// \brief Emit an entry for the debug loc section. This can be used to
564 /// handle an entry that's going to be emitted into the debug loc section.
565 void emitDebugLocEntry(ByteStreamer &Streamer,
566 const DebugLocEntry &Entry);
567 /// \brief emit a single value for the debug loc section.
568 void emitDebugLocValue(ByteStreamer &Streamer,
569 const DebugLocEntry::Value &Value,
570 unsigned PieceOffsetInBits = 0);
571 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
572 void emitLocPieces(ByteStreamer &Streamer,
573 const DITypeIdentifierMap &Map,
574 ArrayRef<DebugLocEntry::Value> Values);
576 /// Emit the location for a debug loc entry, including the size header.
577 void emitDebugLocEntryLocation(const DebugLocEntry &Entry);
579 /// Find the MDNode for the given reference.
580 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const {
581 return Ref.resolve(TypeIdentifierMap);
584 /// \brief Return the TypeIdentifierMap.
585 const DITypeIdentifierMap &getTypeIdentifierMap() const {
586 return TypeIdentifierMap;
589 /// Find the DwarfCompileUnit for the given CU Die.
590 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
591 return CUDieMap.lookup(CU);
593 /// isSubprogramContext - Return true if Context is either a subprogram
594 /// or another context nested inside a subprogram.
595 bool isSubprogramContext(const MDNode *Context);
597 void addSubprogramNames(DISubprogram SP, DIE &Die);
599 AddressPool &getAddressPool() { return AddrPool; }
601 void addAccelName(StringRef Name, const DIE &Die);
603 void addAccelObjC(StringRef Name, const DIE &Die);
605 void addAccelNamespace(StringRef Name, const DIE &Die);
607 void addAccelType(StringRef Name, const DIE &Die, char Flags);
609 const MachineFunction *getCurrentFunction() const { return CurFn; }
611 iterator_range<ImportedEntityMap::const_iterator>
612 findImportedEntitiesForScope(const MDNode *Scope) const {
613 return make_range(std::equal_range(
614 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
615 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
619 /// \brief A helper function to check whether the DIE for a given Scope is
620 /// going to be null.
621 bool isLexicalScopeDIENull(LexicalScope *Scope);
623 /// \brief Return Label preceding the instruction.
624 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
626 /// \brief Return Label immediately following the instruction.
627 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
629 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
631 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
632 return ProcessedSPNodes;
635 } // End of namespace llvm