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 "DbgValueHistoryCalculator.h"
18 #include "DebugHandlerBase.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/MapVector.h"
25 #include "llvm/ADT/SetVector.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"
36 #include "llvm/Target/TargetOptions.h"
46 class DwarfCompileUnit;
50 class MachineModuleInfo;
52 //===----------------------------------------------------------------------===//
53 /// This class is used to track local variable information.
55 /// Variables can be created from allocas, in which case they're generated from
56 /// the MMI table. Such variables can have multiple expressions and frame
59 /// Variables can be created from \c DBG_VALUE instructions. Those whose
60 /// location changes over time use \a DebugLocListIndex, while those with a
61 /// single instruction use \a MInsn and (optionally) a single entry of \a Expr.
63 /// Variables that have been optimized out use none of these fields.
65 const DILocalVariable *Var; /// Variable Descriptor.
66 const DILocation *IA; /// Inlined at location.
67 DIE *TheDIE = nullptr; /// Variable DIE.
68 unsigned DebugLocListIndex = ~0u; /// Offset in DebugLocs.
69 const MachineInstr *MInsn = nullptr; /// DBG_VALUE instruction.
71 struct FrameIndexExpr {
73 const DIExpression *Expr;
75 mutable SmallVector<FrameIndexExpr, 1>
76 FrameIndexExprs; /// Frame index + expression.
79 /// Construct a DbgVariable.
81 /// Creates a variable without any DW_AT_location. Call \a initializeMMI()
82 /// for MMI entries, or \a initializeDbgValue() for DBG_VALUE instructions.
83 DbgVariable(const DILocalVariable *V, const DILocation *IA)
86 /// Initialize from the MMI table.
87 void initializeMMI(const DIExpression *E, int FI) {
88 assert(FrameIndexExprs.empty() && "Already initialized?");
89 assert(!MInsn && "Already initialized?");
91 assert((!E || E->isValid()) && "Expected valid expression");
92 assert(~FI && "Expected valid index");
94 FrameIndexExprs.push_back({FI, E});
97 /// Initialize from a DBG_VALUE instruction.
98 void initializeDbgValue(const MachineInstr *DbgValue) {
99 assert(FrameIndexExprs.empty() && "Already initialized?");
100 assert(!MInsn && "Already initialized?");
102 assert(Var == DbgValue->getDebugVariable() && "Wrong variable");
103 assert(IA == DbgValue->getDebugLoc()->getInlinedAt() && "Wrong inlined-at");
106 if (auto *E = DbgValue->getDebugExpression())
107 if (E->getNumElements())
108 FrameIndexExprs.push_back({0, E});
112 const DILocalVariable *getVariable() const { return Var; }
113 const DILocation *getInlinedAt() const { return IA; }
114 const DIExpression *getSingleExpression() const {
115 assert(MInsn && FrameIndexExprs.size() <= 1);
116 return FrameIndexExprs.size() ? FrameIndexExprs[0].Expr : nullptr;
118 void setDIE(DIE &D) { TheDIE = &D; }
119 DIE *getDIE() const { return TheDIE; }
120 void setDebugLocListIndex(unsigned O) { DebugLocListIndex = O; }
121 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
122 StringRef getName() const { return Var->getName(); }
123 const MachineInstr *getMInsn() const { return MInsn; }
124 /// Get the FI entries, sorted by fragment offset.
125 ArrayRef<FrameIndexExpr> getFrameIndexExprs() const;
126 bool hasFrameIndexExprs() const { return !FrameIndexExprs.empty(); }
128 void addMMIEntry(const DbgVariable &V) {
129 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
130 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
131 assert(V.Var == Var && "conflicting variable");
132 assert(V.IA == IA && "conflicting inlined-at location");
134 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
135 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
137 FrameIndexExprs.append(V.FrameIndexExprs.begin(), V.FrameIndexExprs.end());
138 assert(all_of(FrameIndexExprs,
139 [](FrameIndexExpr &FIE) {
140 return FIE.Expr && FIE.Expr->isFragment();
142 "conflicting locations for variable");
145 // Translate tag to proper Dwarf tag.
146 dwarf::Tag getTag() const {
147 // FIXME: Why don't we just infer this tag and store it all along?
148 if (Var->isParameter())
149 return dwarf::DW_TAG_formal_parameter;
151 return dwarf::DW_TAG_variable;
153 /// Return true if DbgVariable is artificial.
154 bool isArtificial() const {
155 if (Var->isArtificial())
157 if (getType()->isArtificial())
162 bool isObjectPointer() const {
163 if (Var->isObjectPointer())
165 if (getType()->isObjectPointer())
170 bool hasComplexAddress() const {
171 assert(MInsn && "Expected DBG_VALUE, not MMI variable");
172 assert((FrameIndexExprs.empty() ||
173 (FrameIndexExprs.size() == 1 &&
174 FrameIndexExprs[0].Expr->getNumElements())) &&
175 "Invalid Expr for DBG_VALUE");
176 return !FrameIndexExprs.empty();
178 bool isBlockByrefVariable() const;
179 const DIType *getType() const;
182 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
183 return Ref.resolve();
188 /// Helper used to pair up a symbol and its DWARF compile unit.
190 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
192 DwarfCompileUnit *CU;
195 /// Collects and handles dwarf debug information.
196 class DwarfDebug : public DebugHandlerBase {
197 /// All DIEValues are allocated through this allocator.
198 BumpPtrAllocator DIEValueAllocator;
200 /// Maps MDNode with its corresponding DwarfCompileUnit.
201 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
203 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
204 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
206 /// List of all labels used in aranges generation.
207 std::vector<SymbolCU> ArangeLabels;
209 /// Size of each symbol emitted (for those symbols that have a specific size).
210 DenseMap<const MCSymbol *, uint64_t> SymSize;
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 DebugLocStream DebugLocs;
220 /// This is a collection of subprogram MDNodes that are processed to
222 SetVector<const DISubprogram *, SmallVector<const DISubprogram *, 16>,
223 SmallPtrSet<const DISubprogram *, 16>>
226 /// If nonnull, stores the current machine function we're processing.
227 const MachineFunction *CurFn;
229 /// If nonnull, stores the CU in which the previous subprogram was contained.
230 const DwarfCompileUnit *PrevCU;
232 /// As an optimization, there is no need to emit an entry in the directory
233 /// table for the same directory as DW_AT_comp_dir.
234 StringRef CompilationDir;
236 /// Holder for the file specific debug information.
237 DwarfFile InfoHolder;
239 /// Holders for the various debug information flags that we might need to
240 /// have exposed. See accessor functions below for description.
242 /// Map from MDNodes for user-defined types to their type signatures. Also
243 /// used to keep track of which types we have emitted type units for.
244 DenseMap<const MDNode *, uint64_t> TypeSignatures;
247 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
248 TypeUnitsUnderConstruction;
250 /// Whether to emit the pubnames/pubtypes sections.
251 bool HasDwarfPubSections;
253 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
254 bool UseGNUTLSOpcode;
256 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
257 bool UseDWARF2Bitfields;
259 /// Whether to emit all linkage names, or just abstract subprograms.
260 bool UseAllLinkageNames;
262 /// DWARF5 Experimental Options
264 bool HasDwarfAccelTables;
265 bool HasAppleExtensionAttributes;
268 /// Separated Dwarf Variables
269 /// In general these will all be for bits that are left in the
270 /// original object file, rather than things that are meant
271 /// to be in the .dwo sections.
273 /// Holder for the skeleton information.
274 DwarfFile SkeletonHolder;
276 /// Store file names for type units under fission in a line table
277 /// header that will be emitted into debug_line.dwo.
278 // FIXME: replace this with a map from comp_dir to table so that we
279 // can emit multiple tables during LTO each of which uses directory
280 // 0, referencing the comp_dir of all the type units that use it.
281 MCDwarfDwoLineTable SplitTypeUnitFileTable;
284 /// True iff there are multiple CUs in this module.
288 AddressPool AddrPool;
290 DwarfAccelTable AccelNames;
291 DwarfAccelTable AccelObjC;
292 DwarfAccelTable AccelNamespace;
293 DwarfAccelTable AccelTypes;
295 // Identify a debugger for "tuning" the debug info.
296 DebuggerKind DebuggerTuning;
298 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
300 /// Returns whether we are "tuning" for a given debugger.
301 /// Should be used only within the constructor, to set feature flags.
303 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
304 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
305 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
308 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
310 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
311 return InfoHolder.getUnits();
314 typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
316 /// Find abstract variable associated with Var.
317 DbgVariable *getExistingAbstractVariable(InlinedVariable IV,
318 const DILocalVariable *&Cleansed);
319 DbgVariable *getExistingAbstractVariable(InlinedVariable IV);
320 void createAbstractVariable(const DILocalVariable *DV, LexicalScope *Scope);
321 void ensureAbstractVariableIsCreated(InlinedVariable Var,
322 const MDNode *Scope);
323 void ensureAbstractVariableIsCreatedIfScoped(InlinedVariable Var,
324 const MDNode *Scope);
326 DbgVariable *createConcreteVariable(LexicalScope &Scope, InlinedVariable IV);
328 /// Construct a DIE for this abstract scope.
329 void constructAbstractSubprogramScopeDIE(LexicalScope *Scope);
331 void finishVariableDefinitions();
333 void finishSubprogramDefinitions();
335 /// Finish off debug information after all functions have been
337 void finalizeModuleInfo();
339 /// Emit the debug info section.
340 void emitDebugInfo();
342 /// Emit the abbreviation section.
343 void emitAbbreviations();
345 /// Emit a specified accelerator table.
346 void emitAccel(DwarfAccelTable &Accel, MCSection *Section,
347 StringRef TableName);
349 /// Emit visible names into a hashed accelerator table section.
350 void emitAccelNames();
352 /// Emit objective C classes and categories into a hashed
353 /// accelerator table section.
354 void emitAccelObjC();
356 /// Emit namespace dies into a hashed accelerator table.
357 void emitAccelNamespaces();
359 /// Emit type dies into a hashed accelerator table.
360 void emitAccelTypes();
362 /// Emit visible names into a debug pubnames section.
363 /// \param GnuStyle determines whether or not we want to emit
364 /// additional information into the table ala newer gcc for gdb
366 void emitDebugPubNames(bool GnuStyle = false);
368 /// Emit visible types into a debug pubtypes section.
369 /// \param GnuStyle determines whether or not we want to emit
370 /// additional information into the table ala newer gcc for gdb
372 void emitDebugPubTypes(bool GnuStyle = false);
374 void emitDebugPubSection(
375 bool GnuStyle, MCSection *PSec, StringRef Name,
376 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const);
378 /// Emit null-terminated strings into a debug str section.
381 /// Emit variable locations into a debug loc section.
384 /// Emit variable locations into a debug loc dwo section.
385 void emitDebugLocDWO();
387 /// Emit address ranges into a debug aranges section.
388 void emitDebugARanges();
390 /// Emit address ranges into a debug ranges section.
391 void emitDebugRanges();
393 /// Emit macros into a debug macinfo section.
394 void emitDebugMacinfo();
395 void emitMacro(DIMacro &M);
396 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
397 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
399 /// DWARF 5 Experimental Split Dwarf Emitters
401 /// Initialize common features of skeleton units.
402 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
403 std::unique_ptr<DwarfCompileUnit> NewU);
405 /// Construct the split debug info compile unit for the debug info
407 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
409 /// Emit the debug info dwo section.
410 void emitDebugInfoDWO();
412 /// Emit the debug abbrev dwo section.
413 void emitDebugAbbrevDWO();
415 /// Emit the debug line dwo section.
416 void emitDebugLineDWO();
418 /// Emit the debug str dwo section.
419 void emitDebugStrDWO();
421 /// Flags to let the linker know we have emitted new style pubnames. Only
422 /// emit it here if we don't have a skeleton CU for split dwarf.
423 void addGnuPubAttributes(DwarfUnit &U, DIE &D) const;
425 /// Create new DwarfCompileUnit for the given metadata node with tag
426 /// DW_TAG_compile_unit.
427 DwarfCompileUnit &constructDwarfCompileUnit(const DICompileUnit *DIUnit);
429 /// Construct imported_module or imported_declaration DIE.
430 void constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
431 const DIImportedEntity *N);
433 /// Register a source line with debug info. Returns the unique
434 /// label that was emitted and which provides correspondence to the
435 /// source line list.
436 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
439 /// Populate LexicalScope entries with variables' info.
440 void collectVariableInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
441 DenseSet<InlinedVariable> &ProcessedVars);
443 /// Build the location list for all DBG_VALUEs in the
444 /// function that describe the same variable.
445 void buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
446 const DbgValueHistoryMap::InstrRanges &Ranges);
448 /// Collect variable information from the side table maintained by MF.
449 void collectVariableInfoFromMFTable(DenseSet<InlinedVariable> &P);
452 //===--------------------------------------------------------------------===//
453 // Main entry points.
455 DwarfDebug(AsmPrinter *A, Module *M);
457 ~DwarfDebug() override;
459 /// Emit all Dwarf sections that should come prior to the
463 /// Emit all Dwarf sections that should come after the content.
464 void endModule() override;
466 /// Gather pre-function debug information.
467 void beginFunction(const MachineFunction *MF) override;
469 /// Gather and emit post-function debug information.
470 void endFunction(const MachineFunction *MF) override;
472 /// Process beginning of an instruction.
473 void beginInstruction(const MachineInstr *MI) override;
475 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
476 static uint64_t makeTypeSignature(StringRef Identifier);
478 /// Add a DIE to the set of types that we're going to pull into
480 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
481 DIE &Die, const DICompositeType *CTy);
483 /// Add a label so that arange data can be generated for it.
484 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(SCU); }
486 /// For symbols that have a size designated (e.g. common symbols),
487 /// this tracks that size.
488 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
492 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
493 /// If not, we still might emit certain cases.
494 bool useAllLinkageNames() const { return UseAllLinkageNames; }
496 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
497 /// standard DW_OP_form_tls_address opcode
498 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
500 /// Returns whether to use the DWARF2 format for bitfields instyead of the
502 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
504 // Experimental DWARF5 features.
506 /// Returns whether or not to emit tables that dwarf consumers can
507 /// use to accelerate lookup.
508 bool useDwarfAccelTables() const { return HasDwarfAccelTables; }
510 bool useAppleExtensionAttributes() const {
511 return HasAppleExtensionAttributes;
514 /// Returns whether or not to change the current debug info for the
515 /// split dwarf proposal support.
516 bool useSplitDwarf() const { return HasSplitDwarf; }
518 /// Returns the Dwarf Version.
519 uint16_t getDwarfVersion() const;
521 /// Returns the previous CU that was being updated
522 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
523 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
525 /// Returns the entries for the .debug_loc section.
526 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
528 /// Emit an entry for the debug loc section. This can be used to
529 /// handle an entry that's going to be emitted into the debug loc section.
530 void emitDebugLocEntry(ByteStreamer &Streamer,
531 const DebugLocStream::Entry &Entry);
533 /// Emit the location for a debug loc entry, including the size header.
534 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry);
536 /// Find the MDNode for the given reference.
537 template <typename T> T *resolve(TypedDINodeRef<T> Ref) const {
538 return Ref.resolve();
541 void addSubprogramNames(const DISubprogram *SP, DIE &Die);
543 AddressPool &getAddressPool() { return AddrPool; }
545 void addAccelName(StringRef Name, const DIE &Die);
547 void addAccelObjC(StringRef Name, const DIE &Die);
549 void addAccelNamespace(StringRef Name, const DIE &Die);
551 void addAccelType(StringRef Name, const DIE &Die, char Flags);
553 const MachineFunction *getCurrentFunction() const { return CurFn; }
555 /// A helper function to check whether the DIE for a given Scope is
556 /// going to be null.
557 bool isLexicalScopeDIENull(LexicalScope *Scope);
559 } // End of namespace llvm