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 TheCU.constructImportedEntityDIE(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(TheCU.constructImportedEntityDIE(Module));
696 // Emit all Dwarf sections that should come prior to the content. Create
697 // global DIEs and emit initial debug info sections. This is invoked by
698 // the target AsmPrinter.
699 void DwarfDebug::beginModule() {
700 if (DisableDebugInfoPrinting)
703 const Module *M = MMI->getModule();
705 FunctionDIs = makeSubprogramMap(*M);
707 // If module has named metadata anchors then use them, otherwise scan the
708 // module using debug info finder to collect debug info.
709 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
712 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
714 // Emit initial sections so we can reference labels later.
717 SingleCU = CU_Nodes->getNumOperands() == 1;
719 for (MDNode *N : CU_Nodes->operands()) {
720 DICompileUnit CUNode(N);
721 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
722 DIArray ImportedEntities = CUNode.getImportedEntities();
723 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
724 ScopesWithImportedEntities.push_back(std::make_pair(
725 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
726 ImportedEntities.getElement(i)));
727 std::sort(ScopesWithImportedEntities.begin(),
728 ScopesWithImportedEntities.end(), less_first());
729 DIArray GVs = CUNode.getGlobalVariables();
730 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
731 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
732 DIArray SPs = CUNode.getSubprograms();
733 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
734 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
735 DIArray EnumTypes = CUNode.getEnumTypes();
736 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
737 DIType Ty(EnumTypes.getElement(i));
738 // The enum types array by design contains pointers to
739 // MDNodes rather than DIRefs. Unique them here.
740 DIType UniqueTy(resolve(Ty.getRef()));
741 CU.getOrCreateTypeDIE(UniqueTy);
743 DIArray RetainedTypes = CUNode.getRetainedTypes();
744 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
745 DIType Ty(RetainedTypes.getElement(i));
746 // The retained types array by design contains pointers to
747 // MDNodes rather than DIRefs. Unique them here.
748 DIType UniqueTy(resolve(Ty.getRef()));
749 CU.getOrCreateTypeDIE(UniqueTy);
751 // Emit imported_modules last so that the relevant context is already
753 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
754 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
757 // Tell MMI that we have debug info.
758 MMI->setDebugInfoAvailability(true);
760 // Prime section data.
761 SectionMap[Asm->getObjFileLowering().getTextSection()];
764 void DwarfDebug::finishVariableDefinitions() {
765 for (const auto &Var : ConcreteVariables) {
766 DIE *VariableDie = Var->getDIE();
768 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
769 // in the ConcreteVariables list, rather than looking it up again here.
770 // DIE::getUnit isn't simple - it walks parent pointers, etc.
771 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
773 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
774 if (AbsVar && AbsVar->getDIE()) {
775 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
778 Unit->applyVariableAttributes(*Var, *VariableDie);
782 void DwarfDebug::finishSubprogramDefinitions() {
783 const Module *M = MMI->getModule();
785 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
786 for (MDNode *N : CU_Nodes->operands()) {
787 DICompileUnit TheCU(N);
788 // Construct subprogram DIE and add variables DIEs.
789 DwarfCompileUnit *SPCU =
790 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
791 DIArray Subprograms = TheCU.getSubprograms();
792 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
793 DISubprogram SP(Subprograms.getElement(i));
794 // Perhaps the subprogram is in another CU (such as due to comdat
795 // folding, etc), in which case ignore it here.
796 if (SPMap[SP] != SPCU)
798 DIE *D = SPCU->getDIE(SP);
799 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
801 // If this subprogram has an abstract definition, reference that
802 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
804 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
805 // Lazily construct the subprogram if we didn't see either concrete or
806 // inlined versions during codegen. (except in -gmlt ^ where we want
807 // to omit these entirely)
808 D = SPCU->getOrCreateSubprogramDIE(SP);
810 // And attach the attributes
811 SPCU->applySubprogramAttributesToDefinition(SP, *D);
818 // Collect info for variables that were optimized out.
819 void DwarfDebug::collectDeadVariables() {
820 const Module *M = MMI->getModule();
822 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
823 for (MDNode *N : CU_Nodes->operands()) {
824 DICompileUnit TheCU(N);
825 // Construct subprogram DIE and add variables DIEs.
826 DwarfCompileUnit *SPCU =
827 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
828 assert(SPCU && "Unable to find Compile Unit!");
829 DIArray Subprograms = TheCU.getSubprograms();
830 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
831 DISubprogram SP(Subprograms.getElement(i));
832 if (ProcessedSPNodes.count(SP) != 0)
834 assert(SP.isSubprogram() &&
835 "CU's subprogram list contains a non-subprogram");
836 assert(SP.isDefinition() &&
837 "CU's subprogram list contains a subprogram declaration");
838 DIArray Variables = SP.getVariables();
839 if (Variables.getNumElements() == 0)
842 DIE *SPDIE = AbstractSPDies.lookup(SP);
844 SPDIE = SPCU->getDIE(SP);
846 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
847 DIVariable DV(Variables.getElement(vi));
848 assert(DV.isVariable());
849 DbgVariable NewVar(DV, DIExpression(nullptr), this);
850 auto VariableDie = SPCU->constructVariableDIE(NewVar);
851 SPCU->applyVariableAttributes(NewVar, *VariableDie);
852 SPDIE->addChild(std::move(VariableDie));
859 void DwarfDebug::finalizeModuleInfo() {
860 finishSubprogramDefinitions();
862 finishVariableDefinitions();
864 // Collect info for variables that were optimized out.
865 collectDeadVariables();
867 // Handle anything that needs to be done on a per-unit basis after
868 // all other generation.
869 for (const auto &TheU : getUnits()) {
870 // Emit DW_AT_containing_type attribute to connect types with their
871 // vtable holding type.
872 TheU->constructContainingTypeDIEs();
874 // Add CU specific attributes if we need to add any.
875 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
876 // If we're splitting the dwarf out now that we've got the entire
877 // CU then add the dwo id to it.
878 DwarfCompileUnit *SkCU =
879 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
880 if (useSplitDwarf()) {
881 // Emit a unique identifier for this CU.
882 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
883 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
884 dwarf::DW_FORM_data8, ID);
885 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
886 dwarf::DW_FORM_data8, ID);
888 // We don't keep track of which addresses are used in which CU so this
889 // is a bit pessimistic under LTO.
890 if (!AddrPool.isEmpty())
891 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
892 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
893 DwarfAddrSectionSym);
894 if (!TheU->getRangeLists().empty())
895 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
896 dwarf::DW_AT_GNU_ranges_base,
897 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
900 // If we have code split among multiple sections or non-contiguous
901 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
902 // remain in the .o file, otherwise add a DW_AT_low_pc.
903 // FIXME: We should use ranges allow reordering of code ala
904 // .subsections_via_symbols in mach-o. This would mean turning on
905 // ranges for all subprogram DIEs for mach-o.
906 DwarfCompileUnit &U =
907 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
908 unsigned NumRanges = TheU->getRanges().size();
911 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
912 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
913 DwarfDebugRangeSectionSym);
915 // A DW_AT_low_pc attribute may also be specified in combination with
916 // DW_AT_ranges to specify the default base address for use in
917 // location lists (see Section 2.6.2) and range lists (see Section
919 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
922 RangeSpan &Range = TheU->getRanges().back();
923 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
929 // Compute DIE offsets and sizes.
930 InfoHolder.computeSizeAndOffsets();
932 SkeletonHolder.computeSizeAndOffsets();
935 void DwarfDebug::endSections() {
936 // Filter labels by section.
937 for (const SymbolCU &SCU : ArangeLabels) {
938 if (SCU.Sym->isInSection()) {
939 // Make a note of this symbol and it's section.
940 const MCSection *Section = &SCU.Sym->getSection();
941 if (!Section->getKind().isMetadata())
942 SectionMap[Section].push_back(SCU);
944 // Some symbols (e.g. common/bss on mach-o) can have no section but still
945 // appear in the output. This sucks as we rely on sections to build
946 // arange spans. We can do it without, but it's icky.
947 SectionMap[nullptr].push_back(SCU);
951 // Build a list of sections used.
952 std::vector<const MCSection *> Sections;
953 for (const auto &it : SectionMap) {
954 const MCSection *Section = it.first;
955 Sections.push_back(Section);
958 // Sort the sections into order.
959 // This is only done to ensure consistent output order across different runs.
960 std::sort(Sections.begin(), Sections.end(), SectionSort);
962 // Add terminating symbols for each section.
963 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
964 const MCSection *Section = Sections[ID];
965 MCSymbol *Sym = nullptr;
968 // We can't call MCSection::getLabelEndName, as it's only safe to do so
969 // if we know the section name up-front. For user-created sections, the
970 // resulting label may not be valid to use as a label. (section names can
971 // use a greater set of characters on some systems)
972 Sym = Asm->GetTempSymbol("debug_end", ID);
973 Asm->OutStreamer.SwitchSection(Section);
974 Asm->OutStreamer.EmitLabel(Sym);
977 // Insert a final terminator.
978 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
982 // Emit all Dwarf sections that should come after the content.
983 void DwarfDebug::endModule() {
984 assert(CurFn == nullptr);
985 assert(CurMI == nullptr);
990 // End any existing sections.
991 // TODO: Does this need to happen?
994 // Finalize the debug info for the module.
995 finalizeModuleInfo();
999 // Emit all the DIEs into a debug info section.
1002 // Corresponding abbreviations into a abbrev section.
1003 emitAbbreviations();
1005 // Emit info into a debug aranges section.
1006 if (GenerateARangeSection)
1009 // Emit info into a debug ranges section.
1012 if (useSplitDwarf()) {
1015 emitDebugAbbrevDWO();
1018 // Emit DWO addresses.
1019 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1021 // Emit info into a debug loc section.
1024 // Emit info into the dwarf accelerator table sections.
1025 if (useDwarfAccelTables()) {
1028 emitAccelNamespaces();
1032 // Emit the pubnames and pubtypes sections if requested.
1033 if (HasDwarfPubSections) {
1034 emitDebugPubNames(GenerateGnuPubSections);
1035 emitDebugPubTypes(GenerateGnuPubSections);
1040 AbstractVariables.clear();
1042 // Reset these for the next Module if we have one.
1046 // Find abstract variable, if any, associated with Var.
1047 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1048 DIVariable &Cleansed) {
1049 LLVMContext &Ctx = DV->getContext();
1050 // More then one inlined variable corresponds to one abstract variable.
1051 // FIXME: This duplication of variables when inlining should probably be
1052 // removed. It's done to allow each DIVariable to describe its location
1053 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1054 // make it accurate then remove this duplication/cleansing stuff.
1055 Cleansed = cleanseInlinedVariable(DV, Ctx);
1056 auto I = AbstractVariables.find(Cleansed);
1057 if (I != AbstractVariables.end())
1058 return I->second.get();
1062 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1063 DIVariable Cleansed;
1064 return getExistingAbstractVariable(DV, Cleansed);
1067 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1068 LexicalScope *Scope) {
1069 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
1070 addScopeVariable(Scope, AbsDbgVariable.get());
1071 AbstractVariables[Var] = std::move(AbsDbgVariable);
1074 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1075 const MDNode *ScopeNode) {
1076 DIVariable Cleansed = DV;
1077 if (getExistingAbstractVariable(DV, Cleansed))
1080 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1084 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1085 const MDNode *ScopeNode) {
1086 DIVariable Cleansed = DV;
1087 if (getExistingAbstractVariable(DV, Cleansed))
1090 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1091 createAbstractVariable(Cleansed, Scope);
1094 // If Var is a current function argument then add it to CurrentFnArguments list.
1095 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1096 if (!LScopes.isCurrentFunctionScope(Scope))
1098 DIVariable DV = Var->getVariable();
1099 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1101 unsigned ArgNo = DV.getArgNumber();
1105 size_t Size = CurrentFnArguments.size();
1107 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1108 // llvm::Function argument size is not good indicator of how many
1109 // arguments does the function have at source level.
1111 CurrentFnArguments.resize(ArgNo * 2);
1112 assert(!CurrentFnArguments[ArgNo - 1]);
1113 CurrentFnArguments[ArgNo - 1] = Var;
1117 // Collect variable information from side table maintained by MMI.
1118 void DwarfDebug::collectVariableInfoFromMMITable(
1119 SmallPtrSetImpl<const MDNode *> &Processed) {
1120 for (const auto &VI : MMI->getVariableDbgInfo()) {
1123 Processed.insert(VI.Var);
1124 DIVariable DV(VI.Var);
1125 DIExpression Expr(VI.Expr);
1126 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1128 // If variable scope is not found then skip this variable.
1132 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1133 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1134 DbgVariable *RegVar = ConcreteVariables.back().get();
1135 RegVar->setFrameIndex(VI.Slot);
1136 addScopeVariable(Scope, RegVar);
1140 // Get .debug_loc entry for the instruction range starting at MI.
1141 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1142 const MDNode *Expr = MI->getDebugExpression();
1143 const MDNode *Var = MI->getDebugVariable();
1145 assert(MI->getNumOperands() == 4);
1146 if (MI->getOperand(0).isReg()) {
1147 MachineLocation MLoc;
1148 // If the second operand is an immediate, this is a
1149 // register-indirect address.
1150 if (!MI->getOperand(1).isImm())
1151 MLoc.set(MI->getOperand(0).getReg());
1153 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1154 return DebugLocEntry::Value(Var, Expr, MLoc);
1156 if (MI->getOperand(0).isImm())
1157 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1158 if (MI->getOperand(0).isFPImm())
1159 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1160 if (MI->getOperand(0).isCImm())
1161 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1163 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1166 /// Determine whether two variable pieces overlap.
1167 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1168 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1170 unsigned l1 = P1.getPieceOffset();
1171 unsigned l2 = P2.getPieceOffset();
1172 unsigned r1 = l1 + P1.getPieceSize();
1173 unsigned r2 = l2 + P2.getPieceSize();
1174 // True where [l1,r1[ and [r1,r2[ overlap.
1175 return (l1 < r2) && (l2 < r1);
1178 /// Build the location list for all DBG_VALUEs in the function that
1179 /// describe the same variable. If the ranges of several independent
1180 /// pieces of the same variable overlap partially, split them up and
1181 /// combine the ranges. The resulting DebugLocEntries are will have
1182 /// strict monotonically increasing begin addresses and will never
1187 // Ranges History [var, loc, piece ofs size]
1188 // 0 | [x, (reg0, piece 0, 32)]
1189 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1191 // 3 | [clobber reg0]
1192 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1196 // [0-1] [x, (reg0, piece 0, 32)]
1197 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1198 // [3-4] [x, (reg1, piece 32, 32)]
1199 // [4- ] [x, (mem, piece 0, 64)]
1201 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1202 const DbgValueHistoryMap::InstrRanges &Ranges) {
1203 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1205 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1206 const MachineInstr *Begin = I->first;
1207 const MachineInstr *End = I->second;
1208 assert(Begin->isDebugValue() && "Invalid History entry");
1210 // Check if a variable is inaccessible in this range.
1211 if (Begin->getNumOperands() > 1 &&
1212 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1217 // If this piece overlaps with any open ranges, truncate them.
1218 DIExpression DIExpr = Begin->getDebugExpression();
1219 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1220 [&](DebugLocEntry::Value R) {
1221 return piecesOverlap(DIExpr, R.getExpression());
1223 OpenRanges.erase(Last, OpenRanges.end());
1225 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1226 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1228 const MCSymbol *EndLabel;
1230 EndLabel = getLabelAfterInsn(End);
1231 else if (std::next(I) == Ranges.end())
1232 EndLabel = FunctionEndSym;
1234 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1235 assert(EndLabel && "Forgot label after instruction ending a range!");
1237 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1239 auto Value = getDebugLocValue(Begin);
1240 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1241 bool couldMerge = false;
1243 // If this is a piece, it may belong to the current DebugLocEntry.
1244 if (DIExpr.isVariablePiece()) {
1245 // Add this value to the list of open ranges.
1246 OpenRanges.push_back(Value);
1248 // Attempt to add the piece to the last entry.
1249 if (!DebugLoc.empty())
1250 if (DebugLoc.back().MergeValues(Loc))
1255 // Need to add a new DebugLocEntry. Add all values from still
1256 // valid non-overlapping pieces.
1257 if (OpenRanges.size())
1258 Loc.addValues(OpenRanges);
1260 DebugLoc.push_back(std::move(Loc));
1263 // Attempt to coalesce the ranges of two otherwise identical
1265 auto CurEntry = DebugLoc.rbegin();
1266 auto PrevEntry = std::next(CurEntry);
1267 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1268 DebugLoc.pop_back();
1271 dbgs() << CurEntry->getValues().size() << " Values:\n";
1272 for (auto Value : CurEntry->getValues()) {
1273 Value.getVariable()->dump();
1274 Value.getExpression()->dump();
1276 dbgs() << "-----\n";
1282 // Find variables for each lexical scope.
1284 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1285 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1286 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1288 // Grab the variable info that was squirreled away in the MMI side-table.
1289 collectVariableInfoFromMMITable(Processed);
1291 for (const auto &I : DbgValues) {
1292 DIVariable DV(I.first);
1293 if (Processed.count(DV))
1296 // Instruction ranges, specifying where DV is accessible.
1297 const auto &Ranges = I.second;
1301 LexicalScope *Scope = nullptr;
1302 if (MDNode *IA = DV.getInlinedAt()) {
1303 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1304 Scope = LScopes.findInlinedScope(DebugLoc::get(
1305 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1307 Scope = LScopes.findLexicalScope(DV.getContext());
1308 // If variable scope is not found then skip this variable.
1312 Processed.insert(DV);
1313 const MachineInstr *MInsn = Ranges.front().first;
1314 assert(MInsn->isDebugValue() && "History must begin with debug value");
1315 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1316 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1317 DbgVariable *RegVar = ConcreteVariables.back().get();
1318 addScopeVariable(Scope, RegVar);
1320 // Check if the first DBG_VALUE is valid for the rest of the function.
1321 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1324 // Handle multiple DBG_VALUE instructions describing one variable.
1325 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1327 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1328 DebugLocList &LocList = DotDebugLocEntries.back();
1331 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1333 // Build the location list for this variable.
1334 buildLocationList(LocList.List, Ranges);
1337 // Collect info for variables that were optimized out.
1338 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1339 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1340 DIVariable DV(Variables.getElement(i));
1341 assert(DV.isVariable());
1342 if (!Processed.insert(DV))
1344 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1345 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1346 DIExpression NoExpr;
1347 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1348 addScopeVariable(Scope, ConcreteVariables.back().get());
1353 // Return Label preceding the instruction.
1354 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1355 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1356 assert(Label && "Didn't insert label before instruction");
1360 // Return Label immediately following the instruction.
1361 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1362 return LabelsAfterInsn.lookup(MI);
1365 // Process beginning of an instruction.
1366 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1367 assert(CurMI == nullptr);
1369 // Check if source location changes, but ignore DBG_VALUE locations.
1370 if (!MI->isDebugValue()) {
1371 DebugLoc DL = MI->getDebugLoc();
1372 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1375 if (DL == PrologEndLoc) {
1376 Flags |= DWARF2_FLAG_PROLOGUE_END;
1377 PrologEndLoc = DebugLoc();
1379 if (PrologEndLoc.isUnknown())
1380 Flags |= DWARF2_FLAG_IS_STMT;
1382 if (!DL.isUnknown()) {
1383 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1384 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1386 recordSourceLine(0, 0, nullptr, 0);
1390 // Insert labels where requested.
1391 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1392 LabelsBeforeInsn.find(MI);
1395 if (I == LabelsBeforeInsn.end())
1398 // Label already assigned.
1403 PrevLabel = MMI->getContext().CreateTempSymbol();
1404 Asm->OutStreamer.EmitLabel(PrevLabel);
1406 I->second = PrevLabel;
1409 // Process end of an instruction.
1410 void DwarfDebug::endInstruction() {
1411 assert(CurMI != nullptr);
1412 // Don't create a new label after DBG_VALUE instructions.
1413 // They don't generate code.
1414 if (!CurMI->isDebugValue())
1415 PrevLabel = nullptr;
1417 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1418 LabelsAfterInsn.find(CurMI);
1422 if (I == LabelsAfterInsn.end())
1425 // Label already assigned.
1429 // We need a label after this instruction.
1431 PrevLabel = MMI->getContext().CreateTempSymbol();
1432 Asm->OutStreamer.EmitLabel(PrevLabel);
1434 I->second = PrevLabel;
1437 // Each LexicalScope has first instruction and last instruction to mark
1438 // beginning and end of a scope respectively. Create an inverse map that list
1439 // scopes starts (and ends) with an instruction. One instruction may start (or
1440 // end) multiple scopes. Ignore scopes that are not reachable.
1441 void DwarfDebug::identifyScopeMarkers() {
1442 SmallVector<LexicalScope *, 4> WorkList;
1443 WorkList.push_back(LScopes.getCurrentFunctionScope());
1444 while (!WorkList.empty()) {
1445 LexicalScope *S = WorkList.pop_back_val();
1447 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1448 if (!Children.empty())
1449 WorkList.append(Children.begin(), Children.end());
1451 if (S->isAbstractScope())
1454 for (const InsnRange &R : S->getRanges()) {
1455 assert(R.first && "InsnRange does not have first instruction!");
1456 assert(R.second && "InsnRange does not have second instruction!");
1457 requestLabelBeforeInsn(R.first);
1458 requestLabelAfterInsn(R.second);
1463 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1464 // First known non-DBG_VALUE and non-frame setup location marks
1465 // the beginning of the function body.
1466 for (const auto &MBB : *MF)
1467 for (const auto &MI : MBB)
1468 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1469 !MI.getDebugLoc().isUnknown())
1470 return MI.getDebugLoc();
1474 // Gather pre-function debug information. Assumes being called immediately
1475 // after the function entry point has been emitted.
1476 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1479 // If there's no debug info for the function we're not going to do anything.
1480 if (!MMI->hasDebugInfo())
1483 auto DI = FunctionDIs.find(MF->getFunction());
1484 if (DI == FunctionDIs.end())
1487 // Grab the lexical scopes for the function, if we don't have any of those
1488 // then we're not going to be able to do anything.
1489 LScopes.initialize(*MF);
1490 if (LScopes.empty())
1493 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1495 // Make sure that each lexical scope will have a begin/end label.
1496 identifyScopeMarkers();
1498 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1499 // belongs to so that we add to the correct per-cu line table in the
1501 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1502 // FnScope->getScopeNode() and DI->second should represent the same function,
1503 // though they may not be the same MDNode due to inline functions merged in
1504 // LTO where the debug info metadata still differs (either due to distinct
1505 // written differences - two versions of a linkonce_odr function
1506 // written/copied into two separate files, or some sub-optimal metadata that
1507 // isn't structurally identical (see: file path/name info from clang, which
1508 // includes the directory of the cpp file being built, even when the file name
1509 // is absolute (such as an <> lookup header)))
1510 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1511 assert(TheCU && "Unable to find compile unit!");
1512 if (Asm->OutStreamer.hasRawTextSupport())
1513 // Use a single line table if we are generating assembly.
1514 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1516 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1518 // Emit a label for the function so that we have a beginning address.
1519 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1520 // Assumes in correct section after the entry point.
1521 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1523 // Calculate history for local variables.
1524 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1527 // Request labels for the full history.
1528 for (const auto &I : DbgValues) {
1529 const auto &Ranges = I.second;
1533 // The first mention of a function argument gets the FunctionBeginSym
1534 // label, so arguments are visible when breaking at function entry.
1535 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1536 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1537 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1538 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1539 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1540 // Mark all non-overlapping initial pieces.
1541 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1542 DIExpression Piece = I->first->getDebugExpression();
1543 if (std::all_of(Ranges.begin(), I,
1544 [&](DbgValueHistoryMap::InstrRange Pred) {
1545 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1547 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1554 for (const auto &Range : Ranges) {
1555 requestLabelBeforeInsn(Range.first);
1557 requestLabelAfterInsn(Range.second);
1561 PrevInstLoc = DebugLoc();
1562 PrevLabel = FunctionBeginSym;
1564 // Record beginning of function.
1565 PrologEndLoc = findPrologueEndLoc(MF);
1566 if (!PrologEndLoc.isUnknown()) {
1567 DebugLoc FnStartDL =
1568 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1570 FnStartDL.getLine(), FnStartDL.getCol(),
1571 FnStartDL.getScope(MF->getFunction()->getContext()),
1572 // We'd like to list the prologue as "not statements" but GDB behaves
1573 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1574 DWARF2_FLAG_IS_STMT);
1578 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1579 if (addCurrentFnArgument(Var, LS))
1581 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1582 DIVariable DV = Var->getVariable();
1583 // Variables with positive arg numbers are parameters.
1584 if (unsigned ArgNum = DV.getArgNumber()) {
1585 // Keep all parameters in order at the start of the variable list to ensure
1586 // function types are correct (no out-of-order parameters)
1588 // This could be improved by only doing it for optimized builds (unoptimized
1589 // builds have the right order to begin with), searching from the back (this
1590 // would catch the unoptimized case quickly), or doing a binary search
1591 // rather than linear search.
1592 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1593 while (I != Vars.end()) {
1594 unsigned CurNum = (*I)->getVariable().getArgNumber();
1595 // A local (non-parameter) variable has been found, insert immediately
1599 // A later indexed parameter has been found, insert immediately before it.
1600 if (CurNum > ArgNum)
1604 Vars.insert(I, Var);
1608 Vars.push_back(Var);
1611 // Gather and emit post-function debug information.
1612 void DwarfDebug::endFunction(const MachineFunction *MF) {
1613 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1614 // though the beginFunction may not be called at all.
1615 // We should handle both cases.
1619 assert(CurFn == MF);
1620 assert(CurFn != nullptr);
1622 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1623 !FunctionDIs.count(MF->getFunction())) {
1624 // If we don't have a lexical scope for this function then there will
1625 // be a hole in the range information. Keep note of this by setting the
1626 // previously used section to nullptr.
1632 // Define end label for subprogram.
1633 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1634 // Assumes in correct section after the entry point.
1635 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1637 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1638 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1640 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1641 collectVariableInfo(ProcessedVars);
1643 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1644 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1646 // Add the range of this function to the list of ranges for the CU.
1647 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1649 // Under -gmlt, skip building the subprogram if there are no inlined
1650 // subroutines inside it.
1651 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1652 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1653 assert(ScopeVariables.empty());
1654 assert(CurrentFnArguments.empty());
1655 assert(DbgValues.empty());
1656 assert(AbstractVariables.empty());
1657 LabelsBeforeInsn.clear();
1658 LabelsAfterInsn.clear();
1659 PrevLabel = nullptr;
1664 // Construct abstract scopes.
1665 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1666 DISubprogram SP(AScope->getScopeNode());
1667 assert(SP.isSubprogram());
1668 // Collect info for variables that were optimized out.
1669 DIArray Variables = SP.getVariables();
1670 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1671 DIVariable DV(Variables.getElement(i));
1672 assert(DV && DV.isVariable());
1673 if (!ProcessedVars.insert(DV))
1675 ensureAbstractVariableIsCreated(DV, DV.getContext());
1677 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1680 constructSubprogramScopeDIE(TheCU, FnScope);
1683 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1684 // DbgVariables except those that are also in AbstractVariables (since they
1685 // can be used cross-function)
1686 ScopeVariables.clear();
1687 CurrentFnArguments.clear();
1689 LabelsBeforeInsn.clear();
1690 LabelsAfterInsn.clear();
1691 PrevLabel = nullptr;
1695 // Register a source line with debug info. Returns the unique label that was
1696 // emitted and which provides correspondence to the source line list.
1697 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1702 unsigned Discriminator = 0;
1703 if (DIScope Scope = DIScope(S)) {
1704 assert(Scope.isScope());
1705 Fn = Scope.getFilename();
1706 Dir = Scope.getDirectory();
1707 if (Scope.isLexicalBlockFile())
1708 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1710 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1711 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1712 .getOrCreateSourceID(Fn, Dir);
1714 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1718 //===----------------------------------------------------------------------===//
1720 //===----------------------------------------------------------------------===//
1722 // Emit initial Dwarf sections with a label at the start of each one.
1723 void DwarfDebug::emitSectionLabels() {
1724 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1726 // Dwarf sections base addresses.
1727 DwarfInfoSectionSym =
1728 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1729 if (useSplitDwarf()) {
1730 DwarfInfoDWOSectionSym =
1731 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1732 DwarfTypesDWOSectionSym =
1733 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1735 DwarfAbbrevSectionSym =
1736 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1737 if (useSplitDwarf())
1738 DwarfAbbrevDWOSectionSym = emitSectionSym(
1739 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1740 if (GenerateARangeSection)
1741 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1743 DwarfLineSectionSym =
1744 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1745 if (GenerateGnuPubSections) {
1746 DwarfGnuPubNamesSectionSym =
1747 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1748 DwarfGnuPubTypesSectionSym =
1749 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1750 } else if (HasDwarfPubSections) {
1751 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1752 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1755 DwarfStrSectionSym =
1756 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1757 if (useSplitDwarf()) {
1758 DwarfStrDWOSectionSym =
1759 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1760 DwarfAddrSectionSym =
1761 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1762 DwarfDebugLocSectionSym =
1763 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1765 DwarfDebugLocSectionSym =
1766 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1767 DwarfDebugRangeSectionSym =
1768 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1771 // Recursively emits a debug information entry.
1772 void DwarfDebug::emitDIE(DIE &Die) {
1773 // Get the abbreviation for this DIE.
1774 const DIEAbbrev &Abbrev = Die.getAbbrev();
1776 // Emit the code (index) for the abbreviation.
1777 if (Asm->isVerbose())
1778 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1779 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1780 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1781 dwarf::TagString(Abbrev.getTag()));
1782 Asm->EmitULEB128(Abbrev.getNumber());
1784 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1785 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1787 // Emit the DIE attribute values.
1788 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1789 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1790 dwarf::Form Form = AbbrevData[i].getForm();
1791 assert(Form && "Too many attributes for DIE (check abbreviation)");
1793 if (Asm->isVerbose()) {
1794 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1795 if (Attr == dwarf::DW_AT_accessibility)
1796 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1797 cast<DIEInteger>(Values[i])->getValue()));
1800 // Emit an attribute using the defined form.
1801 Values[i]->EmitValue(Asm, Form);
1804 // Emit the DIE children if any.
1805 if (Abbrev.hasChildren()) {
1806 for (auto &Child : Die.getChildren())
1809 Asm->OutStreamer.AddComment("End Of Children Mark");
1814 // Emit the debug info section.
1815 void DwarfDebug::emitDebugInfo() {
1816 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1818 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1821 // Emit the abbreviation section.
1822 void DwarfDebug::emitAbbreviations() {
1823 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1825 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1828 // Emit the last address of the section and the end of the line matrix.
1829 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1830 // Define last address of section.
1831 Asm->OutStreamer.AddComment("Extended Op");
1834 Asm->OutStreamer.AddComment("Op size");
1835 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1836 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1837 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1839 Asm->OutStreamer.AddComment("Section end label");
1841 Asm->OutStreamer.EmitSymbolValue(
1842 Asm->GetTempSymbol("section_end", SectionEnd),
1843 Asm->getDataLayout().getPointerSize());
1845 // Mark end of matrix.
1846 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1852 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1853 StringRef TableName, StringRef SymName) {
1854 Accel.FinalizeTable(Asm, TableName);
1855 Asm->OutStreamer.SwitchSection(Section);
1856 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1857 Asm->OutStreamer.EmitLabel(SectionBegin);
1859 // Emit the full data.
1860 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1863 // Emit visible names into a hashed accelerator table section.
1864 void DwarfDebug::emitAccelNames() {
1865 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1866 "Names", "names_begin");
1869 // Emit objective C classes and categories into a hashed accelerator table
1871 void DwarfDebug::emitAccelObjC() {
1872 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1873 "ObjC", "objc_begin");
1876 // Emit namespace dies into a hashed accelerator table.
1877 void DwarfDebug::emitAccelNamespaces() {
1878 emitAccel(AccelNamespace,
1879 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1880 "namespac", "namespac_begin");
1883 // Emit type dies into a hashed accelerator table.
1884 void DwarfDebug::emitAccelTypes() {
1885 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1886 "types", "types_begin");
1889 // Public name handling.
1890 // The format for the various pubnames:
1892 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1893 // for the DIE that is named.
1895 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1896 // into the CU and the index value is computed according to the type of value
1897 // for the DIE that is named.
1899 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1900 // it's the offset within the debug_info/debug_types dwo section, however, the
1901 // reference in the pubname header doesn't change.
1903 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1904 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1906 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1908 // We could have a specification DIE that has our most of our knowledge,
1909 // look for that now.
1910 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1912 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1913 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1914 Linkage = dwarf::GIEL_EXTERNAL;
1915 } else if (Die->findAttribute(dwarf::DW_AT_external))
1916 Linkage = dwarf::GIEL_EXTERNAL;
1918 switch (Die->getTag()) {
1919 case dwarf::DW_TAG_class_type:
1920 case dwarf::DW_TAG_structure_type:
1921 case dwarf::DW_TAG_union_type:
1922 case dwarf::DW_TAG_enumeration_type:
1923 return dwarf::PubIndexEntryDescriptor(
1924 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1925 ? dwarf::GIEL_STATIC
1926 : dwarf::GIEL_EXTERNAL);
1927 case dwarf::DW_TAG_typedef:
1928 case dwarf::DW_TAG_base_type:
1929 case dwarf::DW_TAG_subrange_type:
1930 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1931 case dwarf::DW_TAG_namespace:
1932 return dwarf::GIEK_TYPE;
1933 case dwarf::DW_TAG_subprogram:
1934 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1935 case dwarf::DW_TAG_constant:
1936 case dwarf::DW_TAG_variable:
1937 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1938 case dwarf::DW_TAG_enumerator:
1939 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1940 dwarf::GIEL_STATIC);
1942 return dwarf::GIEK_NONE;
1946 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1948 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1949 const MCSection *PSec =
1950 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1951 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1953 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1956 void DwarfDebug::emitDebugPubSection(
1957 bool GnuStyle, const MCSection *PSec, StringRef Name,
1958 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1959 for (const auto &NU : CUMap) {
1960 DwarfCompileUnit *TheU = NU.second;
1962 const auto &Globals = (TheU->*Accessor)();
1964 if (Globals.empty())
1967 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1969 unsigned ID = TheU->getUniqueID();
1971 // Start the dwarf pubnames section.
1972 Asm->OutStreamer.SwitchSection(PSec);
1975 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1976 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1977 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1978 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1980 Asm->OutStreamer.EmitLabel(BeginLabel);
1982 Asm->OutStreamer.AddComment("DWARF Version");
1983 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1985 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1986 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1988 Asm->OutStreamer.AddComment("Compilation Unit Length");
1989 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1991 // Emit the pubnames for this compilation unit.
1992 for (const auto &GI : Globals) {
1993 const char *Name = GI.getKeyData();
1994 const DIE *Entity = GI.second;
1996 Asm->OutStreamer.AddComment("DIE offset");
1997 Asm->EmitInt32(Entity->getOffset());
2000 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2001 Asm->OutStreamer.AddComment(
2002 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2003 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2004 Asm->EmitInt8(Desc.toBits());
2007 Asm->OutStreamer.AddComment("External Name");
2008 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2011 Asm->OutStreamer.AddComment("End Mark");
2013 Asm->OutStreamer.EmitLabel(EndLabel);
2017 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2018 const MCSection *PSec =
2019 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2020 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2022 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2025 // Emit visible names into a debug str section.
2026 void DwarfDebug::emitDebugStr() {
2027 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2028 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2031 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2032 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2033 const DITypeIdentifierMap &Map,
2034 ArrayRef<DebugLocEntry::Value> Values) {
2035 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2036 return P.isVariablePiece();
2037 }) && "all values are expected to be pieces");
2038 assert(std::is_sorted(Values.begin(), Values.end()) &&
2039 "pieces are expected to be sorted");
2041 unsigned Offset = 0;
2042 for (auto Piece : Values) {
2043 DIExpression Expr = Piece.getExpression();
2044 unsigned PieceOffset = Expr.getPieceOffset();
2045 unsigned PieceSize = Expr.getPieceSize();
2046 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2047 if (Offset < PieceOffset) {
2048 // The DWARF spec seriously mandates pieces with no locations for gaps.
2049 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2050 Offset += PieceOffset-Offset;
2053 Offset += PieceSize;
2055 const unsigned SizeOfByte = 8;
2057 DIVariable Var = Piece.getVariable();
2058 assert(!Var.isIndirect() && "indirect address for piece");
2059 unsigned VarSize = Var.getSizeInBits(Map);
2060 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2061 && "piece is larger than or outside of variable");
2062 assert(PieceSize*SizeOfByte != VarSize
2063 && "piece covers entire variable");
2065 if (Piece.isLocation() && Piece.getLoc().isReg())
2066 Asm->EmitDwarfRegOpPiece(Streamer,
2068 PieceSize*SizeOfByte);
2070 emitDebugLocValue(Streamer, Piece);
2071 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2077 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2078 const DebugLocEntry &Entry) {
2079 const DebugLocEntry::Value Value = Entry.getValues()[0];
2080 if (Value.isVariablePiece())
2081 // Emit all pieces that belong to the same variable and range.
2082 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2084 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2085 emitDebugLocValue(Streamer, Value);
2088 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2089 const DebugLocEntry::Value &Value) {
2090 DIVariable DV = Value.getVariable();
2092 if (Value.isInt()) {
2093 DIBasicType BTy(resolve(DV.getType()));
2094 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2095 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2096 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2097 Streamer.EmitSLEB128(Value.getInt());
2099 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2100 Streamer.EmitULEB128(Value.getInt());
2102 } else if (Value.isLocation()) {
2103 MachineLocation Loc = Value.getLoc();
2104 DIExpression Expr = Value.getExpression();
2107 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2109 // Complex address entry.
2110 unsigned N = Expr.getNumElements();
2112 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2113 if (Loc.getOffset()) {
2115 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2116 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2117 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2118 Streamer.EmitSLEB128(Expr.getElement(1));
2120 // If first address element is OpPlus then emit
2121 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2122 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2123 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2127 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2130 // Emit remaining complex address elements.
2131 for (; i < N; ++i) {
2132 uint64_t Element = Expr.getElement(i);
2133 if (Element == dwarf::DW_OP_plus) {
2134 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2135 Streamer.EmitULEB128(Expr.getElement(++i));
2136 } else if (Element == dwarf::DW_OP_deref) {
2138 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2139 } else if (Element == dwarf::DW_OP_piece) {
2141 // handled in emitDebugLocEntry.
2143 llvm_unreachable("unknown Opcode found in complex address");
2147 // else ... ignore constant fp. There is not any good way to
2148 // to represent them here in dwarf.
2152 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2153 Asm->OutStreamer.AddComment("Loc expr size");
2154 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2155 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2156 Asm->EmitLabelDifference(end, begin, 2);
2157 Asm->OutStreamer.EmitLabel(begin);
2159 APByteStreamer Streamer(*Asm);
2160 emitDebugLocEntry(Streamer, Entry);
2162 Asm->OutStreamer.EmitLabel(end);
2165 // Emit locations into the debug loc section.
2166 void DwarfDebug::emitDebugLoc() {
2167 // Start the dwarf loc section.
2168 Asm->OutStreamer.SwitchSection(
2169 Asm->getObjFileLowering().getDwarfLocSection());
2170 unsigned char Size = Asm->getDataLayout().getPointerSize();
2171 for (const auto &DebugLoc : DotDebugLocEntries) {
2172 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2173 const DwarfCompileUnit *CU = DebugLoc.CU;
2174 assert(!CU->getRanges().empty());
2175 for (const auto &Entry : DebugLoc.List) {
2176 // Set up the range. This range is relative to the entry point of the
2177 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2178 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2179 if (CU->getRanges().size() == 1) {
2180 // Grab the begin symbol from the first range as our base.
2181 const MCSymbol *Base = CU->getRanges()[0].getStart();
2182 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2183 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2185 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2186 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2189 emitDebugLocEntryLocation(Entry);
2191 Asm->OutStreamer.EmitIntValue(0, Size);
2192 Asm->OutStreamer.EmitIntValue(0, Size);
2196 void DwarfDebug::emitDebugLocDWO() {
2197 Asm->OutStreamer.SwitchSection(
2198 Asm->getObjFileLowering().getDwarfLocDWOSection());
2199 for (const auto &DebugLoc : DotDebugLocEntries) {
2200 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2201 for (const auto &Entry : DebugLoc.List) {
2202 // Just always use start_length for now - at least that's one address
2203 // rather than two. We could get fancier and try to, say, reuse an
2204 // address we know we've emitted elsewhere (the start of the function?
2205 // The start of the CU or CU subrange that encloses this range?)
2206 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2207 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2208 Asm->EmitULEB128(idx);
2209 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2211 emitDebugLocEntryLocation(Entry);
2213 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2218 const MCSymbol *Start, *End;
2221 // Emit a debug aranges section, containing a CU lookup for any
2222 // address we can tie back to a CU.
2223 void DwarfDebug::emitDebugARanges() {
2224 // Start the dwarf aranges section.
2225 Asm->OutStreamer.SwitchSection(
2226 Asm->getObjFileLowering().getDwarfARangesSection());
2228 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2232 // Build a list of sections used.
2233 std::vector<const MCSection *> Sections;
2234 for (const auto &it : SectionMap) {
2235 const MCSection *Section = it.first;
2236 Sections.push_back(Section);
2239 // Sort the sections into order.
2240 // This is only done to ensure consistent output order across different runs.
2241 std::sort(Sections.begin(), Sections.end(), SectionSort);
2243 // Build a set of address spans, sorted by CU.
2244 for (const MCSection *Section : Sections) {
2245 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2246 if (List.size() < 2)
2249 // Sort the symbols by offset within the section.
2250 std::sort(List.begin(), List.end(),
2251 [&](const SymbolCU &A, const SymbolCU &B) {
2252 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2253 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2255 // Symbols with no order assigned should be placed at the end.
2256 // (e.g. section end labels)
2264 // If we have no section (e.g. common), just write out
2265 // individual spans for each symbol.
2267 for (const SymbolCU &Cur : List) {
2269 Span.Start = Cur.Sym;
2272 Spans[Cur.CU].push_back(Span);
2275 // Build spans between each label.
2276 const MCSymbol *StartSym = List[0].Sym;
2277 for (size_t n = 1, e = List.size(); n < e; n++) {
2278 const SymbolCU &Prev = List[n - 1];
2279 const SymbolCU &Cur = List[n];
2281 // Try and build the longest span we can within the same CU.
2282 if (Cur.CU != Prev.CU) {
2284 Span.Start = StartSym;
2286 Spans[Prev.CU].push_back(Span);
2293 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2295 // Build a list of CUs used.
2296 std::vector<DwarfCompileUnit *> CUs;
2297 for (const auto &it : Spans) {
2298 DwarfCompileUnit *CU = it.first;
2302 // Sort the CU list (again, to ensure consistent output order).
2303 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2304 return A->getUniqueID() < B->getUniqueID();
2307 // Emit an arange table for each CU we used.
2308 for (DwarfCompileUnit *CU : CUs) {
2309 std::vector<ArangeSpan> &List = Spans[CU];
2311 // Emit size of content not including length itself.
2312 unsigned ContentSize =
2313 sizeof(int16_t) + // DWARF ARange version number
2314 sizeof(int32_t) + // Offset of CU in the .debug_info section
2315 sizeof(int8_t) + // Pointer Size (in bytes)
2316 sizeof(int8_t); // Segment Size (in bytes)
2318 unsigned TupleSize = PtrSize * 2;
2320 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2322 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2324 ContentSize += Padding;
2325 ContentSize += (List.size() + 1) * TupleSize;
2327 // For each compile unit, write the list of spans it covers.
2328 Asm->OutStreamer.AddComment("Length of ARange Set");
2329 Asm->EmitInt32(ContentSize);
2330 Asm->OutStreamer.AddComment("DWARF Arange version number");
2331 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2332 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2333 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2334 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2335 Asm->EmitInt8(PtrSize);
2336 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2339 Asm->OutStreamer.EmitFill(Padding, 0xff);
2341 for (const ArangeSpan &Span : List) {
2342 Asm->EmitLabelReference(Span.Start, PtrSize);
2344 // Calculate the size as being from the span start to it's end.
2346 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2348 // For symbols without an end marker (e.g. common), we
2349 // write a single arange entry containing just that one symbol.
2350 uint64_t Size = SymSize[Span.Start];
2354 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2358 Asm->OutStreamer.AddComment("ARange terminator");
2359 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2360 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2364 // Emit visible names into a debug ranges section.
2365 void DwarfDebug::emitDebugRanges() {
2366 // Start the dwarf ranges section.
2367 Asm->OutStreamer.SwitchSection(
2368 Asm->getObjFileLowering().getDwarfRangesSection());
2370 // Size for our labels.
2371 unsigned char Size = Asm->getDataLayout().getPointerSize();
2373 // Grab the specific ranges for the compile units in the module.
2374 for (const auto &I : CUMap) {
2375 DwarfCompileUnit *TheCU = I.second;
2377 // Iterate over the misc ranges for the compile units in the module.
2378 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2379 // Emit our symbol so we can find the beginning of the range.
2380 Asm->OutStreamer.EmitLabel(List.getSym());
2382 for (const RangeSpan &Range : List.getRanges()) {
2383 const MCSymbol *Begin = Range.getStart();
2384 const MCSymbol *End = Range.getEnd();
2385 assert(Begin && "Range without a begin symbol?");
2386 assert(End && "Range without an end symbol?");
2387 if (TheCU->getRanges().size() == 1) {
2388 // Grab the begin symbol from the first range as our base.
2389 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2390 Asm->EmitLabelDifference(Begin, Base, Size);
2391 Asm->EmitLabelDifference(End, Base, Size);
2393 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2394 Asm->OutStreamer.EmitSymbolValue(End, Size);
2398 // And terminate the list with two 0 values.
2399 Asm->OutStreamer.EmitIntValue(0, Size);
2400 Asm->OutStreamer.EmitIntValue(0, Size);
2403 // Now emit a range for the CU itself.
2404 if (TheCU->getRanges().size() > 1) {
2405 Asm->OutStreamer.EmitLabel(
2406 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2407 for (const RangeSpan &Range : TheCU->getRanges()) {
2408 const MCSymbol *Begin = Range.getStart();
2409 const MCSymbol *End = Range.getEnd();
2410 assert(Begin && "Range without a begin symbol?");
2411 assert(End && "Range without an end symbol?");
2412 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2413 Asm->OutStreamer.EmitSymbolValue(End, Size);
2415 // And terminate the list with two 0 values.
2416 Asm->OutStreamer.EmitIntValue(0, Size);
2417 Asm->OutStreamer.EmitIntValue(0, Size);
2422 // DWARF5 Experimental Separate Dwarf emitters.
2424 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2425 std::unique_ptr<DwarfUnit> NewU) {
2426 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2427 U.getCUNode().getSplitDebugFilename());
2429 if (!CompilationDir.empty())
2430 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2432 addGnuPubAttributes(*NewU, Die);
2434 SkeletonHolder.addUnit(std::move(NewU));
2437 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2438 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2439 // DW_AT_addr_base, DW_AT_ranges_base.
2440 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2442 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2443 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2444 DwarfCompileUnit &NewCU = *OwnedUnit;
2445 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2446 DwarfInfoSectionSym);
2448 NewCU.initStmtList(DwarfLineSectionSym);
2450 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2455 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2456 // compile units that would normally be in debug_info.
2457 void DwarfDebug::emitDebugInfoDWO() {
2458 assert(useSplitDwarf() && "No split dwarf debug info?");
2459 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2460 // emit relocations into the dwo file.
2461 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2464 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2465 // abbreviations for the .debug_info.dwo section.
2466 void DwarfDebug::emitDebugAbbrevDWO() {
2467 assert(useSplitDwarf() && "No split dwarf?");
2468 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2471 void DwarfDebug::emitDebugLineDWO() {
2472 assert(useSplitDwarf() && "No split dwarf?");
2473 Asm->OutStreamer.SwitchSection(
2474 Asm->getObjFileLowering().getDwarfLineDWOSection());
2475 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2478 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2479 // string section and is identical in format to traditional .debug_str
2481 void DwarfDebug::emitDebugStrDWO() {
2482 assert(useSplitDwarf() && "No split dwarf?");
2483 const MCSection *OffSec =
2484 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2485 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2489 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2490 if (!useSplitDwarf())
2493 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2494 return &SplitTypeUnitFileTable;
2497 static uint64_t makeTypeSignature(StringRef Identifier) {
2499 Hash.update(Identifier);
2500 // ... take the least significant 8 bytes and return those. Our MD5
2501 // implementation always returns its results in little endian, swap bytes
2503 MD5::MD5Result Result;
2505 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2508 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2509 StringRef Identifier, DIE &RefDie,
2510 DICompositeType CTy) {
2511 // Fast path if we're building some type units and one has already used the
2512 // address pool we know we're going to throw away all this work anyway, so
2513 // don't bother building dependent types.
2514 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2517 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2519 CU.addDIETypeSignature(RefDie, *TU);
2523 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2524 AddrPool.resetUsedFlag();
2526 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2527 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2528 this, &InfoHolder, getDwoLineTable(CU));
2529 DwarfTypeUnit &NewTU = *OwnedUnit;
2530 DIE &UnitDie = NewTU.getUnitDie();
2532 TypeUnitsUnderConstruction.push_back(
2533 std::make_pair(std::move(OwnedUnit), CTy));
2535 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2538 uint64_t Signature = makeTypeSignature(Identifier);
2539 NewTU.setTypeSignature(Signature);
2541 if (useSplitDwarf())
2542 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2543 DwarfTypesDWOSectionSym);
2545 CU.applyStmtList(UnitDie);
2547 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2550 NewTU.setType(NewTU.createTypeDIE(CTy));
2553 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2554 TypeUnitsUnderConstruction.clear();
2556 // Types referencing entries in the address table cannot be placed in type
2558 if (AddrPool.hasBeenUsed()) {
2560 // Remove all the types built while building this type.
2561 // This is pessimistic as some of these types might not be dependent on
2562 // the type that used an address.
2563 for (const auto &TU : TypeUnitsToAdd)
2564 DwarfTypeUnits.erase(TU.second);
2566 // Construct this type in the CU directly.
2567 // This is inefficient because all the dependent types will be rebuilt
2568 // from scratch, including building them in type units, discovering that
2569 // they depend on addresses, throwing them out and rebuilding them.
2570 CU.constructTypeDIE(RefDie, CTy);
2574 // If the type wasn't dependent on fission addresses, finish adding the type
2575 // and all its dependent types.
2576 for (auto &TU : TypeUnitsToAdd)
2577 InfoHolder.addUnit(std::move(TU.first));
2579 CU.addDIETypeSignature(RefDie, NewTU);
2582 // Accelerator table mutators - add each name along with its companion
2583 // DIE to the proper table while ensuring that the name that we're going
2584 // to reference is in the string table. We do this since the names we
2585 // add may not only be identical to the names in the DIE.
2586 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2587 if (!useDwarfAccelTables())
2589 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2593 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2594 if (!useDwarfAccelTables())
2596 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2600 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2601 if (!useDwarfAccelTables())
2603 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2607 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2608 if (!useDwarfAccelTables())
2610 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),