1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 #include "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
334 dwarf::Attribute A, const MCSymbol *L,
335 const MCSymbol *Sec) {
336 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
337 U.addSectionLabel(D, A, L);
339 U.addSectionDelta(D, A, L, Sec);
342 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
343 const SmallVectorImpl<InsnRange> &Range) {
344 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
345 // emitting it appropriately.
346 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
348 // Under fission, ranges are specified by constant offsets relative to the
349 // CU's DW_AT_GNU_ranges_base.
351 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
352 DwarfDebugRangeSectionSym);
354 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
355 DwarfDebugRangeSectionSym);
357 RangeSpanList List(RangeSym);
358 for (const InsnRange &R : Range) {
359 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
360 List.addRange(std::move(Span));
363 // Add the range list to the set of ranges to be emitted.
364 TheCU.addRangeList(std::move(List));
367 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
368 const SmallVectorImpl<InsnRange> &Ranges) {
369 assert(!Ranges.empty());
370 if (Ranges.size() == 1)
371 TheCU.attachLowHighPC(Die, getLabelBeforeInsn(Ranges.front().first),
372 getLabelAfterInsn(Ranges.front().second));
374 addScopeRangeList(TheCU, Die, Ranges);
377 // Construct new DW_TAG_lexical_block for this scope and attach
378 // DW_AT_low_pc/DW_AT_high_pc labels.
380 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
381 LexicalScope *Scope) {
382 if (isLexicalScopeDIENull(Scope))
385 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
386 if (Scope->isAbstractScope())
389 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
394 // This scope represents inlined body of a function. Construct DIE to
395 // represent this concrete inlined copy of the function.
397 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
398 LexicalScope *Scope) {
399 assert(Scope->getScopeNode());
400 DIScope DS(Scope->getScopeNode());
401 DISubprogram InlinedSP = getDISubprogram(DS);
402 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
403 // was inlined from another compile unit.
404 DIE *OriginDIE = AbstractSPDies[InlinedSP];
405 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
407 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
408 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
410 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
412 // Add the call site information to the DIE.
413 DILocation DL(Scope->getInlinedAt());
414 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
415 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
416 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
418 // Add name to the name table, we do this here because we're guaranteed
419 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
420 addSubprogramNames(InlinedSP, *ScopeDIE);
425 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
427 const LexicalScope &Scope,
428 DIE *&ObjectPointer) {
429 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
430 if (DV.isObjectPointer())
431 ObjectPointer = Var.get();
435 DIE *DwarfDebug::createScopeChildrenDIE(
436 DwarfCompileUnit &TheCU, LexicalScope *Scope,
437 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
438 unsigned *ChildScopeCount) {
439 DIE *ObjectPointer = nullptr;
441 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
442 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
444 unsigned ChildCountWithoutScopes = Children.size();
446 for (LexicalScope *LS : Scope->getChildren())
447 constructScopeDIE(TheCU, LS, Children);
450 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
452 return ObjectPointer;
455 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
456 LexicalScope *Scope, DIE &ScopeDIE) {
457 // We create children when the scope DIE is not null.
458 SmallVector<std::unique_ptr<DIE>, 8> Children;
459 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
462 for (auto &I : Children)
463 ScopeDIE.addChild(std::move(I));
465 return ObjectPointer;
468 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
469 LexicalScope *Scope) {
470 assert(Scope && Scope->getScopeNode());
471 assert(Scope->isAbstractScope());
472 assert(!Scope->getInlinedAt());
474 DISubprogram SP(Scope->getScopeNode());
476 ProcessedSPNodes.insert(SP);
478 DIE *&AbsDef = AbstractSPDies[SP];
482 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
483 // was inlined from another compile unit.
484 DwarfCompileUnit &SPCU = *SPMap[SP];
487 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
488 // the important distinction that the DIDescriptor is not associated with the
489 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
490 // any). It could be refactored to some common utility function.
491 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
492 ContextDIE = &SPCU.getUnitDie();
493 SPCU.getOrCreateSubprogramDIE(SPDecl);
495 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
497 // Passing null as the associated DIDescriptor because the abstract definition
498 // shouldn't be found by lookup.
499 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
501 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
503 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
504 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
505 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
506 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
509 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
510 LexicalScope *Scope) {
511 assert(Scope && Scope->getScopeNode());
512 assert(!Scope->getInlinedAt());
513 assert(!Scope->isAbstractScope());
514 DISubprogram Sub(Scope->getScopeNode());
516 assert(Sub.isSubprogram());
518 ProcessedSPNodes.insert(Sub);
520 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
522 // Collect arguments for current function.
523 assert(LScopes.isCurrentFunctionScope(Scope));
524 DIE *ObjectPointer = nullptr;
525 for (DbgVariable *ArgDV : CurrentFnArguments)
528 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
530 // If this is a variadic function, add an unspecified parameter.
531 DITypeArray FnArgs = Sub.getType().getTypeArray();
532 // If we have a single element of null, it is a function that returns void.
533 // If we have more than one elements and the last one is null, it is a
534 // variadic function.
535 if (FnArgs.getNumElements() > 1 &&
536 !FnArgs.getElement(FnArgs.getNumElements() - 1))
537 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
539 // Collect lexical scope children first.
540 // ObjectPointer might be a local (non-argument) local variable if it's a
541 // block's synthetic this pointer.
542 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
543 assert(!ObjectPointer && "multiple object pointers can't be described");
544 ObjectPointer = BlockObjPtr;
548 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
551 // Construct a DIE for this scope.
552 void DwarfDebug::constructScopeDIE(
553 DwarfCompileUnit &TheCU, LexicalScope *Scope,
554 SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
555 if (!Scope || !Scope->getScopeNode())
558 DIScope DS(Scope->getScopeNode());
560 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
561 "Only handle inlined subprograms here, use "
562 "constructSubprogramScopeDIE for non-inlined "
565 SmallVector<std::unique_ptr<DIE>, 8> Children;
567 // We try to create the scope DIE first, then the children DIEs. This will
568 // avoid creating un-used children then removing them later when we find out
569 // the scope DIE is null.
570 std::unique_ptr<DIE> ScopeDIE;
571 if (Scope->getParent() && DS.isSubprogram()) {
572 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
575 // We create children when the scope DIE is not null.
576 createScopeChildrenDIE(TheCU, Scope, Children);
578 // Early exit when we know the scope DIE is going to be null.
579 if (isLexicalScopeDIENull(Scope))
582 unsigned ChildScopeCount;
584 // We create children here when we know the scope DIE is not going to be
585 // null and the children will be added to the scope DIE.
586 createScopeChildrenDIE(TheCU, Scope, Children, &ChildScopeCount);
588 // There is no need to emit empty lexical block DIE.
589 std::pair<ImportedEntityMap::const_iterator,
590 ImportedEntityMap::const_iterator> Range =
591 std::equal_range(ScopesWithImportedEntities.begin(),
592 ScopesWithImportedEntities.end(),
593 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
595 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
598 constructImportedEntityDIE(TheCU, DIImportedEntity(i->second)));
599 // If there are only other scopes as children, put them directly in the
600 // parent instead, as this scope would serve no purpose.
601 if (Children.size() == ChildScopeCount) {
602 FinalChildren.insert(FinalChildren.end(),
603 std::make_move_iterator(Children.begin()),
604 std::make_move_iterator(Children.end()));
607 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
608 assert(ScopeDIE && "Scope DIE should not be null.");
612 for (auto &I : Children)
613 ScopeDIE->addChild(std::move(I));
615 FinalChildren.push_back(std::move(ScopeDIE));
618 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
619 if (!GenerateGnuPubSections)
622 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
625 // Create new DwarfCompileUnit for the given metadata node with tag
626 // DW_TAG_compile_unit.
627 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
628 StringRef FN = DIUnit.getFilename();
629 CompilationDir = DIUnit.getDirectory();
631 auto OwnedUnit = make_unique<DwarfCompileUnit>(
632 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
633 DwarfCompileUnit &NewCU = *OwnedUnit;
634 DIE &Die = NewCU.getUnitDie();
635 InfoHolder.addUnit(std::move(OwnedUnit));
637 // LTO with assembly output shares a single line table amongst multiple CUs.
638 // To avoid the compilation directory being ambiguous, let the line table
639 // explicitly describe the directory of all files, never relying on the
640 // compilation directory.
641 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
642 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
643 NewCU.getUniqueID(), CompilationDir);
645 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
646 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
647 DIUnit.getLanguage());
648 NewCU.addString(Die, dwarf::DW_AT_name, FN);
650 if (!useSplitDwarf()) {
651 NewCU.initStmtList(DwarfLineSectionSym);
653 // If we're using split dwarf the compilation dir is going to be in the
654 // skeleton CU and so we don't need to duplicate it here.
655 if (!CompilationDir.empty())
656 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
658 addGnuPubAttributes(NewCU, Die);
661 if (DIUnit.isOptimized())
662 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
664 StringRef Flags = DIUnit.getFlags();
666 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
668 if (unsigned RVer = DIUnit.getRunTimeVersion())
669 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
670 dwarf::DW_FORM_data1, RVer);
675 if (useSplitDwarf()) {
676 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
677 DwarfInfoDWOSectionSym);
678 NewCU.setSkeleton(constructSkeletonCU(NewCU));
680 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
681 DwarfInfoSectionSym);
683 CUMap.insert(std::make_pair(DIUnit, &NewCU));
684 CUDieMap.insert(std::make_pair(&Die, &NewCU));
688 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
690 DIImportedEntity Module(N);
691 assert(Module.Verify());
692 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
693 D->addChild(constructImportedEntityDIE(TheCU, Module));
697 DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
698 const DIImportedEntity &Module) {
699 assert(Module.Verify() &&
700 "Use one of the MDNode * overloads to handle invalid metadata");
701 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
702 TheCU.insertDIE(Module, IMDie.get());
704 DIDescriptor Entity = resolve(Module.getEntity());
705 if (Entity.isNameSpace())
706 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
707 else if (Entity.isSubprogram())
708 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
709 else if (Entity.isType())
710 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
712 EntityDie = TheCU.getDIE(Entity);
714 TheCU.addSourceLine(*IMDie, Module.getLineNumber(),
715 Module.getContext().getFilename(),
716 Module.getContext().getDirectory());
717 TheCU.addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
718 StringRef Name = Module.getName();
720 TheCU.addString(*IMDie, dwarf::DW_AT_name, Name);
725 // Emit all Dwarf sections that should come prior to the content. Create
726 // global DIEs and emit initial debug info sections. This is invoked by
727 // the target AsmPrinter.
728 void DwarfDebug::beginModule() {
729 if (DisableDebugInfoPrinting)
732 const Module *M = MMI->getModule();
734 FunctionDIs = makeSubprogramMap(*M);
736 // If module has named metadata anchors then use them, otherwise scan the
737 // module using debug info finder to collect debug info.
738 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
741 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
743 // Emit initial sections so we can reference labels later.
746 SingleCU = CU_Nodes->getNumOperands() == 1;
748 for (MDNode *N : CU_Nodes->operands()) {
749 DICompileUnit CUNode(N);
750 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
751 DIArray ImportedEntities = CUNode.getImportedEntities();
752 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
753 ScopesWithImportedEntities.push_back(std::make_pair(
754 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
755 ImportedEntities.getElement(i)));
756 std::sort(ScopesWithImportedEntities.begin(),
757 ScopesWithImportedEntities.end(), less_first());
758 DIArray GVs = CUNode.getGlobalVariables();
759 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
760 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
761 DIArray SPs = CUNode.getSubprograms();
762 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
763 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
764 DIArray EnumTypes = CUNode.getEnumTypes();
765 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
766 DIType Ty(EnumTypes.getElement(i));
767 // The enum types array by design contains pointers to
768 // MDNodes rather than DIRefs. Unique them here.
769 DIType UniqueTy(resolve(Ty.getRef()));
770 CU.getOrCreateTypeDIE(UniqueTy);
772 DIArray RetainedTypes = CUNode.getRetainedTypes();
773 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
774 DIType Ty(RetainedTypes.getElement(i));
775 // The retained types array by design contains pointers to
776 // MDNodes rather than DIRefs. Unique them here.
777 DIType UniqueTy(resolve(Ty.getRef()));
778 CU.getOrCreateTypeDIE(UniqueTy);
780 // Emit imported_modules last so that the relevant context is already
782 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
783 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
786 // Tell MMI that we have debug info.
787 MMI->setDebugInfoAvailability(true);
789 // Prime section data.
790 SectionMap[Asm->getObjFileLowering().getTextSection()];
793 void DwarfDebug::finishVariableDefinitions() {
794 for (const auto &Var : ConcreteVariables) {
795 DIE *VariableDie = Var->getDIE();
797 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
798 // in the ConcreteVariables list, rather than looking it up again here.
799 // DIE::getUnit isn't simple - it walks parent pointers, etc.
800 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
802 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
803 if (AbsVar && AbsVar->getDIE()) {
804 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
807 Unit->applyVariableAttributes(*Var, *VariableDie);
811 void DwarfDebug::finishSubprogramDefinitions() {
812 const Module *M = MMI->getModule();
814 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
815 for (MDNode *N : CU_Nodes->operands()) {
816 DICompileUnit TheCU(N);
817 // Construct subprogram DIE and add variables DIEs.
818 DwarfCompileUnit *SPCU =
819 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
820 DIArray Subprograms = TheCU.getSubprograms();
821 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
822 DISubprogram SP(Subprograms.getElement(i));
823 // Perhaps the subprogram is in another CU (such as due to comdat
824 // folding, etc), in which case ignore it here.
825 if (SPMap[SP] != SPCU)
827 DIE *D = SPCU->getDIE(SP);
828 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
830 // If this subprogram has an abstract definition, reference that
831 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
833 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
834 // Lazily construct the subprogram if we didn't see either concrete or
835 // inlined versions during codegen. (except in -gmlt ^ where we want
836 // to omit these entirely)
837 D = SPCU->getOrCreateSubprogramDIE(SP);
839 // And attach the attributes
840 SPCU->applySubprogramAttributesToDefinition(SP, *D);
847 // Collect info for variables that were optimized out.
848 void DwarfDebug::collectDeadVariables() {
849 const Module *M = MMI->getModule();
851 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
852 for (MDNode *N : CU_Nodes->operands()) {
853 DICompileUnit TheCU(N);
854 // Construct subprogram DIE and add variables DIEs.
855 DwarfCompileUnit *SPCU =
856 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
857 assert(SPCU && "Unable to find Compile Unit!");
858 DIArray Subprograms = TheCU.getSubprograms();
859 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
860 DISubprogram SP(Subprograms.getElement(i));
861 if (ProcessedSPNodes.count(SP) != 0)
863 assert(SP.isSubprogram() &&
864 "CU's subprogram list contains a non-subprogram");
865 assert(SP.isDefinition() &&
866 "CU's subprogram list contains a subprogram declaration");
867 DIArray Variables = SP.getVariables();
868 if (Variables.getNumElements() == 0)
871 DIE *SPDIE = AbstractSPDies.lookup(SP);
873 SPDIE = SPCU->getDIE(SP);
875 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
876 DIVariable DV(Variables.getElement(vi));
877 assert(DV.isVariable());
878 DbgVariable NewVar(DV, DIExpression(nullptr), this);
879 auto VariableDie = SPCU->constructVariableDIE(NewVar);
880 SPCU->applyVariableAttributes(NewVar, *VariableDie);
881 SPDIE->addChild(std::move(VariableDie));
888 void DwarfDebug::finalizeModuleInfo() {
889 finishSubprogramDefinitions();
891 finishVariableDefinitions();
893 // Collect info for variables that were optimized out.
894 collectDeadVariables();
896 // Handle anything that needs to be done on a per-unit basis after
897 // all other generation.
898 for (const auto &TheU : getUnits()) {
899 // Emit DW_AT_containing_type attribute to connect types with their
900 // vtable holding type.
901 TheU->constructContainingTypeDIEs();
903 // Add CU specific attributes if we need to add any.
904 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
905 // If we're splitting the dwarf out now that we've got the entire
906 // CU then add the dwo id to it.
907 DwarfCompileUnit *SkCU =
908 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
909 if (useSplitDwarf()) {
910 // Emit a unique identifier for this CU.
911 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
912 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
913 dwarf::DW_FORM_data8, ID);
914 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
915 dwarf::DW_FORM_data8, ID);
917 // We don't keep track of which addresses are used in which CU so this
918 // is a bit pessimistic under LTO.
919 if (!AddrPool.isEmpty())
920 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
921 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
922 DwarfAddrSectionSym);
923 if (!TheU->getRangeLists().empty())
924 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
925 dwarf::DW_AT_GNU_ranges_base,
926 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
929 // If we have code split among multiple sections or non-contiguous
930 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
931 // remain in the .o file, otherwise add a DW_AT_low_pc.
932 // FIXME: We should use ranges allow reordering of code ala
933 // .subsections_via_symbols in mach-o. This would mean turning on
934 // ranges for all subprogram DIEs for mach-o.
935 DwarfCompileUnit &U =
936 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
937 unsigned NumRanges = TheU->getRanges().size();
940 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
941 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
942 DwarfDebugRangeSectionSym);
944 // A DW_AT_low_pc attribute may also be specified in combination with
945 // DW_AT_ranges to specify the default base address for use in
946 // location lists (see Section 2.6.2) and range lists (see Section
948 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
951 RangeSpan &Range = TheU->getRanges().back();
952 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
958 // Compute DIE offsets and sizes.
959 InfoHolder.computeSizeAndOffsets();
961 SkeletonHolder.computeSizeAndOffsets();
964 void DwarfDebug::endSections() {
965 // Filter labels by section.
966 for (const SymbolCU &SCU : ArangeLabels) {
967 if (SCU.Sym->isInSection()) {
968 // Make a note of this symbol and it's section.
969 const MCSection *Section = &SCU.Sym->getSection();
970 if (!Section->getKind().isMetadata())
971 SectionMap[Section].push_back(SCU);
973 // Some symbols (e.g. common/bss on mach-o) can have no section but still
974 // appear in the output. This sucks as we rely on sections to build
975 // arange spans. We can do it without, but it's icky.
976 SectionMap[nullptr].push_back(SCU);
980 // Build a list of sections used.
981 std::vector<const MCSection *> Sections;
982 for (const auto &it : SectionMap) {
983 const MCSection *Section = it.first;
984 Sections.push_back(Section);
987 // Sort the sections into order.
988 // This is only done to ensure consistent output order across different runs.
989 std::sort(Sections.begin(), Sections.end(), SectionSort);
991 // Add terminating symbols for each section.
992 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
993 const MCSection *Section = Sections[ID];
994 MCSymbol *Sym = nullptr;
997 // We can't call MCSection::getLabelEndName, as it's only safe to do so
998 // if we know the section name up-front. For user-created sections, the
999 // resulting label may not be valid to use as a label. (section names can
1000 // use a greater set of characters on some systems)
1001 Sym = Asm->GetTempSymbol("debug_end", ID);
1002 Asm->OutStreamer.SwitchSection(Section);
1003 Asm->OutStreamer.EmitLabel(Sym);
1006 // Insert a final terminator.
1007 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1011 // Emit all Dwarf sections that should come after the content.
1012 void DwarfDebug::endModule() {
1013 assert(CurFn == nullptr);
1014 assert(CurMI == nullptr);
1019 // End any existing sections.
1020 // TODO: Does this need to happen?
1023 // Finalize the debug info for the module.
1024 finalizeModuleInfo();
1028 // Emit all the DIEs into a debug info section.
1031 // Corresponding abbreviations into a abbrev section.
1032 emitAbbreviations();
1034 // Emit info into a debug aranges section.
1035 if (GenerateARangeSection)
1038 // Emit info into a debug ranges section.
1041 if (useSplitDwarf()) {
1044 emitDebugAbbrevDWO();
1047 // Emit DWO addresses.
1048 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1050 // Emit info into a debug loc section.
1053 // Emit info into the dwarf accelerator table sections.
1054 if (useDwarfAccelTables()) {
1057 emitAccelNamespaces();
1061 // Emit the pubnames and pubtypes sections if requested.
1062 if (HasDwarfPubSections) {
1063 emitDebugPubNames(GenerateGnuPubSections);
1064 emitDebugPubTypes(GenerateGnuPubSections);
1069 AbstractVariables.clear();
1071 // Reset these for the next Module if we have one.
1075 // Find abstract variable, if any, associated with Var.
1076 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1077 DIVariable &Cleansed) {
1078 LLVMContext &Ctx = DV->getContext();
1079 // More then one inlined variable corresponds to one abstract variable.
1080 // FIXME: This duplication of variables when inlining should probably be
1081 // removed. It's done to allow each DIVariable to describe its location
1082 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1083 // make it accurate then remove this duplication/cleansing stuff.
1084 Cleansed = cleanseInlinedVariable(DV, Ctx);
1085 auto I = AbstractVariables.find(Cleansed);
1086 if (I != AbstractVariables.end())
1087 return I->second.get();
1091 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1092 DIVariable Cleansed;
1093 return getExistingAbstractVariable(DV, Cleansed);
1096 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1097 LexicalScope *Scope) {
1098 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
1099 addScopeVariable(Scope, AbsDbgVariable.get());
1100 AbstractVariables[Var] = std::move(AbsDbgVariable);
1103 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1104 const MDNode *ScopeNode) {
1105 DIVariable Cleansed = DV;
1106 if (getExistingAbstractVariable(DV, Cleansed))
1109 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1113 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1114 const MDNode *ScopeNode) {
1115 DIVariable Cleansed = DV;
1116 if (getExistingAbstractVariable(DV, Cleansed))
1119 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1120 createAbstractVariable(Cleansed, Scope);
1123 // If Var is a current function argument then add it to CurrentFnArguments list.
1124 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1125 if (!LScopes.isCurrentFunctionScope(Scope))
1127 DIVariable DV = Var->getVariable();
1128 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1130 unsigned ArgNo = DV.getArgNumber();
1134 size_t Size = CurrentFnArguments.size();
1136 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1137 // llvm::Function argument size is not good indicator of how many
1138 // arguments does the function have at source level.
1140 CurrentFnArguments.resize(ArgNo * 2);
1141 assert(!CurrentFnArguments[ArgNo - 1]);
1142 CurrentFnArguments[ArgNo - 1] = Var;
1146 // Collect variable information from side table maintained by MMI.
1147 void DwarfDebug::collectVariableInfoFromMMITable(
1148 SmallPtrSetImpl<const MDNode *> &Processed) {
1149 for (const auto &VI : MMI->getVariableDbgInfo()) {
1152 Processed.insert(VI.Var);
1153 DIVariable DV(VI.Var);
1154 DIExpression Expr(VI.Expr);
1155 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1157 // If variable scope is not found then skip this variable.
1161 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1162 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1163 DbgVariable *RegVar = ConcreteVariables.back().get();
1164 RegVar->setFrameIndex(VI.Slot);
1165 addScopeVariable(Scope, RegVar);
1169 // Get .debug_loc entry for the instruction range starting at MI.
1170 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1171 const MDNode *Expr = MI->getDebugExpression();
1172 const MDNode *Var = MI->getDebugVariable();
1174 assert(MI->getNumOperands() == 4);
1175 if (MI->getOperand(0).isReg()) {
1176 MachineLocation MLoc;
1177 // If the second operand is an immediate, this is a
1178 // register-indirect address.
1179 if (!MI->getOperand(1).isImm())
1180 MLoc.set(MI->getOperand(0).getReg());
1182 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1183 return DebugLocEntry::Value(Var, Expr, MLoc);
1185 if (MI->getOperand(0).isImm())
1186 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1187 if (MI->getOperand(0).isFPImm())
1188 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1189 if (MI->getOperand(0).isCImm())
1190 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1192 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1195 /// Determine whether two variable pieces overlap.
1196 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1197 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1199 unsigned l1 = P1.getPieceOffset();
1200 unsigned l2 = P2.getPieceOffset();
1201 unsigned r1 = l1 + P1.getPieceSize();
1202 unsigned r2 = l2 + P2.getPieceSize();
1203 // True where [l1,r1[ and [r1,r2[ overlap.
1204 return (l1 < r2) && (l2 < r1);
1207 /// Build the location list for all DBG_VALUEs in the function that
1208 /// describe the same variable. If the ranges of several independent
1209 /// pieces of the same variable overlap partially, split them up and
1210 /// combine the ranges. The resulting DebugLocEntries are will have
1211 /// strict monotonically increasing begin addresses and will never
1216 // Ranges History [var, loc, piece ofs size]
1217 // 0 | [x, (reg0, piece 0, 32)]
1218 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1220 // 3 | [clobber reg0]
1221 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1225 // [0-1] [x, (reg0, piece 0, 32)]
1226 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1227 // [3-4] [x, (reg1, piece 32, 32)]
1228 // [4- ] [x, (mem, piece 0, 64)]
1230 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1231 const DbgValueHistoryMap::InstrRanges &Ranges) {
1232 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1234 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1235 const MachineInstr *Begin = I->first;
1236 const MachineInstr *End = I->second;
1237 assert(Begin->isDebugValue() && "Invalid History entry");
1239 // Check if a variable is inaccessible in this range.
1240 if (Begin->getNumOperands() > 1 &&
1241 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1246 // If this piece overlaps with any open ranges, truncate them.
1247 DIExpression DIExpr = Begin->getDebugExpression();
1248 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1249 [&](DebugLocEntry::Value R) {
1250 return piecesOverlap(DIExpr, R.getExpression());
1252 OpenRanges.erase(Last, OpenRanges.end());
1254 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1255 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1257 const MCSymbol *EndLabel;
1259 EndLabel = getLabelAfterInsn(End);
1260 else if (std::next(I) == Ranges.end())
1261 EndLabel = FunctionEndSym;
1263 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1264 assert(EndLabel && "Forgot label after instruction ending a range!");
1266 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1268 auto Value = getDebugLocValue(Begin);
1269 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1270 bool couldMerge = false;
1272 // If this is a piece, it may belong to the current DebugLocEntry.
1273 if (DIExpr.isVariablePiece()) {
1274 // Add this value to the list of open ranges.
1275 OpenRanges.push_back(Value);
1277 // Attempt to add the piece to the last entry.
1278 if (!DebugLoc.empty())
1279 if (DebugLoc.back().MergeValues(Loc))
1284 // Need to add a new DebugLocEntry. Add all values from still
1285 // valid non-overlapping pieces.
1286 if (OpenRanges.size())
1287 Loc.addValues(OpenRanges);
1289 DebugLoc.push_back(std::move(Loc));
1292 // Attempt to coalesce the ranges of two otherwise identical
1294 auto CurEntry = DebugLoc.rbegin();
1295 auto PrevEntry = std::next(CurEntry);
1296 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1297 DebugLoc.pop_back();
1300 dbgs() << CurEntry->getValues().size() << " Values:\n";
1301 for (auto Value : CurEntry->getValues()) {
1302 Value.getVariable()->dump();
1303 Value.getExpression()->dump();
1305 dbgs() << "-----\n";
1311 // Find variables for each lexical scope.
1313 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1314 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1315 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1317 // Grab the variable info that was squirreled away in the MMI side-table.
1318 collectVariableInfoFromMMITable(Processed);
1320 for (const auto &I : DbgValues) {
1321 DIVariable DV(I.first);
1322 if (Processed.count(DV))
1325 // Instruction ranges, specifying where DV is accessible.
1326 const auto &Ranges = I.second;
1330 LexicalScope *Scope = nullptr;
1331 if (MDNode *IA = DV.getInlinedAt()) {
1332 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1333 Scope = LScopes.findInlinedScope(DebugLoc::get(
1334 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1336 Scope = LScopes.findLexicalScope(DV.getContext());
1337 // If variable scope is not found then skip this variable.
1341 Processed.insert(DV);
1342 const MachineInstr *MInsn = Ranges.front().first;
1343 assert(MInsn->isDebugValue() && "History must begin with debug value");
1344 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1345 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1346 DbgVariable *RegVar = ConcreteVariables.back().get();
1347 addScopeVariable(Scope, RegVar);
1349 // Check if the first DBG_VALUE is valid for the rest of the function.
1350 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1353 // Handle multiple DBG_VALUE instructions describing one variable.
1354 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1356 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1357 DebugLocList &LocList = DotDebugLocEntries.back();
1360 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1362 // Build the location list for this variable.
1363 buildLocationList(LocList.List, Ranges);
1366 // Collect info for variables that were optimized out.
1367 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1368 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1369 DIVariable DV(Variables.getElement(i));
1370 assert(DV.isVariable());
1371 if (!Processed.insert(DV))
1373 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1374 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1375 DIExpression NoExpr;
1376 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1377 addScopeVariable(Scope, ConcreteVariables.back().get());
1382 // Return Label preceding the instruction.
1383 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1384 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1385 assert(Label && "Didn't insert label before instruction");
1389 // Return Label immediately following the instruction.
1390 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1391 return LabelsAfterInsn.lookup(MI);
1394 // Process beginning of an instruction.
1395 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1396 assert(CurMI == nullptr);
1398 // Check if source location changes, but ignore DBG_VALUE locations.
1399 if (!MI->isDebugValue()) {
1400 DebugLoc DL = MI->getDebugLoc();
1401 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1404 if (DL == PrologEndLoc) {
1405 Flags |= DWARF2_FLAG_PROLOGUE_END;
1406 PrologEndLoc = DebugLoc();
1408 if (PrologEndLoc.isUnknown())
1409 Flags |= DWARF2_FLAG_IS_STMT;
1411 if (!DL.isUnknown()) {
1412 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1413 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1415 recordSourceLine(0, 0, nullptr, 0);
1419 // Insert labels where requested.
1420 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1421 LabelsBeforeInsn.find(MI);
1424 if (I == LabelsBeforeInsn.end())
1427 // Label already assigned.
1432 PrevLabel = MMI->getContext().CreateTempSymbol();
1433 Asm->OutStreamer.EmitLabel(PrevLabel);
1435 I->second = PrevLabel;
1438 // Process end of an instruction.
1439 void DwarfDebug::endInstruction() {
1440 assert(CurMI != nullptr);
1441 // Don't create a new label after DBG_VALUE instructions.
1442 // They don't generate code.
1443 if (!CurMI->isDebugValue())
1444 PrevLabel = nullptr;
1446 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1447 LabelsAfterInsn.find(CurMI);
1451 if (I == LabelsAfterInsn.end())
1454 // Label already assigned.
1458 // We need a label after this instruction.
1460 PrevLabel = MMI->getContext().CreateTempSymbol();
1461 Asm->OutStreamer.EmitLabel(PrevLabel);
1463 I->second = PrevLabel;
1466 // Each LexicalScope has first instruction and last instruction to mark
1467 // beginning and end of a scope respectively. Create an inverse map that list
1468 // scopes starts (and ends) with an instruction. One instruction may start (or
1469 // end) multiple scopes. Ignore scopes that are not reachable.
1470 void DwarfDebug::identifyScopeMarkers() {
1471 SmallVector<LexicalScope *, 4> WorkList;
1472 WorkList.push_back(LScopes.getCurrentFunctionScope());
1473 while (!WorkList.empty()) {
1474 LexicalScope *S = WorkList.pop_back_val();
1476 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1477 if (!Children.empty())
1478 WorkList.append(Children.begin(), Children.end());
1480 if (S->isAbstractScope())
1483 for (const InsnRange &R : S->getRanges()) {
1484 assert(R.first && "InsnRange does not have first instruction!");
1485 assert(R.second && "InsnRange does not have second instruction!");
1486 requestLabelBeforeInsn(R.first);
1487 requestLabelAfterInsn(R.second);
1492 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1493 // First known non-DBG_VALUE and non-frame setup location marks
1494 // the beginning of the function body.
1495 for (const auto &MBB : *MF)
1496 for (const auto &MI : MBB)
1497 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1498 !MI.getDebugLoc().isUnknown())
1499 return MI.getDebugLoc();
1503 // Gather pre-function debug information. Assumes being called immediately
1504 // after the function entry point has been emitted.
1505 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1508 // If there's no debug info for the function we're not going to do anything.
1509 if (!MMI->hasDebugInfo())
1512 auto DI = FunctionDIs.find(MF->getFunction());
1513 if (DI == FunctionDIs.end())
1516 // Grab the lexical scopes for the function, if we don't have any of those
1517 // then we're not going to be able to do anything.
1518 LScopes.initialize(*MF);
1519 if (LScopes.empty())
1522 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1524 // Make sure that each lexical scope will have a begin/end label.
1525 identifyScopeMarkers();
1527 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1528 // belongs to so that we add to the correct per-cu line table in the
1530 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1531 // FnScope->getScopeNode() and DI->second should represent the same function,
1532 // though they may not be the same MDNode due to inline functions merged in
1533 // LTO where the debug info metadata still differs (either due to distinct
1534 // written differences - two versions of a linkonce_odr function
1535 // written/copied into two separate files, or some sub-optimal metadata that
1536 // isn't structurally identical (see: file path/name info from clang, which
1537 // includes the directory of the cpp file being built, even when the file name
1538 // is absolute (such as an <> lookup header)))
1539 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1540 assert(TheCU && "Unable to find compile unit!");
1541 if (Asm->OutStreamer.hasRawTextSupport())
1542 // Use a single line table if we are generating assembly.
1543 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1545 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1547 // Emit a label for the function so that we have a beginning address.
1548 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1549 // Assumes in correct section after the entry point.
1550 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1552 // Calculate history for local variables.
1553 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1556 // Request labels for the full history.
1557 for (const auto &I : DbgValues) {
1558 const auto &Ranges = I.second;
1562 // The first mention of a function argument gets the FunctionBeginSym
1563 // label, so arguments are visible when breaking at function entry.
1564 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1565 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1566 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1567 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1568 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1569 // Mark all non-overlapping initial pieces.
1570 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1571 DIExpression Piece = I->first->getDebugExpression();
1572 if (std::all_of(Ranges.begin(), I,
1573 [&](DbgValueHistoryMap::InstrRange Pred) {
1574 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1576 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1583 for (const auto &Range : Ranges) {
1584 requestLabelBeforeInsn(Range.first);
1586 requestLabelAfterInsn(Range.second);
1590 PrevInstLoc = DebugLoc();
1591 PrevLabel = FunctionBeginSym;
1593 // Record beginning of function.
1594 PrologEndLoc = findPrologueEndLoc(MF);
1595 if (!PrologEndLoc.isUnknown()) {
1596 DebugLoc FnStartDL =
1597 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1599 FnStartDL.getLine(), FnStartDL.getCol(),
1600 FnStartDL.getScope(MF->getFunction()->getContext()),
1601 // We'd like to list the prologue as "not statements" but GDB behaves
1602 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1603 DWARF2_FLAG_IS_STMT);
1607 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1608 if (addCurrentFnArgument(Var, LS))
1610 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1611 DIVariable DV = Var->getVariable();
1612 // Variables with positive arg numbers are parameters.
1613 if (unsigned ArgNum = DV.getArgNumber()) {
1614 // Keep all parameters in order at the start of the variable list to ensure
1615 // function types are correct (no out-of-order parameters)
1617 // This could be improved by only doing it for optimized builds (unoptimized
1618 // builds have the right order to begin with), searching from the back (this
1619 // would catch the unoptimized case quickly), or doing a binary search
1620 // rather than linear search.
1621 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1622 while (I != Vars.end()) {
1623 unsigned CurNum = (*I)->getVariable().getArgNumber();
1624 // A local (non-parameter) variable has been found, insert immediately
1628 // A later indexed parameter has been found, insert immediately before it.
1629 if (CurNum > ArgNum)
1633 Vars.insert(I, Var);
1637 Vars.push_back(Var);
1640 // Gather and emit post-function debug information.
1641 void DwarfDebug::endFunction(const MachineFunction *MF) {
1642 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1643 // though the beginFunction may not be called at all.
1644 // We should handle both cases.
1648 assert(CurFn == MF);
1649 assert(CurFn != nullptr);
1651 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1652 !FunctionDIs.count(MF->getFunction())) {
1653 // If we don't have a lexical scope for this function then there will
1654 // be a hole in the range information. Keep note of this by setting the
1655 // previously used section to nullptr.
1661 // Define end label for subprogram.
1662 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1663 // Assumes in correct section after the entry point.
1664 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1666 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1667 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1669 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1670 collectVariableInfo(ProcessedVars);
1672 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1673 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1675 // Add the range of this function to the list of ranges for the CU.
1676 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1678 // Under -gmlt, skip building the subprogram if there are no inlined
1679 // subroutines inside it.
1680 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1681 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1682 assert(ScopeVariables.empty());
1683 assert(CurrentFnArguments.empty());
1684 assert(DbgValues.empty());
1685 assert(AbstractVariables.empty());
1686 LabelsBeforeInsn.clear();
1687 LabelsAfterInsn.clear();
1688 PrevLabel = nullptr;
1693 // Construct abstract scopes.
1694 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1695 DISubprogram SP(AScope->getScopeNode());
1696 assert(SP.isSubprogram());
1697 // Collect info for variables that were optimized out.
1698 DIArray Variables = SP.getVariables();
1699 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1700 DIVariable DV(Variables.getElement(i));
1701 assert(DV && DV.isVariable());
1702 if (!ProcessedVars.insert(DV))
1704 ensureAbstractVariableIsCreated(DV, DV.getContext());
1706 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1709 constructSubprogramScopeDIE(TheCU, FnScope);
1712 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1713 // DbgVariables except those that are also in AbstractVariables (since they
1714 // can be used cross-function)
1715 ScopeVariables.clear();
1716 CurrentFnArguments.clear();
1718 LabelsBeforeInsn.clear();
1719 LabelsAfterInsn.clear();
1720 PrevLabel = nullptr;
1724 // Register a source line with debug info. Returns the unique label that was
1725 // emitted and which provides correspondence to the source line list.
1726 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1731 unsigned Discriminator = 0;
1732 if (DIScope Scope = DIScope(S)) {
1733 assert(Scope.isScope());
1734 Fn = Scope.getFilename();
1735 Dir = Scope.getDirectory();
1736 if (Scope.isLexicalBlockFile())
1737 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1739 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1740 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1741 .getOrCreateSourceID(Fn, Dir);
1743 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1747 //===----------------------------------------------------------------------===//
1749 //===----------------------------------------------------------------------===//
1751 // Emit initial Dwarf sections with a label at the start of each one.
1752 void DwarfDebug::emitSectionLabels() {
1753 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1755 // Dwarf sections base addresses.
1756 DwarfInfoSectionSym =
1757 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1758 if (useSplitDwarf()) {
1759 DwarfInfoDWOSectionSym =
1760 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1761 DwarfTypesDWOSectionSym =
1762 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1764 DwarfAbbrevSectionSym =
1765 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1766 if (useSplitDwarf())
1767 DwarfAbbrevDWOSectionSym = emitSectionSym(
1768 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1769 if (GenerateARangeSection)
1770 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1772 DwarfLineSectionSym =
1773 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1774 if (GenerateGnuPubSections) {
1775 DwarfGnuPubNamesSectionSym =
1776 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1777 DwarfGnuPubTypesSectionSym =
1778 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1779 } else if (HasDwarfPubSections) {
1780 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1781 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1784 DwarfStrSectionSym =
1785 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1786 if (useSplitDwarf()) {
1787 DwarfStrDWOSectionSym =
1788 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1789 DwarfAddrSectionSym =
1790 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1791 DwarfDebugLocSectionSym =
1792 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1794 DwarfDebugLocSectionSym =
1795 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1796 DwarfDebugRangeSectionSym =
1797 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1800 // Recursively emits a debug information entry.
1801 void DwarfDebug::emitDIE(DIE &Die) {
1802 // Get the abbreviation for this DIE.
1803 const DIEAbbrev &Abbrev = Die.getAbbrev();
1805 // Emit the code (index) for the abbreviation.
1806 if (Asm->isVerbose())
1807 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1808 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1809 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1810 dwarf::TagString(Abbrev.getTag()));
1811 Asm->EmitULEB128(Abbrev.getNumber());
1813 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1814 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1816 // Emit the DIE attribute values.
1817 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1818 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1819 dwarf::Form Form = AbbrevData[i].getForm();
1820 assert(Form && "Too many attributes for DIE (check abbreviation)");
1822 if (Asm->isVerbose()) {
1823 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1824 if (Attr == dwarf::DW_AT_accessibility)
1825 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1826 cast<DIEInteger>(Values[i])->getValue()));
1829 // Emit an attribute using the defined form.
1830 Values[i]->EmitValue(Asm, Form);
1833 // Emit the DIE children if any.
1834 if (Abbrev.hasChildren()) {
1835 for (auto &Child : Die.getChildren())
1838 Asm->OutStreamer.AddComment("End Of Children Mark");
1843 // Emit the debug info section.
1844 void DwarfDebug::emitDebugInfo() {
1845 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1847 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1850 // Emit the abbreviation section.
1851 void DwarfDebug::emitAbbreviations() {
1852 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1854 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1857 // Emit the last address of the section and the end of the line matrix.
1858 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1859 // Define last address of section.
1860 Asm->OutStreamer.AddComment("Extended Op");
1863 Asm->OutStreamer.AddComment("Op size");
1864 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1865 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1866 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1868 Asm->OutStreamer.AddComment("Section end label");
1870 Asm->OutStreamer.EmitSymbolValue(
1871 Asm->GetTempSymbol("section_end", SectionEnd),
1872 Asm->getDataLayout().getPointerSize());
1874 // Mark end of matrix.
1875 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1881 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1882 StringRef TableName, StringRef SymName) {
1883 Accel.FinalizeTable(Asm, TableName);
1884 Asm->OutStreamer.SwitchSection(Section);
1885 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1886 Asm->OutStreamer.EmitLabel(SectionBegin);
1888 // Emit the full data.
1889 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1892 // Emit visible names into a hashed accelerator table section.
1893 void DwarfDebug::emitAccelNames() {
1894 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1895 "Names", "names_begin");
1898 // Emit objective C classes and categories into a hashed accelerator table
1900 void DwarfDebug::emitAccelObjC() {
1901 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1902 "ObjC", "objc_begin");
1905 // Emit namespace dies into a hashed accelerator table.
1906 void DwarfDebug::emitAccelNamespaces() {
1907 emitAccel(AccelNamespace,
1908 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1909 "namespac", "namespac_begin");
1912 // Emit type dies into a hashed accelerator table.
1913 void DwarfDebug::emitAccelTypes() {
1914 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1915 "types", "types_begin");
1918 // Public name handling.
1919 // The format for the various pubnames:
1921 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1922 // for the DIE that is named.
1924 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1925 // into the CU and the index value is computed according to the type of value
1926 // for the DIE that is named.
1928 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1929 // it's the offset within the debug_info/debug_types dwo section, however, the
1930 // reference in the pubname header doesn't change.
1932 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1933 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1935 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1937 // We could have a specification DIE that has our most of our knowledge,
1938 // look for that now.
1939 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1941 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1942 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1943 Linkage = dwarf::GIEL_EXTERNAL;
1944 } else if (Die->findAttribute(dwarf::DW_AT_external))
1945 Linkage = dwarf::GIEL_EXTERNAL;
1947 switch (Die->getTag()) {
1948 case dwarf::DW_TAG_class_type:
1949 case dwarf::DW_TAG_structure_type:
1950 case dwarf::DW_TAG_union_type:
1951 case dwarf::DW_TAG_enumeration_type:
1952 return dwarf::PubIndexEntryDescriptor(
1953 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1954 ? dwarf::GIEL_STATIC
1955 : dwarf::GIEL_EXTERNAL);
1956 case dwarf::DW_TAG_typedef:
1957 case dwarf::DW_TAG_base_type:
1958 case dwarf::DW_TAG_subrange_type:
1959 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1960 case dwarf::DW_TAG_namespace:
1961 return dwarf::GIEK_TYPE;
1962 case dwarf::DW_TAG_subprogram:
1963 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1964 case dwarf::DW_TAG_constant:
1965 case dwarf::DW_TAG_variable:
1966 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1967 case dwarf::DW_TAG_enumerator:
1968 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1969 dwarf::GIEL_STATIC);
1971 return dwarf::GIEK_NONE;
1975 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1977 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1978 const MCSection *PSec =
1979 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1980 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1982 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1985 void DwarfDebug::emitDebugPubSection(
1986 bool GnuStyle, const MCSection *PSec, StringRef Name,
1987 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1988 for (const auto &NU : CUMap) {
1989 DwarfCompileUnit *TheU = NU.second;
1991 const auto &Globals = (TheU->*Accessor)();
1993 if (Globals.empty())
1996 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1998 unsigned ID = TheU->getUniqueID();
2000 // Start the dwarf pubnames section.
2001 Asm->OutStreamer.SwitchSection(PSec);
2004 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2005 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2006 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2007 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2009 Asm->OutStreamer.EmitLabel(BeginLabel);
2011 Asm->OutStreamer.AddComment("DWARF Version");
2012 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2014 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2015 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2017 Asm->OutStreamer.AddComment("Compilation Unit Length");
2018 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2020 // Emit the pubnames for this compilation unit.
2021 for (const auto &GI : Globals) {
2022 const char *Name = GI.getKeyData();
2023 const DIE *Entity = GI.second;
2025 Asm->OutStreamer.AddComment("DIE offset");
2026 Asm->EmitInt32(Entity->getOffset());
2029 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2030 Asm->OutStreamer.AddComment(
2031 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2032 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2033 Asm->EmitInt8(Desc.toBits());
2036 Asm->OutStreamer.AddComment("External Name");
2037 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2040 Asm->OutStreamer.AddComment("End Mark");
2042 Asm->OutStreamer.EmitLabel(EndLabel);
2046 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2047 const MCSection *PSec =
2048 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2049 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2051 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2054 // Emit visible names into a debug str section.
2055 void DwarfDebug::emitDebugStr() {
2056 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2057 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2060 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2061 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2062 const DITypeIdentifierMap &Map,
2063 ArrayRef<DebugLocEntry::Value> Values) {
2064 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2065 return P.isVariablePiece();
2066 }) && "all values are expected to be pieces");
2067 assert(std::is_sorted(Values.begin(), Values.end()) &&
2068 "pieces are expected to be sorted");
2070 unsigned Offset = 0;
2071 for (auto Piece : Values) {
2072 DIExpression Expr = Piece.getExpression();
2073 unsigned PieceOffset = Expr.getPieceOffset();
2074 unsigned PieceSize = Expr.getPieceSize();
2075 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2076 if (Offset < PieceOffset) {
2077 // The DWARF spec seriously mandates pieces with no locations for gaps.
2078 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2079 Offset += PieceOffset-Offset;
2082 Offset += PieceSize;
2084 const unsigned SizeOfByte = 8;
2086 DIVariable Var = Piece.getVariable();
2087 assert(!Var.isIndirect() && "indirect address for piece");
2088 unsigned VarSize = Var.getSizeInBits(Map);
2089 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2090 && "piece is larger than or outside of variable");
2091 assert(PieceSize*SizeOfByte != VarSize
2092 && "piece covers entire variable");
2094 if (Piece.isLocation() && Piece.getLoc().isReg())
2095 Asm->EmitDwarfRegOpPiece(Streamer,
2097 PieceSize*SizeOfByte);
2099 emitDebugLocValue(Streamer, Piece);
2100 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2106 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2107 const DebugLocEntry &Entry) {
2108 const DebugLocEntry::Value Value = Entry.getValues()[0];
2109 if (Value.isVariablePiece())
2110 // Emit all pieces that belong to the same variable and range.
2111 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2113 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2114 emitDebugLocValue(Streamer, Value);
2117 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2118 const DebugLocEntry::Value &Value) {
2119 DIVariable DV = Value.getVariable();
2121 if (Value.isInt()) {
2122 DIBasicType BTy(resolve(DV.getType()));
2123 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2124 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2125 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2126 Streamer.EmitSLEB128(Value.getInt());
2128 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2129 Streamer.EmitULEB128(Value.getInt());
2131 } else if (Value.isLocation()) {
2132 MachineLocation Loc = Value.getLoc();
2133 DIExpression Expr = Value.getExpression();
2136 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2138 // Complex address entry.
2139 unsigned N = Expr.getNumElements();
2141 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2142 if (Loc.getOffset()) {
2144 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2145 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2146 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2147 Streamer.EmitSLEB128(Expr.getElement(1));
2149 // If first address element is OpPlus then emit
2150 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2151 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2152 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2156 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2159 // Emit remaining complex address elements.
2160 for (; i < N; ++i) {
2161 uint64_t Element = Expr.getElement(i);
2162 if (Element == dwarf::DW_OP_plus) {
2163 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2164 Streamer.EmitULEB128(Expr.getElement(++i));
2165 } else if (Element == dwarf::DW_OP_deref) {
2167 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2168 } else if (Element == dwarf::DW_OP_piece) {
2170 // handled in emitDebugLocEntry.
2172 llvm_unreachable("unknown Opcode found in complex address");
2176 // else ... ignore constant fp. There is not any good way to
2177 // to represent them here in dwarf.
2181 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2182 Asm->OutStreamer.AddComment("Loc expr size");
2183 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2184 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2185 Asm->EmitLabelDifference(end, begin, 2);
2186 Asm->OutStreamer.EmitLabel(begin);
2188 APByteStreamer Streamer(*Asm);
2189 emitDebugLocEntry(Streamer, Entry);
2191 Asm->OutStreamer.EmitLabel(end);
2194 // Emit locations into the debug loc section.
2195 void DwarfDebug::emitDebugLoc() {
2196 // Start the dwarf loc section.
2197 Asm->OutStreamer.SwitchSection(
2198 Asm->getObjFileLowering().getDwarfLocSection());
2199 unsigned char Size = Asm->getDataLayout().getPointerSize();
2200 for (const auto &DebugLoc : DotDebugLocEntries) {
2201 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2202 const DwarfCompileUnit *CU = DebugLoc.CU;
2203 assert(!CU->getRanges().empty());
2204 for (const auto &Entry : DebugLoc.List) {
2205 // Set up the range. This range is relative to the entry point of the
2206 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2207 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2208 if (CU->getRanges().size() == 1) {
2209 // Grab the begin symbol from the first range as our base.
2210 const MCSymbol *Base = CU->getRanges()[0].getStart();
2211 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2212 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2214 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2215 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2218 emitDebugLocEntryLocation(Entry);
2220 Asm->OutStreamer.EmitIntValue(0, Size);
2221 Asm->OutStreamer.EmitIntValue(0, Size);
2225 void DwarfDebug::emitDebugLocDWO() {
2226 Asm->OutStreamer.SwitchSection(
2227 Asm->getObjFileLowering().getDwarfLocDWOSection());
2228 for (const auto &DebugLoc : DotDebugLocEntries) {
2229 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2230 for (const auto &Entry : DebugLoc.List) {
2231 // Just always use start_length for now - at least that's one address
2232 // rather than two. We could get fancier and try to, say, reuse an
2233 // address we know we've emitted elsewhere (the start of the function?
2234 // The start of the CU or CU subrange that encloses this range?)
2235 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2236 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2237 Asm->EmitULEB128(idx);
2238 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2240 emitDebugLocEntryLocation(Entry);
2242 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2247 const MCSymbol *Start, *End;
2250 // Emit a debug aranges section, containing a CU lookup for any
2251 // address we can tie back to a CU.
2252 void DwarfDebug::emitDebugARanges() {
2253 // Start the dwarf aranges section.
2254 Asm->OutStreamer.SwitchSection(
2255 Asm->getObjFileLowering().getDwarfARangesSection());
2257 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2261 // Build a list of sections used.
2262 std::vector<const MCSection *> Sections;
2263 for (const auto &it : SectionMap) {
2264 const MCSection *Section = it.first;
2265 Sections.push_back(Section);
2268 // Sort the sections into order.
2269 // This is only done to ensure consistent output order across different runs.
2270 std::sort(Sections.begin(), Sections.end(), SectionSort);
2272 // Build a set of address spans, sorted by CU.
2273 for (const MCSection *Section : Sections) {
2274 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2275 if (List.size() < 2)
2278 // Sort the symbols by offset within the section.
2279 std::sort(List.begin(), List.end(),
2280 [&](const SymbolCU &A, const SymbolCU &B) {
2281 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2282 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2284 // Symbols with no order assigned should be placed at the end.
2285 // (e.g. section end labels)
2293 // If we have no section (e.g. common), just write out
2294 // individual spans for each symbol.
2296 for (const SymbolCU &Cur : List) {
2298 Span.Start = Cur.Sym;
2301 Spans[Cur.CU].push_back(Span);
2304 // Build spans between each label.
2305 const MCSymbol *StartSym = List[0].Sym;
2306 for (size_t n = 1, e = List.size(); n < e; n++) {
2307 const SymbolCU &Prev = List[n - 1];
2308 const SymbolCU &Cur = List[n];
2310 // Try and build the longest span we can within the same CU.
2311 if (Cur.CU != Prev.CU) {
2313 Span.Start = StartSym;
2315 Spans[Prev.CU].push_back(Span);
2322 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2324 // Build a list of CUs used.
2325 std::vector<DwarfCompileUnit *> CUs;
2326 for (const auto &it : Spans) {
2327 DwarfCompileUnit *CU = it.first;
2331 // Sort the CU list (again, to ensure consistent output order).
2332 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2333 return A->getUniqueID() < B->getUniqueID();
2336 // Emit an arange table for each CU we used.
2337 for (DwarfCompileUnit *CU : CUs) {
2338 std::vector<ArangeSpan> &List = Spans[CU];
2340 // Emit size of content not including length itself.
2341 unsigned ContentSize =
2342 sizeof(int16_t) + // DWARF ARange version number
2343 sizeof(int32_t) + // Offset of CU in the .debug_info section
2344 sizeof(int8_t) + // Pointer Size (in bytes)
2345 sizeof(int8_t); // Segment Size (in bytes)
2347 unsigned TupleSize = PtrSize * 2;
2349 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2351 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2353 ContentSize += Padding;
2354 ContentSize += (List.size() + 1) * TupleSize;
2356 // For each compile unit, write the list of spans it covers.
2357 Asm->OutStreamer.AddComment("Length of ARange Set");
2358 Asm->EmitInt32(ContentSize);
2359 Asm->OutStreamer.AddComment("DWARF Arange version number");
2360 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2361 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2362 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2363 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2364 Asm->EmitInt8(PtrSize);
2365 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2368 Asm->OutStreamer.EmitFill(Padding, 0xff);
2370 for (const ArangeSpan &Span : List) {
2371 Asm->EmitLabelReference(Span.Start, PtrSize);
2373 // Calculate the size as being from the span start to it's end.
2375 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2377 // For symbols without an end marker (e.g. common), we
2378 // write a single arange entry containing just that one symbol.
2379 uint64_t Size = SymSize[Span.Start];
2383 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2387 Asm->OutStreamer.AddComment("ARange terminator");
2388 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2389 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2393 // Emit visible names into a debug ranges section.
2394 void DwarfDebug::emitDebugRanges() {
2395 // Start the dwarf ranges section.
2396 Asm->OutStreamer.SwitchSection(
2397 Asm->getObjFileLowering().getDwarfRangesSection());
2399 // Size for our labels.
2400 unsigned char Size = Asm->getDataLayout().getPointerSize();
2402 // Grab the specific ranges for the compile units in the module.
2403 for (const auto &I : CUMap) {
2404 DwarfCompileUnit *TheCU = I.second;
2406 // Iterate over the misc ranges for the compile units in the module.
2407 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2408 // Emit our symbol so we can find the beginning of the range.
2409 Asm->OutStreamer.EmitLabel(List.getSym());
2411 for (const RangeSpan &Range : List.getRanges()) {
2412 const MCSymbol *Begin = Range.getStart();
2413 const MCSymbol *End = Range.getEnd();
2414 assert(Begin && "Range without a begin symbol?");
2415 assert(End && "Range without an end symbol?");
2416 if (TheCU->getRanges().size() == 1) {
2417 // Grab the begin symbol from the first range as our base.
2418 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2419 Asm->EmitLabelDifference(Begin, Base, Size);
2420 Asm->EmitLabelDifference(End, Base, Size);
2422 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2423 Asm->OutStreamer.EmitSymbolValue(End, Size);
2427 // And terminate the list with two 0 values.
2428 Asm->OutStreamer.EmitIntValue(0, Size);
2429 Asm->OutStreamer.EmitIntValue(0, Size);
2432 // Now emit a range for the CU itself.
2433 if (TheCU->getRanges().size() > 1) {
2434 Asm->OutStreamer.EmitLabel(
2435 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2436 for (const RangeSpan &Range : TheCU->getRanges()) {
2437 const MCSymbol *Begin = Range.getStart();
2438 const MCSymbol *End = Range.getEnd();
2439 assert(Begin && "Range without a begin symbol?");
2440 assert(End && "Range without an end symbol?");
2441 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2442 Asm->OutStreamer.EmitSymbolValue(End, Size);
2444 // And terminate the list with two 0 values.
2445 Asm->OutStreamer.EmitIntValue(0, Size);
2446 Asm->OutStreamer.EmitIntValue(0, Size);
2451 // DWARF5 Experimental Separate Dwarf emitters.
2453 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2454 std::unique_ptr<DwarfUnit> NewU) {
2455 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2456 U.getCUNode().getSplitDebugFilename());
2458 if (!CompilationDir.empty())
2459 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2461 addGnuPubAttributes(*NewU, Die);
2463 SkeletonHolder.addUnit(std::move(NewU));
2466 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2467 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2468 // DW_AT_addr_base, DW_AT_ranges_base.
2469 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2471 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2472 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2473 DwarfCompileUnit &NewCU = *OwnedUnit;
2474 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2475 DwarfInfoSectionSym);
2477 NewCU.initStmtList(DwarfLineSectionSym);
2479 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2484 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2485 // compile units that would normally be in debug_info.
2486 void DwarfDebug::emitDebugInfoDWO() {
2487 assert(useSplitDwarf() && "No split dwarf debug info?");
2488 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2489 // emit relocations into the dwo file.
2490 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2493 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2494 // abbreviations for the .debug_info.dwo section.
2495 void DwarfDebug::emitDebugAbbrevDWO() {
2496 assert(useSplitDwarf() && "No split dwarf?");
2497 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2500 void DwarfDebug::emitDebugLineDWO() {
2501 assert(useSplitDwarf() && "No split dwarf?");
2502 Asm->OutStreamer.SwitchSection(
2503 Asm->getObjFileLowering().getDwarfLineDWOSection());
2504 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2507 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2508 // string section and is identical in format to traditional .debug_str
2510 void DwarfDebug::emitDebugStrDWO() {
2511 assert(useSplitDwarf() && "No split dwarf?");
2512 const MCSection *OffSec =
2513 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2514 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2518 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2519 if (!useSplitDwarf())
2522 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2523 return &SplitTypeUnitFileTable;
2526 static uint64_t makeTypeSignature(StringRef Identifier) {
2528 Hash.update(Identifier);
2529 // ... take the least significant 8 bytes and return those. Our MD5
2530 // implementation always returns its results in little endian, swap bytes
2532 MD5::MD5Result Result;
2534 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2537 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2538 StringRef Identifier, DIE &RefDie,
2539 DICompositeType CTy) {
2540 // Fast path if we're building some type units and one has already used the
2541 // address pool we know we're going to throw away all this work anyway, so
2542 // don't bother building dependent types.
2543 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2546 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2548 CU.addDIETypeSignature(RefDie, *TU);
2552 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2553 AddrPool.resetUsedFlag();
2555 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2556 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2557 this, &InfoHolder, getDwoLineTable(CU));
2558 DwarfTypeUnit &NewTU = *OwnedUnit;
2559 DIE &UnitDie = NewTU.getUnitDie();
2561 TypeUnitsUnderConstruction.push_back(
2562 std::make_pair(std::move(OwnedUnit), CTy));
2564 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2567 uint64_t Signature = makeTypeSignature(Identifier);
2568 NewTU.setTypeSignature(Signature);
2570 if (useSplitDwarf())
2571 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2572 DwarfTypesDWOSectionSym);
2574 CU.applyStmtList(UnitDie);
2576 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2579 NewTU.setType(NewTU.createTypeDIE(CTy));
2582 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2583 TypeUnitsUnderConstruction.clear();
2585 // Types referencing entries in the address table cannot be placed in type
2587 if (AddrPool.hasBeenUsed()) {
2589 // Remove all the types built while building this type.
2590 // This is pessimistic as some of these types might not be dependent on
2591 // the type that used an address.
2592 for (const auto &TU : TypeUnitsToAdd)
2593 DwarfTypeUnits.erase(TU.second);
2595 // Construct this type in the CU directly.
2596 // This is inefficient because all the dependent types will be rebuilt
2597 // from scratch, including building them in type units, discovering that
2598 // they depend on addresses, throwing them out and rebuilding them.
2599 CU.constructTypeDIE(RefDie, CTy);
2603 // If the type wasn't dependent on fission addresses, finish adding the type
2604 // and all its dependent types.
2605 for (auto &TU : TypeUnitsToAdd)
2606 InfoHolder.addUnit(std::move(TU.first));
2608 CU.addDIETypeSignature(RefDie, NewTU);
2611 // Accelerator table mutators - add each name along with its companion
2612 // DIE to the proper table while ensuring that the name that we're going
2613 // to reference is in the string table. We do this since the names we
2614 // add may not only be identical to the names in the DIE.
2615 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2616 if (!useDwarfAccelTables())
2618 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2622 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2623 if (!useDwarfAccelTables())
2625 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2629 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2630 if (!useDwarfAccelTables())
2632 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2636 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2637 if (!useDwarfAccelTables())
2639 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),