1//===- llvm/CodeGen/DwarfDebug.h - Dwarf Debug Framework --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing dwarf debug info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
15
16#include "AddressPool.h"
17#include "DebugLocEntry.h"
18#include "DebugLocStream.h"
19#include "DwarfFile.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/BinaryFormat/Dwarf.h"
29#include "llvm/CodeGen/AccelTable.h"
30#include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
31#include "llvm/CodeGen/DebugHandlerBase.h"
32#include "llvm/IR/DebugInfoMetadata.h"
33#include "llvm/IR/DebugLoc.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/MC/MCDwarf.h"
36#include "llvm/Support/Allocator.h"
37#include "llvm/Target/TargetOptions.h"
38#include <cassert>
39#include <cstdint>
40#include <limits>
41#include <memory>
42#include <utility>
43#include <variant>
44#include <vector>
45
46namespace llvm {
47
48class AsmPrinter;
49class ByteStreamer;
50class DIE;
51class DwarfCompileUnit;
52class DwarfExpression;
53class DwarfTypeUnit;
54class DwarfUnit;
55class LexicalScope;
56class MachineFunction;
57class MCSection;
58class MCSymbol;
59class Module;
60
61//===----------------------------------------------------------------------===//
62/// This class is defined as the common parent of DbgVariable and DbgLabel
63/// such that it could levarage polymorphism to extract common code for
64/// DbgVariable and DbgLabel.
65class DbgEntity {
66public:
67 enum DbgEntityKind {
68 DbgVariableKind,
69 DbgLabelKind
70 };
71
72private:
73 const DINode *Entity;
74 const DILocation *InlinedAt;
75 DIE *TheDIE = nullptr;
76 const DbgEntityKind SubclassID;
77
78public:
79 DbgEntity(const DINode *N, const DILocation *IA, DbgEntityKind ID)
80 : Entity(N), InlinedAt(IA), SubclassID(ID) {}
81 virtual ~DbgEntity() = default;
82
83 /// Accessors.
84 /// @{
85 const DINode *getEntity() const { return Entity; }
86 const DILocation *getInlinedAt() const { return InlinedAt; }
87 DIE *getDIE() const { return TheDIE; }
88 DbgEntityKind getDbgEntityID() const { return SubclassID; }
89 /// @}
90
91 void setDIE(DIE &D) { TheDIE = &D; }
92
93 static bool classof(const DbgEntity *N) {
94 switch (N->getDbgEntityID()) {
95 case DbgVariableKind:
96 case DbgLabelKind:
97 return true;
98 }
99 llvm_unreachable("Invalid DbgEntityKind");
100 }
101};
102
103class DbgVariable;
104
105bool operator<(const struct FrameIndexExpr &LHS,
106 const struct FrameIndexExpr &RHS);
107bool operator<(const struct EntryValueInfo &LHS,
108 const struct EntryValueInfo &RHS);
109
110/// Proxy for one MMI entry.
111struct FrameIndexExpr {
112 int FI;
113 const DIExpression *Expr;
114
115 /// Operator enabling sorting based on fragment offset.
116 friend bool operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS);
117};
118
119/// Represents an entry-value location, or a fragment of one.
120struct EntryValueInfo {
121 MCRegister Reg;
122 const DIExpression &Expr;
123
124 /// Operator enabling sorting based on fragment offset.
125 friend bool operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS);
126};
127
128// Namespace for alternatives of a DbgVariable.
129namespace Loc {
130/// Single value location description.
131class Single {
132 std::unique_ptr<DbgValueLoc> ValueLoc;
133 const DIExpression *Expr;
134
135public:
136 explicit Single(DbgValueLoc ValueLoc);
137 explicit Single(const MachineInstr *DbgValue);
138 const DbgValueLoc &getValueLoc() const { return *ValueLoc; }
139 const DIExpression *getExpr() const { return Expr; }
140};
141/// Multi-value location description.
142class Multi {
143 /// Index of the entry list in DebugLocs.
144 unsigned DebugLocListIndex;
145 /// DW_OP_LLVM_tag_offset value from DebugLocs.
146 std::optional<uint8_t> DebugLocListTagOffset;
147
148public:
149 explicit Multi(unsigned DebugLocListIndex,
150 std::optional<uint8_t> DebugLocListTagOffset)
151 : DebugLocListIndex(DebugLocListIndex),
152 DebugLocListTagOffset(DebugLocListTagOffset) {}
153 unsigned getDebugLocListIndex() const { return DebugLocListIndex; }
154 std::optional<uint8_t> getDebugLocListTagOffset() const {
155 return DebugLocListTagOffset;
156 }
157};
158/// Single location defined by (potentially multiple) MMI entries.
159struct MMI {
160 std::set<FrameIndexExpr> FrameIndexExprs;
161
162public:
163 explicit MMI(const DIExpression *E, int FI) : FrameIndexExprs({{.FI: FI, .Expr: E}}) {
164 assert((!E || E->isValid()) && "Expected valid expression");
165 assert(FI != std::numeric_limits<int>::max() && "Expected valid index");
166 }
167 void addFrameIndexExpr(const DIExpression *Expr, int FI);
168 /// Get the FI entries, sorted by fragment offset.
169 const std::set<FrameIndexExpr> &getFrameIndexExprs() const;
170};
171/// Single location defined by (potentially multiple) EntryValueInfo.
172struct EntryValue {
173 std::set<EntryValueInfo> EntryValues;
174 explicit EntryValue(MCRegister Reg, const DIExpression &Expr) {
175 addExpr(Reg, Expr);
176 };
177 // Add the pair Reg, Expr to the list of entry values describing the variable.
178 // If multiple expressions are added, it is the callers responsibility to
179 // ensure they are all non-overlapping fragments.
180 void addExpr(MCRegister Reg, const DIExpression &Expr) {
181 std::optional<const DIExpression *> NonVariadicExpr =
182 DIExpression::convertToNonVariadicExpression(Expr: &Expr);
183 assert(NonVariadicExpr && *NonVariadicExpr);
184
185 EntryValues.insert(x: {.Reg: Reg, .Expr: **NonVariadicExpr});
186 }
187};
188/// Alias for the std::variant specialization base class of DbgVariable.
189using Variant = std::variant<std::monostate, Loc::Single, Loc::Multi, Loc::MMI,
190 Loc::EntryValue>;
191} // namespace Loc
192
193//===----------------------------------------------------------------------===//
194/// This class is used to track local variable information.
195///
196/// Variables that have been optimized out hold the \c monostate alternative.
197/// This is not distinguished from the case of a constructed \c DbgVariable
198/// which has not be initialized yet.
199///
200/// Variables can be created from allocas, in which case they're generated from
201/// the MMI table. Such variables hold the \c Loc::MMI alternative which can
202/// have multiple expressions and frame indices.
203///
204/// Variables can be created from the entry value of registers, in which case
205/// they're generated from the MMI table. Such variables hold the \c
206/// EntryValueLoc alternative which can either have a single expression or
207/// multiple *fragment* expressions.
208///
209/// Variables can be created from \c DBG_VALUE instructions. Those whose
210/// location changes over time hold a \c Loc::Multi alternative which uses \c
211/// DebugLocListIndex and (optionally) \c DebugLocListTagOffset, while those
212/// with a single location hold a \c Loc::Single alternative which use \c
213/// ValueLoc and (optionally) a single \c Expr.
214class DbgVariable : public DbgEntity, public Loc::Variant {
215
216public:
217 /// To workaround P2162R0 https://github.com/cplusplus/papers/issues/873 the
218 /// base class subobject needs to be passed directly to std::visit, so expose
219 /// it directly here.
220 Loc::Variant &asVariant() { return *static_cast<Loc::Variant *>(this); }
221 const Loc::Variant &asVariant() const {
222 return *static_cast<const Loc::Variant *>(this);
223 }
224 /// Member shorthand for std::holds_alternative
225 template <typename T> bool holds() const {
226 return std::holds_alternative<T>(*this);
227 }
228 /// Asserting, noexcept member alternative to std::get
229 template <typename T> auto &get() noexcept {
230 assert(holds<T>());
231 return *std::get_if<T>(this);
232 }
233 /// Asserting, noexcept member alternative to std::get
234 template <typename T> const auto &get() const noexcept {
235 assert(holds<T>());
236 return *std::get_if<T>(this);
237 }
238
239 /// Construct a DbgVariable.
240 ///
241 /// Creates a variable without any DW_AT_location.
242 DbgVariable(const DILocalVariable *V, const DILocation *IA)
243 : DbgEntity(V, IA, DbgVariableKind) {}
244
245 // Accessors.
246 const DILocalVariable *getVariable() const {
247 return cast<DILocalVariable>(Val: getEntity());
248 }
249
250 StringRef getName() const { return getVariable()->getName(); }
251
252 // Translate tag to proper Dwarf tag.
253 dwarf::Tag getTag() const {
254 // FIXME: Why don't we just infer this tag and store it all along?
255 if (getVariable()->isParameter())
256 return dwarf::DW_TAG_formal_parameter;
257
258 return dwarf::DW_TAG_variable;
259 }
260
261 /// Return true if DbgVariable is artificial.
262 bool isArtificial() const {
263 if (getVariable()->isArtificial())
264 return true;
265 if (getType()->isArtificial())
266 return true;
267 return false;
268 }
269
270 bool isObjectPointer() const {
271 if (getVariable()->isObjectPointer())
272 return true;
273 if (getType()->isObjectPointer())
274 return true;
275 return false;
276 }
277
278 const DIType *getType() const;
279
280 static bool classof(const DbgEntity *N) {
281 return N->getDbgEntityID() == DbgVariableKind;
282 }
283};
284
285//===----------------------------------------------------------------------===//
286/// This class is used to track label information.
287///
288/// Labels are collected from \c DBG_LABEL instructions.
289class DbgLabel : public DbgEntity {
290 const MCSymbol *Sym; /// Symbol before DBG_LABEL instruction.
291
292public:
293 /// We need MCSymbol information to generate DW_AT_low_pc.
294 DbgLabel(const DILabel *L, const DILocation *IA, const MCSymbol *Sym = nullptr)
295 : DbgEntity(L, IA, DbgLabelKind), Sym(Sym) {}
296
297 /// Accessors.
298 /// @{
299 const DILabel *getLabel() const { return cast<DILabel>(Val: getEntity()); }
300 const MCSymbol *getSymbol() const { return Sym; }
301
302 StringRef getName() const { return getLabel()->getName(); }
303 /// @}
304
305 /// Translate tag to proper Dwarf tag.
306 dwarf::Tag getTag() const {
307 return dwarf::DW_TAG_label;
308 }
309
310 static bool classof(const DbgEntity *N) {
311 return N->getDbgEntityID() == DbgLabelKind;
312 }
313};
314
315/// Used for tracking debug info about call site parameters.
316class DbgCallSiteParam {
317private:
318 unsigned Register; ///< Parameter register at the callee entry point.
319 DbgValueLoc Value; ///< Corresponding location for the parameter value at
320 ///< the call site.
321public:
322 DbgCallSiteParam(unsigned Reg, DbgValueLoc Val)
323 : Register(Reg), Value(Val) {
324 assert(Reg && "Parameter register cannot be undef");
325 }
326
327 unsigned getRegister() const { return Register; }
328 DbgValueLoc getValue() const { return Value; }
329};
330
331/// Collection used for storing debug call site parameters.
332using ParamSet = SmallVector<DbgCallSiteParam, 4>;
333
334/// Helper used to pair up a symbol and its DWARF compile unit.
335struct SymbolCU {
336 SymbolCU(DwarfCompileUnit *CU, const MCSymbol *Sym) : Sym(Sym), CU(CU) {}
337
338 const MCSymbol *Sym;
339 DwarfCompileUnit *CU;
340};
341
342/// The kind of accelerator tables we should emit.
343enum class AccelTableKind {
344 Default, ///< Platform default.
345 None, ///< None.
346 Apple, ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
347 Dwarf, ///< DWARF v5 .debug_names.
348};
349
350/// Collects and handles dwarf debug information.
351class DwarfDebug : public DebugHandlerBase {
352 /// All DIEValues are allocated through this allocator.
353 BumpPtrAllocator DIEValueAllocator;
354
355 /// Maps MDNode with its corresponding DwarfCompileUnit.
356 MapVector<const MDNode *, DwarfCompileUnit *> CUMap;
357
358 /// Maps a CU DIE with its corresponding DwarfCompileUnit.
359 DenseMap<const DIE *, DwarfCompileUnit *> CUDieMap;
360
361 /// List of all labels used in aranges generation.
362 std::vector<SymbolCU> ArangeLabels;
363
364 /// Size of each symbol emitted (for those symbols that have a specific size).
365 DenseMap<const MCSymbol *, uint64_t> SymSize;
366
367 /// Collection of abstract variables/labels.
368 SmallVector<std::unique_ptr<DbgEntity>, 64> ConcreteEntities;
369
370 /// Collection of DebugLocEntry. Stored in a linked list so that DIELocLists
371 /// can refer to them in spite of insertions into this list.
372 DebugLocStream DebugLocs;
373
374 /// This is a collection of subprogram MDNodes that are processed to
375 /// create DIEs.
376 SmallSetVector<const DISubprogram *, 16> ProcessedSPNodes;
377
378 /// Map function-local imported entities to their parent local scope
379 /// (either DILexicalBlock or DISubprogram) for a processed function
380 /// (including inlined subprograms).
381 using MDNodeSet = SetVector<const MDNode *, SmallVector<const MDNode *, 2>,
382 SmallPtrSet<const MDNode *, 2>>;
383 DenseMap<const DILocalScope *, MDNodeSet> LocalDeclsPerLS;
384
385 SmallDenseSet<const MachineInstr *> ForceIsStmtInstrs;
386
387 /// If nonnull, stores the current machine function we're processing.
388 const MachineFunction *CurFn = nullptr;
389
390 /// If nonnull, stores the CU in which the previous subprogram was contained.
391 const DwarfCompileUnit *PrevCU = nullptr;
392
393 /// As an optimization, there is no need to emit an entry in the directory
394 /// table for the same directory as DW_AT_comp_dir.
395 StringRef CompilationDir;
396
397 /// Holders for the various debug information flags that we might need to
398 /// have exposed. See accessor functions below for description.
399
400 /// Map from MDNodes for user-defined types to their type signatures. Also
401 /// used to keep track of which types we have emitted type units for.
402 DenseMap<const MDNode *, uint64_t> TypeSignatures;
403
404 DenseMap<const MCSection *, const MCSymbol *> SectionLabels;
405
406 SmallVector<
407 std::pair<std::unique_ptr<DwarfTypeUnit>, const DICompositeType *>, 1>
408 TypeUnitsUnderConstruction;
409
410 /// Symbol pointing to the current function's DWARF line table entries.
411 MCSymbol *FunctionLineTableLabel;
412
413 /// Used to set a uniqe ID for a Type Unit.
414 /// This counter represents number of DwarfTypeUnits created, not necessarily
415 /// number of type units that will be emitted.
416 unsigned NumTypeUnitsCreated = 0;
417
418 /// Whether to use the GNU TLS opcode (instead of the standard opcode).
419 bool UseGNUTLSOpcode;
420
421 /// Whether to use DWARF 2 bitfields (instead of the DWARF 4 format).
422 bool UseDWARF2Bitfields;
423
424 /// Whether to emit all linkage names, or just abstract subprograms.
425 bool UseAllLinkageNames;
426
427 /// Use inlined strings.
428 bool UseInlineStrings = false;
429
430 /// Allow emission of .debug_ranges section.
431 bool UseRangesSection = true;
432
433 /// True if the sections itself must be used as references and don't create
434 /// temp symbols inside DWARF sections.
435 bool UseSectionsAsReferences = false;
436
437 /// Allow emission of .debug_aranges section
438 bool UseARangesSection = false;
439
440 /// Generate DWARF v4 type units.
441 bool GenerateTypeUnits;
442
443 /// Emit a .debug_macro section instead of .debug_macinfo.
444 bool UseDebugMacroSection;
445
446 /// Avoid using DW_OP_convert due to consumer incompatibilities.
447 bool EnableOpConvert;
448
449public:
450 enum class MinimizeAddrInV5 {
451 Default,
452 Disabled,
453 Ranges,
454 Expressions,
455 Form,
456 };
457
458 enum class DWARF5AccelTableKind {
459 CU = 0,
460 TU = 1,
461 };
462
463private:
464 /// Instructions which should get is_stmt applied because they implement key
465 /// functionality for a source atom.
466 SmallDenseSet<const MachineInstr *> KeyInstructions;
467
468 /// Force the use of DW_AT_ranges even for single-entry range lists.
469 MinimizeAddrInV5 MinimizeAddr = MinimizeAddrInV5::Disabled;
470
471 /// DWARF5 Experimental Options
472 /// @{
473 AccelTableKind TheAccelTableKind;
474 bool HasAppleExtensionAttributes;
475 bool HasSplitDwarf;
476
477 /// Whether to generate the DWARF v5 string offsets table.
478 /// It consists of a series of contributions, each preceded by a header.
479 /// The pre-DWARF v5 string offsets table for split dwarf is, in contrast,
480 /// a monolithic sequence of string offsets.
481 bool UseSegmentedStringOffsetsTable;
482
483 /// Enable production of call site parameters needed to print the debug entry
484 /// values. Useful for testing purposes when a debugger does not support the
485 /// feature yet.
486 bool EmitDebugEntryValues;
487
488 /// Separated Dwarf Variables
489 /// In general these will all be for bits that are left in the
490 /// original object file, rather than things that are meant
491 /// to be in the .dwo sections.
492
493 /// Holder for the skeleton information.
494 DwarfFile SkeletonHolder;
495
496 /// Store file names for type units under fission in a line table
497 /// header that will be emitted into debug_line.dwo.
498 // FIXME: replace this with a map from comp_dir to table so that we
499 // can emit multiple tables during LTO each of which uses directory
500 // 0, referencing the comp_dir of all the type units that use it.
501 MCDwarfDwoLineTable SplitTypeUnitFileTable;
502 /// @}
503
504 /// True iff there are multiple CUs in this module.
505 bool SingleCU;
506 bool IsDarwin;
507
508 /// Map for tracking Fortran deferred CHARACTER lengths.
509 DenseMap<const DIStringType *, unsigned> StringTypeLocMap;
510
511 AddressPool AddrPool;
512
513 /// Accelerator tables.
514 DWARF5AccelTable AccelDebugNames;
515 DWARF5AccelTable AccelTypeUnitsDebugNames;
516 /// Used to hide which DWARF5AccelTable we are using now.
517 DWARF5AccelTable *CurrentDebugNames = &AccelDebugNames;
518 AccelTable<AppleAccelTableOffsetData> AccelNames;
519 AccelTable<AppleAccelTableOffsetData> AccelObjC;
520 AccelTable<AppleAccelTableOffsetData> AccelNamespace;
521 AccelTable<AppleAccelTableTypeData> AccelTypes;
522
523 /// Identify a debugger for "tuning" the debug info.
524 ///
525 /// The "tuning" should be used to set defaults for individual feature flags
526 /// in DwarfDebug; if a given feature has a more specific command-line option,
527 /// that option should take precedence over the tuning.
528 DebuggerKind DebuggerTuning = DebuggerKind::Default;
529
530 MCDwarfDwoLineTable *getDwoLineTable(const DwarfCompileUnit &);
531
532 using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
533
534 void ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
535 const DINode *Node,
536 const MDNode *Scope);
537
538 DbgEntity *createConcreteEntity(DwarfCompileUnit &TheCU,
539 LexicalScope &Scope,
540 const DINode *Node,
541 const DILocation *Location,
542 const MCSymbol *Sym = nullptr);
543
544 /// Construct a DIE for this abstract scope.
545 void constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU, LexicalScope *Scope);
546
547 /// Construct DIEs for call site entries describing the calls in \p MF.
548 void constructCallSiteEntryDIEs(const DISubprogram &SP, DwarfCompileUnit &CU,
549 DIE &ScopeDIE, const MachineFunction &MF);
550
551 template <typename DataT>
552 void addAccelNameImpl(const DwarfUnit &Unit,
553 const DICompileUnit::DebugNameTableKind NameTableKind,
554 AccelTable<DataT> &AppleAccel, StringRef Name,
555 const DIE &Die);
556
557 void finishEntityDefinitions();
558
559 void finishSubprogramDefinitions();
560
561 /// Finish off debug information after all functions have been
562 /// processed.
563 void finalizeModuleInfo();
564
565 /// Emit the debug info section.
566 void emitDebugInfo();
567
568 /// Emit the abbreviation section.
569 void emitAbbreviations();
570
571 /// Emit the string offsets table header.
572 void emitStringOffsetsTableHeader();
573
574 /// Emit a specified accelerator table.
575 template <typename AccelTableT>
576 void emitAccel(AccelTableT &Accel, MCSection *Section, StringRef TableName);
577
578 /// Emit DWARF v5 accelerator table.
579 void emitAccelDebugNames();
580
581 /// Emit visible names into a hashed accelerator table section.
582 void emitAccelNames();
583
584 /// Emit objective C classes and categories into a hashed
585 /// accelerator table section.
586 void emitAccelObjC();
587
588 /// Emit namespace dies into a hashed accelerator table.
589 void emitAccelNamespaces();
590
591 /// Emit type dies into a hashed accelerator table.
592 void emitAccelTypes();
593
594 /// Emit visible names and types into debug pubnames and pubtypes sections.
595 void emitDebugPubSections();
596
597 void emitDebugPubSection(bool GnuStyle, StringRef Name,
598 DwarfCompileUnit *TheU,
599 const StringMap<const DIE *> &Globals);
600
601 /// Emit null-terminated strings into a debug str section.
602 void emitDebugStr();
603
604 /// Emit variable locations into a debug loc section.
605 void emitDebugLoc();
606
607 /// Emit variable locations into a debug loc dwo section.
608 void emitDebugLocDWO();
609
610 void emitDebugLocImpl(MCSection *Sec);
611
612 /// Emit address ranges into a debug aranges section.
613 void emitDebugARanges();
614
615 /// Emit address ranges into a debug ranges section.
616 void emitDebugRanges();
617 void emitDebugRangesDWO();
618 void emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section);
619
620 /// Emit macros into a debug macinfo section.
621 void emitDebugMacinfo();
622 /// Emit macros into a debug macinfo.dwo section.
623 void emitDebugMacinfoDWO();
624 void emitDebugMacinfoImpl(MCSection *Section);
625 void emitMacro(DIMacro &M);
626 void emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U);
627 void emitMacroFileImpl(DIMacroFile &F, DwarfCompileUnit &U,
628 unsigned StartFile, unsigned EndFile,
629 StringRef (*MacroFormToString)(unsigned Form));
630 void handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U);
631
632 /// DWARF 5 Experimental Split Dwarf Emitters
633
634 /// Initialize common features of skeleton units.
635 void initSkeletonUnit(const DwarfUnit &U, DIE &Die,
636 std::unique_ptr<DwarfCompileUnit> NewU);
637
638 /// Construct the split debug info compile unit for the debug info section.
639 /// In DWARF v5, the skeleton unit DIE may have the following attributes:
640 /// DW_AT_addr_base, DW_AT_comp_dir, DW_AT_dwo_name, DW_AT_high_pc,
641 /// DW_AT_low_pc, DW_AT_ranges, DW_AT_stmt_list, and DW_AT_str_offsets_base.
642 /// Prior to DWARF v5 it may also have DW_AT_GNU_dwo_id. DW_AT_GNU_dwo_name
643 /// is used instead of DW_AT_dwo_name, Dw_AT_GNU_addr_base instead of
644 /// DW_AT_addr_base, and DW_AT_GNU_ranges_base instead of DW_AT_rnglists_base.
645 DwarfCompileUnit &constructSkeletonCU(const DwarfCompileUnit &CU);
646
647 /// Emit the debug info dwo section.
648 void emitDebugInfoDWO();
649
650 /// Emit the debug abbrev dwo section.
651 void emitDebugAbbrevDWO();
652
653 /// Emit the debug line dwo section.
654 void emitDebugLineDWO();
655
656 /// Emit the dwo stringoffsets table header.
657 void emitStringOffsetsTableHeaderDWO();
658
659 /// Emit the debug str dwo section.
660 void emitDebugStrDWO();
661
662 /// Emit DWO addresses.
663 void emitDebugAddr();
664
665 /// Flags to let the linker know we have emitted new style pubnames. Only
666 /// emit it here if we don't have a skeleton CU for split dwarf.
667 void addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const;
668
669 /// Create new DwarfCompileUnit for the given metadata node with tag
670 /// DW_TAG_compile_unit.
671 DwarfCompileUnit &getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit);
672 void finishUnitAttributes(const DICompileUnit *DIUnit,
673 DwarfCompileUnit &NewCU);
674
675 /// Register a source line with debug info. Returns the unique
676 /// label that was emitted and which provides correspondence to the
677 /// source line list.
678 void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
679 unsigned Flags, StringRef Location = {});
680
681 /// Populate LexicalScope entries with variables' info.
682 void collectEntityInfo(DwarfCompileUnit &TheCU, const DISubprogram *SP,
683 DenseSet<InlinedEntity> &ProcessedVars);
684
685 /// Build the location list for all DBG_VALUEs in the
686 /// function that describe the same variable. If the resulting
687 /// list has only one entry that is valid for entire variable's
688 /// scope return true.
689 bool buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
690 const DbgValueHistoryMap::Entries &Entries);
691
692 /// Collect variable information from the side table maintained by MF.
693 void collectVariableInfoFromMFTable(DwarfCompileUnit &TheCU,
694 DenseSet<InlinedEntity> &P);
695
696 /// Emit the reference to the section.
697 void emitSectionReference(const DwarfCompileUnit &CU);
698
699 void findForceIsStmtInstrs(const MachineFunction *MF);
700
701 /// Compute instructions which should get is_stmt applied because they
702 /// implement key functionality for a source location atom, store results in
703 /// DwarfDebug::KeyInstructions.
704 void computeKeyInstructions(const MachineFunction *MF);
705
706protected:
707 /// Holder for the file specific debug information.
708 DwarfFile InfoHolder;
709 /// Gather pre-function debug information.
710 void beginFunctionImpl(const MachineFunction *MF) override;
711
712 /// Gather and emit post-function debug information.
713 void endFunctionImpl(const MachineFunction *MF) override;
714
715 /// Get Dwarf compile unit ID for line table.
716 unsigned getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU);
717
718 void skippedNonDebugFunction() override;
719
720 /// Target-specific debug info initialization at function start.
721 /// Default implementation is empty, overridden by NVPTX target.
722 virtual void initializeTargetDebugInfo(const MachineFunction &MF) {}
723
724 /// Target-specific source line recording.
725 virtual void recordTargetSourceLine(const DebugLoc &DL, unsigned Flags);
726
727 const SmallVectorImpl<std::unique_ptr<DwarfCompileUnit>> &getUnits() {
728 return InfoHolder.getUnits();
729 }
730
731public:
732 //===--------------------------------------------------------------------===//
733 // Main entry points.
734 //
735 DwarfDebug(AsmPrinter *A);
736
737 ~DwarfDebug() override;
738
739 /// Emit all Dwarf sections that should come prior to the
740 /// content.
741 void beginModule(Module *M) override;
742
743 /// Emit all Dwarf sections that should come after the content.
744 void endModule() override;
745
746 /// Emits inital debug location directive. Returns instruction at which
747 /// the function prologue ends.
748 const MachineInstr *emitInitialLocDirective(const MachineFunction &MF,
749 unsigned CUID);
750
751 /// Process beginning of an instruction.
752 void beginInstruction(const MachineInstr *MI) override;
753
754 /// Process beginning of code alignment.
755 void beginCodeAlignment(const MachineBasicBlock &MBB) override;
756
757 /// Perform an MD5 checksum of \p Identifier and return the lower 64 bits.
758 static uint64_t makeTypeSignature(StringRef Identifier);
759
760 /// Add a DIE to the set of types that we're going to pull into
761 /// type units.
762 void addDwarfTypeUnitType(DwarfCompileUnit &CU, StringRef Identifier,
763 DIE &Die, const DICompositeType *CTy);
764
765 /// Add a label so that arange data can be generated for it.
766 void addArangeLabel(SymbolCU SCU) { ArangeLabels.push_back(x: SCU); }
767
768 /// For symbols that have a size designated (e.g. common symbols),
769 /// this tracks that size.
770 void setSymbolSize(const MCSymbol *Sym, uint64_t Size) override {
771 SymSize[Sym] = Size;
772 }
773
774 /// Returns whether we should emit all DW_AT_[MIPS_]linkage_name.
775 /// If not, we still might emit certain cases.
776 bool useAllLinkageNames() const { return UseAllLinkageNames; }
777
778 /// Returns whether to use DW_OP_GNU_push_tls_address, instead of the
779 /// standard DW_OP_form_tls_address opcode
780 bool useGNUTLSOpcode() const { return UseGNUTLSOpcode; }
781
782 /// Returns whether to use the DWARF2 format for bitfields instyead of the
783 /// DWARF4 format.
784 bool useDWARF2Bitfields() const { return UseDWARF2Bitfields; }
785
786 /// Returns whether to use inline strings.
787 bool useInlineStrings() const { return UseInlineStrings; }
788
789 /// Returns whether ranges section should be emitted.
790 bool useRangesSection() const { return UseRangesSection; }
791
792 /// Returns whether range encodings should be used for single entry range
793 /// lists.
794 bool alwaysUseRanges(const DwarfCompileUnit &) const;
795
796 // Returns whether novel exprloc addrx+offset encodings should be used to
797 // reduce debug_addr size.
798 bool useAddrOffsetExpressions() const {
799 return MinimizeAddr == MinimizeAddrInV5::Expressions;
800 }
801
802 // Returns whether addrx+offset LLVM extension form should be used to reduce
803 // debug_addr size.
804 bool useAddrOffsetForm() const {
805 return MinimizeAddr == MinimizeAddrInV5::Form;
806 }
807
808 /// Returns whether to use sections as labels rather than temp symbols.
809 bool useSectionsAsReferences() const {
810 return UseSectionsAsReferences;
811 }
812
813 /// Returns whether to generate DWARF v4 type units.
814 bool generateTypeUnits() const { return GenerateTypeUnits; }
815
816 // Experimental DWARF5 features.
817
818 /// Returns what kind (if any) of accelerator tables to emit.
819 AccelTableKind getAccelTableKind() const { return TheAccelTableKind; }
820
821 /// Seet TheAccelTableKind
822 void setTheAccelTableKind(AccelTableKind K) { TheAccelTableKind = K; };
823
824 bool useAppleExtensionAttributes() const {
825 return HasAppleExtensionAttributes;
826 }
827
828 /// Returns whether or not to change the current debug info for the
829 /// split dwarf proposal support.
830 bool useSplitDwarf() const { return HasSplitDwarf; }
831
832 /// Returns whether to generate a string offsets table with (possibly shared)
833 /// contributions from each CU and type unit. This implies the use of
834 /// DW_FORM_strx* indirect references with DWARF v5 and beyond. Note that
835 /// DW_FORM_GNU_str_index is also an indirect reference, but it is used with
836 /// a pre-DWARF v5 implementation of split DWARF sections, which uses a
837 /// monolithic string offsets table.
838 bool useSegmentedStringOffsetsTable() const {
839 return UseSegmentedStringOffsetsTable;
840 }
841
842 bool emitDebugEntryValues() const {
843 return EmitDebugEntryValues;
844 }
845
846 bool useOpConvert() const {
847 return EnableOpConvert;
848 }
849
850 bool shareAcrossDWOCUs() const;
851
852 /// Returns the Dwarf Version.
853 uint16_t getDwarfVersion() const;
854
855 /// Returns a suitable DWARF form to represent a section offset, i.e.
856 /// * DW_FORM_sec_offset for DWARF version >= 4;
857 /// * DW_FORM_data8 for 64-bit DWARFv3;
858 /// * DW_FORM_data4 for 32-bit DWARFv3 and DWARFv2.
859 dwarf::Form getDwarfSectionOffsetForm() const;
860
861 /// Returns the previous CU that was being updated
862 const DwarfCompileUnit *getPrevCU() const { return PrevCU; }
863 void setPrevCU(const DwarfCompileUnit *PrevCU) { this->PrevCU = PrevCU; }
864
865 /// Terminate the line table by adding the last range label.
866 void terminateLineTable(const DwarfCompileUnit *CU);
867
868 /// Returns the entries for the .debug_loc section.
869 const DebugLocStream &getDebugLocs() const { return DebugLocs; }
870
871 /// Emit an entry for the debug loc section. This can be used to
872 /// handle an entry that's going to be emitted into the debug loc section.
873 void emitDebugLocEntry(ByteStreamer &Streamer,
874 const DebugLocStream::Entry &Entry,
875 const DwarfCompileUnit *CU);
876
877 /// Emit the location for a debug loc entry, including the size header.
878 void emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
879 const DwarfCompileUnit *CU);
880
881 void addSubprogramNames(const DwarfUnit &Unit,
882 const DICompileUnit::DebugNameTableKind NameTableKind,
883 const DISubprogram *SP, DIE &Die);
884
885 AddressPool &getAddressPool() { return AddrPool; }
886
887 void addAccelName(const DwarfUnit &Unit,
888 const DICompileUnit::DebugNameTableKind NameTableKind,
889 StringRef Name, const DIE &Die);
890
891 void addAccelObjC(const DwarfUnit &Unit,
892 const DICompileUnit::DebugNameTableKind NameTableKind,
893 StringRef Name, const DIE &Die);
894
895 void addAccelNamespace(const DwarfUnit &Unit,
896 const DICompileUnit::DebugNameTableKind NameTableKind,
897 StringRef Name, const DIE &Die);
898
899 void addAccelType(const DwarfUnit &Unit,
900 const DICompileUnit::DebugNameTableKind NameTableKind,
901 StringRef Name, const DIE &Die, char Flags);
902
903 const MachineFunction *getCurrentFunction() const { return CurFn; }
904
905 /// A helper function to check whether the DIE for a given Scope is
906 /// going to be null.
907 bool isLexicalScopeDIENull(LexicalScope *Scope);
908
909 /// Find the matching DwarfCompileUnit for the given CU DIE.
910 DwarfCompileUnit *lookupCU(const DIE *Die) { return CUDieMap.lookup(Val: Die); }
911 const DwarfCompileUnit *lookupCU(const DIE *Die) const {
912 return CUDieMap.lookup(Val: Die);
913 }
914
915 /// Find the matching DwarfCompileUnit for the given SP referenced from SrcCU.
916 DwarfCompileUnit &getOrCreateAbstractSubprogramCU(const DISubprogram *SP,
917 DwarfCompileUnit &SrcCU);
918
919 unsigned getStringTypeLoc(const DIStringType *ST) const {
920 return StringTypeLocMap.lookup(Val: ST);
921 }
922
923 void addStringTypeLoc(const DIStringType *ST, unsigned Loc) {
924 assert(ST);
925 if (Loc)
926 StringTypeLocMap[ST] = Loc;
927 }
928
929 /// \defgroup DebuggerTuning Predicates to tune DWARF for a given debugger.
930 ///
931 /// Returns whether we are "tuning" for a given debugger.
932 /// @{
933 bool tuneForGDB() const { return DebuggerTuning == DebuggerKind::GDB; }
934 bool tuneForLLDB() const { return DebuggerTuning == DebuggerKind::LLDB; }
935 bool tuneForSCE() const { return DebuggerTuning == DebuggerKind::SCE; }
936 bool tuneForDBX() const { return DebuggerTuning == DebuggerKind::DBX; }
937 /// @}
938
939 const MCSymbol *getSectionLabel(const MCSection *S);
940 void insertSectionLabel(const MCSymbol *S);
941
942 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
943 const DbgValueLoc &Value,
944 DwarfExpression &DwarfExpr);
945
946 /// If the \p File has an MD5 checksum, return it as an MD5Result
947 /// allocated in the MCContext.
948 std::optional<MD5::MD5Result> getMD5AsBytes(const DIFile *File) const;
949
950 MDNodeSet &getLocalDeclsForScope(const DILocalScope *S) {
951 return LocalDeclsPerLS[S];
952 }
953
954 /// Sets the current DWARF5AccelTable to use.
955 void setCurrentDWARF5AccelTable(const DWARF5AccelTableKind Kind) {
956 switch (Kind) {
957 case DWARF5AccelTableKind::CU:
958 CurrentDebugNames = &AccelDebugNames;
959 break;
960 case DWARF5AccelTableKind::TU:
961 CurrentDebugNames = &AccelTypeUnitsDebugNames;
962 }
963 }
964 /// Returns either CU or TU DWARF5AccelTable.
965 DWARF5AccelTable &getCurrentDWARF5AccelTable() { return *CurrentDebugNames; }
966};
967
968} // end namespace llvm
969
970#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFDEBUG_H
971