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()->getInlinedAt()),
102 Expr(1, DbgValue->getDebugExpression()), TheDIE(nullptr),
103 DotDebugLocOffset(~0U), MInsn(DbgValue), DD(DD) {
104 FrameIndex.push_back(~0);
108 DIVariable getVariable() const { return Var; }
109 DILocation getInlinedAt() const { return IA; }
110 const ArrayRef<DIExpression> getExpression() const { return Expr; }
111 void setDIE(DIE &D) { TheDIE = &D; }
112 DIE *getDIE() const { return TheDIE; }
113 void setDotDebugLocOffset(unsigned O) { DotDebugLocOffset = O; }
114 unsigned getDotDebugLocOffset() const { return DotDebugLocOffset; }
115 StringRef getName() const { return Var->getName(); }
116 const MachineInstr *getMInsn() const { return MInsn; }
117 const ArrayRef<int> getFrameIndex() const { return FrameIndex; }
119 void addMMIEntry(const DbgVariable &V) {
120 assert( DotDebugLocOffset == ~0U && !MInsn && "not an MMI entry");
121 assert(V.DotDebugLocOffset == ~0U && !V.MInsn && "not an MMI entry");
122 assert(V.Var == Var && "conflicting DIVariable");
123 assert(V.IA == IA && "conflicting inlined-at location");
125 if (V.getFrameIndex().back() != ~0) {
126 auto E = V.getExpression();
127 auto FI = V.getFrameIndex();
128 Expr.append(E.begin(), E.end());
129 FrameIndex.append(FI.begin(), FI.end());
131 assert(Expr.size() > 1
132 ? std::all_of(Expr.begin(), Expr.end(),
133 [](DIExpression &E) { return E->isBitPiece(); })
134 : (true && "conflicting locations for variable"));
137 // Translate tag to proper Dwarf tag.
138 dwarf::Tag getTag() const {
139 if (Var->getTag() == dwarf::DW_TAG_arg_variable)
140 return dwarf::DW_TAG_formal_parameter;
142 return dwarf::DW_TAG_variable;
144 /// \brief Return true if DbgVariable is artificial.
145 bool isArtificial() const {
146 if (Var->isArtificial())
148 if (getType()->isArtificial())
153 bool isObjectPointer() const {
154 if (Var->isObjectPointer())
156 if (getType()->isObjectPointer())
161 bool variableHasComplexAddress() const {
162 assert(Var && "Invalid complex DbgVariable!");
163 assert(Expr.size() == 1 &&
164 "variableHasComplexAddress() invoked on multi-FI variable");
165 return Expr.back()->getNumElements() > 0;
167 bool isBlockByrefVariable() const;
168 DIType getType() const;
171 /// resolve - Look in the DwarfDebug map for the MDNode that
172 /// corresponds to the reference.
173 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const;
177 /// \brief Helper used to pair up a symbol and its DWARF compile unit.
179 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
181 DwarfCompileUnit *CU;
184 /// \brief Collects and handles dwarf debug information.
185 class DwarfDebug : public AsmPrinterHandler {
186 // Target of Dwarf emission.
189 // Collected machine module information.
190 MachineModuleInfo *MMI;
192 // All DIEValues are allocated through this allocator.
193 BumpPtrAllocator DIEValueAllocator;
195 // Maps MDNode with its corresponding DwarfCompileUnit.
196 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
198 // Maps subprogram MDNode with its corresponding DwarfCompileUnit.
199 MapVector<const MDNode *, DwarfCompileUnit *> SPMap;
201 // Maps a CU DIE with its corresponding DwarfCompileUnit.
202 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
204 // List of all labels used in aranges generation.
205 std::vector<SymbolCU> ArangeLabels;
207 // Size of each symbol emitted (for those symbols that have a specific size).
208 DenseMap<const MCSymbol *, uint64_t> SymSize;
210 LexicalScopes LScopes;
212 // Collection of abstract variables.
213 DenseMap<const MDNode *, std::unique_ptr<DbgVariable>> AbstractVariables;
214 SmallVector<std::unique_ptr<DbgVariable>, 64> ConcreteVariables;
216 // Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
217 // can refer to them in spite of insertions into this list.
218 SmallVector<DebugLocList, 4> DotDebugLocEntries;
220 // This is a collection of subprogram MDNodes that are processed to
222 SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
224 // Maps instruction with label emitted before instruction.
225 DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
227 // Maps instruction with label emitted after instruction.
228 DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
230 // History of DBG_VALUE and clobber instructions for each user variable.
231 // Variables are listed in order of appearance.
232 DbgValueHistoryMap DbgValues;
234 // Previous instruction's location information. This is used to determine
235 // label location to indicate scope boundries in dwarf debug info.
236 DebugLoc PrevInstLoc;
239 // This location indicates end of function prologue and beginning of function
241 DebugLoc PrologEndLoc;
243 // If nonnull, stores the current machine function we're processing.
244 const MachineFunction *CurFn;
246 // If nonnull, stores the current machine instruction we're processing.
247 const MachineInstr *CurMI;
249 // If nonnull, stores the CU in which the previous subprogram was contained.
250 const DwarfCompileUnit *PrevCU;
252 // As an optimization, there is no need to emit an entry in the directory
253 // table for the same directory as DW_AT_comp_dir.
254 StringRef CompilationDir;
256 // Holder for the file specific debug information.
257 DwarfFile InfoHolder;
259 // Holders for the various debug information flags that we might need to
260 // have exposed. See accessor functions below for description.
262 // Holder for imported entities.
263 typedef SmallVector<std::pair<const MDNode *, const MDNode *>, 32>
265 ImportedEntityMap ScopesWithImportedEntities;
267 // Map from MDNodes for user-defined types to the type units that describe
269 DenseMap<const MDNode *, const DwarfTypeUnit *> DwarfTypeUnits;
271 SmallVector<std::pair<std::unique_ptr<DwarfTypeUnit>, DICompositeType>, 1>
272 TypeUnitsUnderConstruction;
274 // Whether to emit the pubnames/pubtypes sections.
275 bool HasDwarfPubSections;
277 // Whether or not to use AT_ranges for compilation units.
280 // Whether we emitted a function into a section other than the default
282 bool UsedNonDefaultText;
284 // Whether to use the GNU TLS opcode (instead of the standard opcode).
285 bool UseGNUTLSOpcode;
287 // Version of dwarf we're emitting.
288 unsigned DwarfVersion;
290 // Maps from a type identifier to the actual MDNode.
291 DITypeIdentifierMap TypeIdentifierMap;
293 // DWARF5 Experimental Options
294 bool HasDwarfAccelTables;
297 // Separated Dwarf Variables
298 // In general these will all be for bits that are left in the
299 // original object file, rather than things that are meant
300 // to be in the .dwo sections.
302 // Holder for the skeleton information.
303 DwarfFile SkeletonHolder;
305 /// Store file names for type units under fission in a line table header that
306 /// will be emitted into debug_line.dwo.
307 // FIXME: replace this with a map from comp_dir to table so that we can emit
308 // multiple tables during LTO each of which uses directory 0, referencing the
309 // comp_dir of all the type units that use it.
310 MCDwarfDwoLineTable SplitTypeUnitFileTable;
312 // True iff there are multiple CUs in this module.
317 AddressPool AddrPool;
319 DwarfAccelTable AccelNames;
320 DwarfAccelTable AccelObjC;
321 DwarfAccelTable AccelNamespace;
322 DwarfAccelTable AccelTypes;
324 DenseMap<const Function *, DISubprogram> FunctionDIs;
326 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
328 const SmallVectorImpl<std::unique_ptr<DwarfUnit>> &getUnits() {
329 return InfoHolder.getUnits();
332 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
334 /// \brief Find abstract variable associated with Var.
335 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
336 DIVariable &Cleansed);
337 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
338 void createAbstractVariable(const DIVariable &DV, LexicalScope *Scope);
339 void ensureAbstractVariableIsCreated(InlinedVariable Var,
340 const MDNode *Scope);
341 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
342 const MDNode *Scope);
344 /// \brief Construct a DIE for this abstract scope.
345 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
347 /// \brief Compute the size and offset of a DIE given an incoming Offset.
348 unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
350 /// \brief Compute the size and offset of all the DIEs.
351 void computeSizeAndOffsets();
353 /// \brief Collect info for variables that were optimized out.
354 void collectDeadVariables();
356 void finishVariableDefinitions();
358 void finishSubprogramDefinitions();
360 /// \brief Finish off debug information after all functions have been
362 void finalizeModuleInfo();
364 /// \brief Emit the debug info section.
365 void emitDebugInfo();
367 /// \brief Emit the abbreviation section.
368 void emitAbbreviations();
370 /// \brief Emit a specified accelerator table.
371 void emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
372 StringRef TableName);
374 /// \brief Emit visible names into a hashed accelerator table section.
375 void emitAccelNames();
377 /// \brief Emit objective C classes and categories into a hashed
378 /// accelerator table section.
379 void emitAccelObjC();
381 /// \brief Emit namespace dies into a hashed accelerator table.
382 void emitAccelNamespaces();
384 /// \brief Emit type dies into a hashed accelerator table.
385 void emitAccelTypes();
387 /// \brief Emit visible names into a debug pubnames section.
388 /// \param GnuStyle determines whether or not we want to emit
389 /// additional information into the table ala newer gcc for gdb
391 void emitDebugPubNames(bool GnuStyle = false);
393 /// \brief Emit visible types into a debug pubtypes section.
394 /// \param GnuStyle determines whether or not we want to emit
395 /// additional information into the table ala newer gcc for gdb
397 void emitDebugPubTypes(bool GnuStyle = false);
399 void emitDebugPubSection(
400 bool GnuStyle, const MCSection *PSec, StringRef Name,
401 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
403 /// \brief Emit visible names into a debug str section.
406 /// \brief Emit visible names into a debug loc section.
409 /// \brief Emit visible names into a debug loc dwo section.
410 void emitDebugLocDWO();
412 /// \brief Emit visible names into a debug aranges section.
413 void emitDebugARanges();
415 /// \brief Emit visible names into a debug ranges section.
416 void emitDebugRanges();
418 /// \brief Emit inline info using custom format.
419 void emitDebugInlineInfo();
421 /// DWARF 5 Experimental Split Dwarf Emitters
423 /// \brief Initialize common features of skeleton units.
424 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
425 std::unique_ptr<DwarfUnit> NewU);
427 /// \brief Construct the split debug info compile unit for the debug info
429 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
431 /// \brief Construct the split debug info compile unit for the debug info
433 DwarfTypeUnit &constructSkeletonTU(DwarfTypeUnit &TU);
435 /// \brief Emit the debug info dwo section.
436 void emitDebugInfoDWO();
438 /// \brief Emit the debug abbrev dwo section.
439 void emitDebugAbbrevDWO();
441 /// \brief Emit the debug line dwo section.
442 void emitDebugLineDWO();
444 /// \brief Emit the debug str dwo section.
445 void emitDebugStrDWO();
447 /// Flags to let the linker know we have emitted new style pubnames. Only
448 /// emit it here if we don't have a skeleton CU for split dwarf.
449 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
451 /// \brief Create new DwarfCompileUnit for the given metadata node with tag
452 /// DW_TAG_compile_unit.
453 DwarfCompileUnit &constructDwarfCompileUnit(DICompileUnit DIUnit);
455 /// \brief Construct imported_module or imported_declaration DIE.
456 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
459 /// \brief Register a source line with debug info. Returns the unique
460 /// label that was emitted and which provides correspondence to the
461 /// source line list.
462 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
465 /// \brief Indentify instructions that are marking the beginning of or
466 /// ending of a scope.
467 void identifyScopeMarkers();
469 /// \brief Populate LexicalScope entries with variables' info.
470 void collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
471 DenseSet<InlinedVariable> &ProcessedVars);
473 /// \brief Build the location list for all DBG_VALUEs in the
474 /// function that describe the same variable.
475 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
476 const DbgValueHistoryMap::InstrRanges &Ranges);
478 /// \brief Collect variable information from the side table maintained
480 void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &P);
482 /// \brief Ensure that a label will be emitted before MI.
483 void requestLabelBeforeInsn(const MachineInstr *MI) {
484 LabelsBeforeInsn.insert(std::make_pair(MI, nullptr));
487 /// \brief Ensure that a label will be emitted after MI.
488 void requestLabelAfterInsn(const MachineInstr *MI) {
489 LabelsAfterInsn.insert(std::make_pair(MI, nullptr));
493 //===--------------------------------------------------------------------===//
494 // Main entry points.
496 DwarfDebug(AsmPrinter *A, Module *M);
498 ~DwarfDebug() override;
500 /// \brief Emit all Dwarf sections that should come prior to the
504 /// \brief Emit all Dwarf sections that should come after the content.
505 void endModule() override;
507 /// \brief Gather pre-function debug information.
508 void beginFunction(const MachineFunction *MF) override;
510 /// \brief Gather and emit post-function debug information.
511 void endFunction(const MachineFunction *MF) override;
513 /// \brief Process beginning of an instruction.
514 void beginInstruction(const MachineInstr *MI) override;
516 /// \brief Process end of an instruction.
517 void endInstruction() override;
519 /// \brief Add a DIE to the set of types that we're going to pull into
521 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
522 DIE &Die, DICompositeType CTy);
524 /// \brief Add a label so that arange data can be generated for it.
525 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
527 /// \brief For symbols that have a size designated (e.g. common symbols),
528 /// this tracks that size.
529 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
533 /// \brief Returns whether to use DW_OP_GNU_push_tls_address, instead of the
534 /// standard DW_OP_form_tls_address opcode
535 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
537 // Experimental DWARF5 features.
539 /// \brief Returns whether or not to emit tables that dwarf consumers can
540 /// use to accelerate lookup.
541 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
543 /// \brief Returns whether or not to change the current debug info for the
544 /// split dwarf proposal support.
545 bool useSplitDwarf() const { return HasSplitDwarf; }
547 /// Returns the Dwarf Version.
548 unsigned getDwarfVersion() const { return DwarfVersion; }
550 /// Returns the previous CU that was being updated
551 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
552 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
554 /// Returns the entries for the .debug_loc section.
555 const SmallVectorImpl<DebugLocList> &
556 getDebugLocEntries() const {
557 return DotDebugLocEntries;
560 /// \brief Emit an entry for the debug loc section. This can be used to
561 /// handle an entry that's going to be emitted into the debug loc section.
562 void emitDebugLocEntry(ByteStreamer &Streamer,
563 const DebugLocEntry &Entry);
564 /// \brief emit a single value for the debug loc section.
565 void emitDebugLocValue(ByteStreamer &Streamer,
566 const DebugLocEntry::Value &Value,
567 unsigned PieceOffsetInBits = 0);
568 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
569 void emitLocPieces(ByteStreamer &Streamer,
570 const DITypeIdentifierMap &Map,
571 ArrayRef<DebugLocEntry::Value> Values);
573 /// Emit the location for a debug loc entry, including the size header.
574 void emitDebugLocEntryLocation(const DebugLocEntry &Entry);
576 /// Find the MDNode for the given reference.
577 template <typename T> T *resolve(TypedDebugNodeRef<T> Ref) const {
578 return Ref.resolve(TypeIdentifierMap);
581 /// \brief Return the TypeIdentifierMap.
582 const DITypeIdentifierMap &getTypeIdentifierMap() const {
583 return TypeIdentifierMap;
586 /// Find the DwarfCompileUnit for the given CU Die.
587 DwarfCompileUnit *lookupUnit(const DIE *CU) const {
588 return CUDieMap.lookup(CU);
590 /// isSubprogramContext - Return true if Context is either a subprogram
591 /// or another context nested inside a subprogram.
592 bool isSubprogramContext(const MDNode *Context);
594 void addSubprogramNames(DISubprogram SP, DIE &Die);
596 AddressPool &getAddressPool() { return AddrPool; }
598 void addAccelName(StringRef Name, const DIE &Die);
600 void addAccelObjC(StringRef Name, const DIE &Die);
602 void addAccelNamespace(StringRef Name, const DIE &Die);
604 void addAccelType(StringRef Name, const DIE &Die, char Flags);
606 const MachineFunction *getCurrentFunction() const { return CurFn; }
608 iterator_range<ImportedEntityMap::const_iterator>
609 findImportedEntitiesForScope(const MDNode *Scope) const {
610 return make_range(std::equal_range(
611 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
612 std::pair<const MDNode *, const MDNode *>(Scope, nullptr),
616 /// \brief A helper function to check whether the DIE for a given Scope is
617 /// going to be null.
618 bool isLexicalScopeDIENull(LexicalScope *Scope);
620 /// \brief Return Label preceding the instruction.
621 MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
623 /// \brief Return Label immediately following the instruction.
624 MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
626 // FIXME: Sink these functions down into DwarfFile/Dwarf*Unit.
628 SmallPtrSet<const MDNode *, 16> &getProcessedSPNodes() {
629 return ProcessedSPNodes;
632 } // End of namespace llvm