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 InlinedSubprogramDIEs.insert(OriginDIE);
414 // Add the call site information to the DIE.
415 DILocation DL(Scope->getInlinedAt());
416 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
417 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
418 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
420 // Add name to the name table, we do this here because we're guaranteed
421 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
422 addSubprogramNames(InlinedSP, *ScopeDIE);
427 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
429 const LexicalScope &Scope,
430 DIE *&ObjectPointer) {
431 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
432 if (DV.isObjectPointer())
433 ObjectPointer = Var.get();
437 DIE *DwarfDebug::createScopeChildrenDIE(
438 DwarfCompileUnit &TheCU, LexicalScope *Scope,
439 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
440 unsigned *ChildScopeCount) {
441 DIE *ObjectPointer = nullptr;
443 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
444 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
446 unsigned ChildCountWithoutScopes = Children.size();
448 for (LexicalScope *LS : Scope->getChildren())
449 constructScopeDIE(TheCU, LS, Children);
452 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
454 return ObjectPointer;
457 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
458 LexicalScope *Scope, DIE &ScopeDIE) {
459 // We create children when the scope DIE is not null.
460 SmallVector<std::unique_ptr<DIE>, 8> Children;
461 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
464 for (auto &I : Children)
465 ScopeDIE.addChild(std::move(I));
467 return ObjectPointer;
470 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
471 LexicalScope *Scope) {
472 assert(Scope && Scope->getScopeNode());
473 assert(Scope->isAbstractScope());
474 assert(!Scope->getInlinedAt());
476 DISubprogram SP(Scope->getScopeNode());
478 ProcessedSPNodes.insert(SP);
480 DIE *&AbsDef = AbstractSPDies[SP];
484 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
485 // was inlined from another compile unit.
486 DwarfCompileUnit &SPCU = *SPMap[SP];
489 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
490 // the important distinction that the DIDescriptor is not associated with the
491 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
492 // any). It could be refactored to some common utility function.
493 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
494 ContextDIE = &SPCU.getUnitDie();
495 SPCU.getOrCreateSubprogramDIE(SPDecl);
497 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
499 // Passing null as the associated DIDescriptor because the abstract definition
500 // shouldn't be found by lookup.
501 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
503 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
505 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
506 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
507 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
508 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
511 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
512 LexicalScope *Scope) {
513 assert(Scope && Scope->getScopeNode());
514 assert(!Scope->getInlinedAt());
515 assert(!Scope->isAbstractScope());
516 DISubprogram Sub(Scope->getScopeNode());
518 assert(Sub.isSubprogram());
520 ProcessedSPNodes.insert(Sub);
522 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
524 // Collect arguments for current function.
525 assert(LScopes.isCurrentFunctionScope(Scope));
526 DIE *ObjectPointer = nullptr;
527 for (DbgVariable *ArgDV : CurrentFnArguments)
530 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
532 // If this is a variadic function, add an unspecified parameter.
533 DITypeArray FnArgs = Sub.getType().getTypeArray();
534 // If we have a single element of null, it is a function that returns void.
535 // If we have more than one elements and the last one is null, it is a
536 // variadic function.
537 if (FnArgs.getNumElements() > 1 &&
538 !FnArgs.getElement(FnArgs.getNumElements() - 1))
539 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
541 // Collect lexical scope children first.
542 // ObjectPointer might be a local (non-argument) local variable if it's a
543 // block's synthetic this pointer.
544 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
545 assert(!ObjectPointer && "multiple object pointers can't be described");
546 ObjectPointer = BlockObjPtr;
550 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
553 // Construct a DIE for this scope.
554 void DwarfDebug::constructScopeDIE(
555 DwarfCompileUnit &TheCU, LexicalScope *Scope,
556 SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
557 if (!Scope || !Scope->getScopeNode())
560 DIScope DS(Scope->getScopeNode());
562 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
563 "Only handle inlined subprograms here, use "
564 "constructSubprogramScopeDIE for non-inlined "
567 SmallVector<std::unique_ptr<DIE>, 8> Children;
569 // We try to create the scope DIE first, then the children DIEs. This will
570 // avoid creating un-used children then removing them later when we find out
571 // the scope DIE is null.
572 std::unique_ptr<DIE> ScopeDIE;
573 if (Scope->getParent() && DS.isSubprogram()) {
574 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
577 // We create children when the scope DIE is not null.
578 createScopeChildrenDIE(TheCU, Scope, Children);
580 // Early exit when we know the scope DIE is going to be null.
581 if (isLexicalScopeDIENull(Scope))
584 unsigned ChildScopeCount;
586 // We create children here when we know the scope DIE is not going to be
587 // null and the children will be added to the scope DIE.
588 createScopeChildrenDIE(TheCU, Scope, Children, &ChildScopeCount);
590 // There is no need to emit empty lexical block DIE.
591 std::pair<ImportedEntityMap::const_iterator,
592 ImportedEntityMap::const_iterator> Range =
593 std::equal_range(ScopesWithImportedEntities.begin(),
594 ScopesWithImportedEntities.end(),
595 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
597 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
600 constructImportedEntityDIE(TheCU, DIImportedEntity(i->second)));
601 // If there are only other scopes as children, put them directly in the
602 // parent instead, as this scope would serve no purpose.
603 if (Children.size() == ChildScopeCount) {
604 FinalChildren.insert(FinalChildren.end(),
605 std::make_move_iterator(Children.begin()),
606 std::make_move_iterator(Children.end()));
609 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
610 assert(ScopeDIE && "Scope DIE should not be null.");
614 for (auto &I : Children)
615 ScopeDIE->addChild(std::move(I));
617 FinalChildren.push_back(std::move(ScopeDIE));
620 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
621 if (!GenerateGnuPubSections)
624 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
627 // Create new DwarfCompileUnit for the given metadata node with tag
628 // DW_TAG_compile_unit.
629 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
630 StringRef FN = DIUnit.getFilename();
631 CompilationDir = DIUnit.getDirectory();
633 auto OwnedUnit = make_unique<DwarfCompileUnit>(
634 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
635 DwarfCompileUnit &NewCU = *OwnedUnit;
636 DIE &Die = NewCU.getUnitDie();
637 InfoHolder.addUnit(std::move(OwnedUnit));
639 // LTO with assembly output shares a single line table amongst multiple CUs.
640 // To avoid the compilation directory being ambiguous, let the line table
641 // explicitly describe the directory of all files, never relying on the
642 // compilation directory.
643 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
644 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
645 NewCU.getUniqueID(), CompilationDir);
647 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
648 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
649 DIUnit.getLanguage());
650 NewCU.addString(Die, dwarf::DW_AT_name, FN);
652 if (!useSplitDwarf()) {
653 NewCU.initStmtList(DwarfLineSectionSym);
655 // If we're using split dwarf the compilation dir is going to be in the
656 // skeleton CU and so we don't need to duplicate it here.
657 if (!CompilationDir.empty())
658 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
660 addGnuPubAttributes(NewCU, Die);
663 if (DIUnit.isOptimized())
664 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
666 StringRef Flags = DIUnit.getFlags();
668 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
670 if (unsigned RVer = DIUnit.getRunTimeVersion())
671 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
672 dwarf::DW_FORM_data1, RVer);
677 if (useSplitDwarf()) {
678 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
679 DwarfInfoDWOSectionSym);
680 NewCU.setSkeleton(constructSkeletonCU(NewCU));
682 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
683 DwarfInfoSectionSym);
685 CUMap.insert(std::make_pair(DIUnit, &NewCU));
686 CUDieMap.insert(std::make_pair(&Die, &NewCU));
690 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
692 DIImportedEntity Module(N);
693 assert(Module.Verify());
694 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
695 D->addChild(constructImportedEntityDIE(TheCU, Module));
699 DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
700 const DIImportedEntity &Module) {
701 assert(Module.Verify() &&
702 "Use one of the MDNode * overloads to handle invalid metadata");
703 std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
704 TheCU.insertDIE(Module, IMDie.get());
706 DIDescriptor Entity = resolve(Module.getEntity());
707 if (Entity.isNameSpace())
708 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
709 else if (Entity.isSubprogram())
710 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
711 else if (Entity.isType())
712 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
714 EntityDie = TheCU.getDIE(Entity);
716 TheCU.addSourceLine(*IMDie, Module.getLineNumber(),
717 Module.getContext().getFilename(),
718 Module.getContext().getDirectory());
719 TheCU.addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
720 StringRef Name = Module.getName();
722 TheCU.addString(*IMDie, dwarf::DW_AT_name, Name);
727 // Emit all Dwarf sections that should come prior to the content. Create
728 // global DIEs and emit initial debug info sections. This is invoked by
729 // the target AsmPrinter.
730 void DwarfDebug::beginModule() {
731 if (DisableDebugInfoPrinting)
734 const Module *M = MMI->getModule();
736 FunctionDIs = makeSubprogramMap(*M);
738 // If module has named metadata anchors then use them, otherwise scan the
739 // module using debug info finder to collect debug info.
740 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
743 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
745 // Emit initial sections so we can reference labels later.
748 SingleCU = CU_Nodes->getNumOperands() == 1;
750 for (MDNode *N : CU_Nodes->operands()) {
751 DICompileUnit CUNode(N);
752 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
753 DIArray ImportedEntities = CUNode.getImportedEntities();
754 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
755 ScopesWithImportedEntities.push_back(std::make_pair(
756 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
757 ImportedEntities.getElement(i)));
758 std::sort(ScopesWithImportedEntities.begin(),
759 ScopesWithImportedEntities.end(), less_first());
760 DIArray GVs = CUNode.getGlobalVariables();
761 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
762 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
763 DIArray SPs = CUNode.getSubprograms();
764 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
765 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
766 DIArray EnumTypes = CUNode.getEnumTypes();
767 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
768 DIType Ty(EnumTypes.getElement(i));
769 // The enum types array by design contains pointers to
770 // MDNodes rather than DIRefs. Unique them here.
771 DIType UniqueTy(resolve(Ty.getRef()));
772 CU.getOrCreateTypeDIE(UniqueTy);
774 DIArray RetainedTypes = CUNode.getRetainedTypes();
775 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
776 DIType Ty(RetainedTypes.getElement(i));
777 // The retained types array by design contains pointers to
778 // MDNodes rather than DIRefs. Unique them here.
779 DIType UniqueTy(resolve(Ty.getRef()));
780 CU.getOrCreateTypeDIE(UniqueTy);
782 // Emit imported_modules last so that the relevant context is already
784 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
785 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
788 // Tell MMI that we have debug info.
789 MMI->setDebugInfoAvailability(true);
791 // Prime section data.
792 SectionMap[Asm->getObjFileLowering().getTextSection()];
795 void DwarfDebug::finishVariableDefinitions() {
796 for (const auto &Var : ConcreteVariables) {
797 DIE *VariableDie = Var->getDIE();
799 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
800 // in the ConcreteVariables list, rather than looking it up again here.
801 // DIE::getUnit isn't simple - it walks parent pointers, etc.
802 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
804 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
805 if (AbsVar && AbsVar->getDIE()) {
806 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
809 Unit->applyVariableAttributes(*Var, *VariableDie);
813 void DwarfDebug::finishSubprogramDefinitions() {
814 const Module *M = MMI->getModule();
816 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
817 for (MDNode *N : CU_Nodes->operands()) {
818 DICompileUnit TheCU(N);
819 // Construct subprogram DIE and add variables DIEs.
820 DwarfCompileUnit *SPCU =
821 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
822 DIArray Subprograms = TheCU.getSubprograms();
823 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
824 DISubprogram SP(Subprograms.getElement(i));
825 // Perhaps the subprogram is in another CU (such as due to comdat
826 // folding, etc), in which case ignore it here.
827 if (SPMap[SP] != SPCU)
829 DIE *D = SPCU->getDIE(SP);
830 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
832 // If this subprogram has an abstract definition, reference that
833 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
835 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
836 // Lazily construct the subprogram if we didn't see either concrete or
837 // inlined versions during codegen. (except in -gmlt ^ where we want
838 // to omit these entirely)
839 D = SPCU->getOrCreateSubprogramDIE(SP);
841 // And attach the attributes
842 SPCU->applySubprogramAttributesToDefinition(SP, *D);
849 // Collect info for variables that were optimized out.
850 void DwarfDebug::collectDeadVariables() {
851 const Module *M = MMI->getModule();
853 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
854 for (MDNode *N : CU_Nodes->operands()) {
855 DICompileUnit TheCU(N);
856 // Construct subprogram DIE and add variables DIEs.
857 DwarfCompileUnit *SPCU =
858 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
859 assert(SPCU && "Unable to find Compile Unit!");
860 DIArray Subprograms = TheCU.getSubprograms();
861 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
862 DISubprogram SP(Subprograms.getElement(i));
863 if (ProcessedSPNodes.count(SP) != 0)
865 assert(SP.isSubprogram() &&
866 "CU's subprogram list contains a non-subprogram");
867 assert(SP.isDefinition() &&
868 "CU's subprogram list contains a subprogram declaration");
869 DIArray Variables = SP.getVariables();
870 if (Variables.getNumElements() == 0)
873 DIE *SPDIE = AbstractSPDies.lookup(SP);
875 SPDIE = SPCU->getDIE(SP);
877 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
878 DIVariable DV(Variables.getElement(vi));
879 assert(DV.isVariable());
880 DbgVariable NewVar(DV, DIExpression(nullptr), this);
881 auto VariableDie = SPCU->constructVariableDIE(NewVar);
882 SPCU->applyVariableAttributes(NewVar, *VariableDie);
883 SPDIE->addChild(std::move(VariableDie));
890 void DwarfDebug::finalizeModuleInfo() {
891 finishSubprogramDefinitions();
893 finishVariableDefinitions();
895 // Collect info for variables that were optimized out.
896 collectDeadVariables();
898 // Handle anything that needs to be done on a per-unit basis after
899 // all other generation.
900 for (const auto &TheU : getUnits()) {
901 // Emit DW_AT_containing_type attribute to connect types with their
902 // vtable holding type.
903 TheU->constructContainingTypeDIEs();
905 // Add CU specific attributes if we need to add any.
906 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
907 // If we're splitting the dwarf out now that we've got the entire
908 // CU then add the dwo id to it.
909 DwarfCompileUnit *SkCU =
910 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
911 if (useSplitDwarf()) {
912 // Emit a unique identifier for this CU.
913 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
914 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
915 dwarf::DW_FORM_data8, ID);
916 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
917 dwarf::DW_FORM_data8, ID);
919 // We don't keep track of which addresses are used in which CU so this
920 // is a bit pessimistic under LTO.
921 if (!AddrPool.isEmpty())
922 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
923 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
924 DwarfAddrSectionSym);
925 if (!TheU->getRangeLists().empty())
926 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
927 dwarf::DW_AT_GNU_ranges_base,
928 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
931 // If we have code split among multiple sections or non-contiguous
932 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
933 // remain in the .o file, otherwise add a DW_AT_low_pc.
934 // FIXME: We should use ranges allow reordering of code ala
935 // .subsections_via_symbols in mach-o. This would mean turning on
936 // ranges for all subprogram DIEs for mach-o.
937 DwarfCompileUnit &U =
938 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
939 unsigned NumRanges = TheU->getRanges().size();
942 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
943 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
944 DwarfDebugRangeSectionSym);
946 // A DW_AT_low_pc attribute may also be specified in combination with
947 // DW_AT_ranges to specify the default base address for use in
948 // location lists (see Section 2.6.2) and range lists (see Section
950 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
953 RangeSpan &Range = TheU->getRanges().back();
954 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
960 // Compute DIE offsets and sizes.
961 InfoHolder.computeSizeAndOffsets();
963 SkeletonHolder.computeSizeAndOffsets();
966 void DwarfDebug::endSections() {
967 // Filter labels by section.
968 for (const SymbolCU &SCU : ArangeLabels) {
969 if (SCU.Sym->isInSection()) {
970 // Make a note of this symbol and it's section.
971 const MCSection *Section = &SCU.Sym->getSection();
972 if (!Section->getKind().isMetadata())
973 SectionMap[Section].push_back(SCU);
975 // Some symbols (e.g. common/bss on mach-o) can have no section but still
976 // appear in the output. This sucks as we rely on sections to build
977 // arange spans. We can do it without, but it's icky.
978 SectionMap[nullptr].push_back(SCU);
982 // Build a list of sections used.
983 std::vector<const MCSection *> Sections;
984 for (const auto &it : SectionMap) {
985 const MCSection *Section = it.first;
986 Sections.push_back(Section);
989 // Sort the sections into order.
990 // This is only done to ensure consistent output order across different runs.
991 std::sort(Sections.begin(), Sections.end(), SectionSort);
993 // Add terminating symbols for each section.
994 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
995 const MCSection *Section = Sections[ID];
996 MCSymbol *Sym = nullptr;
999 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1000 // if we know the section name up-front. For user-created sections, the
1001 // resulting label may not be valid to use as a label. (section names can
1002 // use a greater set of characters on some systems)
1003 Sym = Asm->GetTempSymbol("debug_end", ID);
1004 Asm->OutStreamer.SwitchSection(Section);
1005 Asm->OutStreamer.EmitLabel(Sym);
1008 // Insert a final terminator.
1009 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1013 // Emit all Dwarf sections that should come after the content.
1014 void DwarfDebug::endModule() {
1015 assert(CurFn == nullptr);
1016 assert(CurMI == nullptr);
1021 // End any existing sections.
1022 // TODO: Does this need to happen?
1025 // Finalize the debug info for the module.
1026 finalizeModuleInfo();
1030 // Emit all the DIEs into a debug info section.
1033 // Corresponding abbreviations into a abbrev section.
1034 emitAbbreviations();
1036 // Emit info into a debug aranges section.
1037 if (GenerateARangeSection)
1040 // Emit info into a debug ranges section.
1043 if (useSplitDwarf()) {
1046 emitDebugAbbrevDWO();
1049 // Emit DWO addresses.
1050 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1052 // Emit info into a debug loc section.
1055 // Emit info into the dwarf accelerator table sections.
1056 if (useDwarfAccelTables()) {
1059 emitAccelNamespaces();
1063 // Emit the pubnames and pubtypes sections if requested.
1064 if (HasDwarfPubSections) {
1065 emitDebugPubNames(GenerateGnuPubSections);
1066 emitDebugPubTypes(GenerateGnuPubSections);
1071 AbstractVariables.clear();
1073 // Reset these for the next Module if we have one.
1077 // Find abstract variable, if any, associated with Var.
1078 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1079 DIVariable &Cleansed) {
1080 LLVMContext &Ctx = DV->getContext();
1081 // More then one inlined variable corresponds to one abstract variable.
1082 // FIXME: This duplication of variables when inlining should probably be
1083 // removed. It's done to allow each DIVariable to describe its location
1084 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1085 // make it accurate then remove this duplication/cleansing stuff.
1086 Cleansed = cleanseInlinedVariable(DV, Ctx);
1087 auto I = AbstractVariables.find(Cleansed);
1088 if (I != AbstractVariables.end())
1089 return I->second.get();
1093 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1094 DIVariable Cleansed;
1095 return getExistingAbstractVariable(DV, Cleansed);
1098 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1099 LexicalScope *Scope) {
1100 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
1101 addScopeVariable(Scope, AbsDbgVariable.get());
1102 AbstractVariables[Var] = std::move(AbsDbgVariable);
1105 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1106 const MDNode *ScopeNode) {
1107 DIVariable Cleansed = DV;
1108 if (getExistingAbstractVariable(DV, Cleansed))
1111 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1115 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1116 const MDNode *ScopeNode) {
1117 DIVariable Cleansed = DV;
1118 if (getExistingAbstractVariable(DV, Cleansed))
1121 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1122 createAbstractVariable(Cleansed, Scope);
1125 // If Var is a current function argument then add it to CurrentFnArguments list.
1126 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1127 if (!LScopes.isCurrentFunctionScope(Scope))
1129 DIVariable DV = Var->getVariable();
1130 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1132 unsigned ArgNo = DV.getArgNumber();
1136 size_t Size = CurrentFnArguments.size();
1138 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1139 // llvm::Function argument size is not good indicator of how many
1140 // arguments does the function have at source level.
1142 CurrentFnArguments.resize(ArgNo * 2);
1143 assert(!CurrentFnArguments[ArgNo - 1]);
1144 CurrentFnArguments[ArgNo - 1] = Var;
1148 // Collect variable information from side table maintained by MMI.
1149 void DwarfDebug::collectVariableInfoFromMMITable(
1150 SmallPtrSetImpl<const MDNode *> &Processed) {
1151 for (const auto &VI : MMI->getVariableDbgInfo()) {
1154 Processed.insert(VI.Var);
1155 DIVariable DV(VI.Var);
1156 DIExpression Expr(VI.Expr);
1157 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1159 // If variable scope is not found then skip this variable.
1163 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1164 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1165 DbgVariable *RegVar = ConcreteVariables.back().get();
1166 RegVar->setFrameIndex(VI.Slot);
1167 addScopeVariable(Scope, RegVar);
1171 // Get .debug_loc entry for the instruction range starting at MI.
1172 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1173 const MDNode *Expr = MI->getDebugExpression();
1174 const MDNode *Var = MI->getDebugVariable();
1176 assert(MI->getNumOperands() == 4);
1177 if (MI->getOperand(0).isReg()) {
1178 MachineLocation MLoc;
1179 // If the second operand is an immediate, this is a
1180 // register-indirect address.
1181 if (!MI->getOperand(1).isImm())
1182 MLoc.set(MI->getOperand(0).getReg());
1184 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1185 return DebugLocEntry::Value(Var, Expr, MLoc);
1187 if (MI->getOperand(0).isImm())
1188 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1189 if (MI->getOperand(0).isFPImm())
1190 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1191 if (MI->getOperand(0).isCImm())
1192 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1194 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1197 /// Determine whether two variable pieces overlap.
1198 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1199 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1201 unsigned l1 = P1.getPieceOffset();
1202 unsigned l2 = P2.getPieceOffset();
1203 unsigned r1 = l1 + P1.getPieceSize();
1204 unsigned r2 = l2 + P2.getPieceSize();
1205 // True where [l1,r1[ and [r1,r2[ overlap.
1206 return (l1 < r2) && (l2 < r1);
1209 /// Build the location list for all DBG_VALUEs in the function that
1210 /// describe the same variable. If the ranges of several independent
1211 /// pieces of the same variable overlap partially, split them up and
1212 /// combine the ranges. The resulting DebugLocEntries are will have
1213 /// strict monotonically increasing begin addresses and will never
1218 // Ranges History [var, loc, piece ofs size]
1219 // 0 | [x, (reg0, piece 0, 32)]
1220 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1222 // 3 | [clobber reg0]
1223 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1227 // [0-1] [x, (reg0, piece 0, 32)]
1228 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1229 // [3-4] [x, (reg1, piece 32, 32)]
1230 // [4- ] [x, (mem, piece 0, 64)]
1232 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1233 const DbgValueHistoryMap::InstrRanges &Ranges) {
1234 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1236 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1237 const MachineInstr *Begin = I->first;
1238 const MachineInstr *End = I->second;
1239 assert(Begin->isDebugValue() && "Invalid History entry");
1241 // Check if a variable is inaccessible in this range.
1242 if (Begin->getNumOperands() > 1 &&
1243 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1248 // If this piece overlaps with any open ranges, truncate them.
1249 DIExpression DIExpr = Begin->getDebugExpression();
1250 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1251 [&](DebugLocEntry::Value R) {
1252 return piecesOverlap(DIExpr, R.getExpression());
1254 OpenRanges.erase(Last, OpenRanges.end());
1256 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1257 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1259 const MCSymbol *EndLabel;
1261 EndLabel = getLabelAfterInsn(End);
1262 else if (std::next(I) == Ranges.end())
1263 EndLabel = FunctionEndSym;
1265 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1266 assert(EndLabel && "Forgot label after instruction ending a range!");
1268 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1270 auto Value = getDebugLocValue(Begin);
1271 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1272 bool couldMerge = false;
1274 // If this is a piece, it may belong to the current DebugLocEntry.
1275 if (DIExpr.isVariablePiece()) {
1276 // Add this value to the list of open ranges.
1277 OpenRanges.push_back(Value);
1279 // Attempt to add the piece to the last entry.
1280 if (!DebugLoc.empty())
1281 if (DebugLoc.back().MergeValues(Loc))
1286 // Need to add a new DebugLocEntry. Add all values from still
1287 // valid non-overlapping pieces.
1288 if (OpenRanges.size())
1289 Loc.addValues(OpenRanges);
1291 DebugLoc.push_back(std::move(Loc));
1294 // Attempt to coalesce the ranges of two otherwise identical
1296 auto CurEntry = DebugLoc.rbegin();
1297 auto PrevEntry = std::next(CurEntry);
1298 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1299 DebugLoc.pop_back();
1302 dbgs() << CurEntry->getValues().size() << " Values:\n";
1303 for (auto Value : CurEntry->getValues()) {
1304 Value.getVariable()->dump();
1305 Value.getExpression()->dump();
1307 dbgs() << "-----\n";
1313 // Find variables for each lexical scope.
1315 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1316 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1317 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1319 // Grab the variable info that was squirreled away in the MMI side-table.
1320 collectVariableInfoFromMMITable(Processed);
1322 for (const auto &I : DbgValues) {
1323 DIVariable DV(I.first);
1324 if (Processed.count(DV))
1327 // Instruction ranges, specifying where DV is accessible.
1328 const auto &Ranges = I.second;
1332 LexicalScope *Scope = nullptr;
1333 if (MDNode *IA = DV.getInlinedAt()) {
1334 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1335 Scope = LScopes.findInlinedScope(DebugLoc::get(
1336 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1338 Scope = LScopes.findLexicalScope(DV.getContext());
1339 // If variable scope is not found then skip this variable.
1343 Processed.insert(DV);
1344 const MachineInstr *MInsn = Ranges.front().first;
1345 assert(MInsn->isDebugValue() && "History must begin with debug value");
1346 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1347 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1348 DbgVariable *RegVar = ConcreteVariables.back().get();
1349 addScopeVariable(Scope, RegVar);
1351 // Check if the first DBG_VALUE is valid for the rest of the function.
1352 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1355 // Handle multiple DBG_VALUE instructions describing one variable.
1356 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1358 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1359 DebugLocList &LocList = DotDebugLocEntries.back();
1362 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1364 // Build the location list for this variable.
1365 buildLocationList(LocList.List, Ranges);
1368 // Collect info for variables that were optimized out.
1369 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1370 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1371 DIVariable DV(Variables.getElement(i));
1372 assert(DV.isVariable());
1373 if (!Processed.insert(DV))
1375 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1376 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1377 DIExpression NoExpr;
1378 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1379 addScopeVariable(Scope, ConcreteVariables.back().get());
1384 // Return Label preceding the instruction.
1385 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1386 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1387 assert(Label && "Didn't insert label before instruction");
1391 // Return Label immediately following the instruction.
1392 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1393 return LabelsAfterInsn.lookup(MI);
1396 // Process beginning of an instruction.
1397 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1398 assert(CurMI == nullptr);
1400 // Check if source location changes, but ignore DBG_VALUE locations.
1401 if (!MI->isDebugValue()) {
1402 DebugLoc DL = MI->getDebugLoc();
1403 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1406 if (DL == PrologEndLoc) {
1407 Flags |= DWARF2_FLAG_PROLOGUE_END;
1408 PrologEndLoc = DebugLoc();
1410 if (PrologEndLoc.isUnknown())
1411 Flags |= DWARF2_FLAG_IS_STMT;
1413 if (!DL.isUnknown()) {
1414 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1415 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1417 recordSourceLine(0, 0, nullptr, 0);
1421 // Insert labels where requested.
1422 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1423 LabelsBeforeInsn.find(MI);
1426 if (I == LabelsBeforeInsn.end())
1429 // Label already assigned.
1434 PrevLabel = MMI->getContext().CreateTempSymbol();
1435 Asm->OutStreamer.EmitLabel(PrevLabel);
1437 I->second = PrevLabel;
1440 // Process end of an instruction.
1441 void DwarfDebug::endInstruction() {
1442 assert(CurMI != nullptr);
1443 // Don't create a new label after DBG_VALUE instructions.
1444 // They don't generate code.
1445 if (!CurMI->isDebugValue())
1446 PrevLabel = nullptr;
1448 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1449 LabelsAfterInsn.find(CurMI);
1453 if (I == LabelsAfterInsn.end())
1456 // Label already assigned.
1460 // We need a label after this instruction.
1462 PrevLabel = MMI->getContext().CreateTempSymbol();
1463 Asm->OutStreamer.EmitLabel(PrevLabel);
1465 I->second = PrevLabel;
1468 // Each LexicalScope has first instruction and last instruction to mark
1469 // beginning and end of a scope respectively. Create an inverse map that list
1470 // scopes starts (and ends) with an instruction. One instruction may start (or
1471 // end) multiple scopes. Ignore scopes that are not reachable.
1472 void DwarfDebug::identifyScopeMarkers() {
1473 SmallVector<LexicalScope *, 4> WorkList;
1474 WorkList.push_back(LScopes.getCurrentFunctionScope());
1475 while (!WorkList.empty()) {
1476 LexicalScope *S = WorkList.pop_back_val();
1478 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1479 if (!Children.empty())
1480 WorkList.append(Children.begin(), Children.end());
1482 if (S->isAbstractScope())
1485 for (const InsnRange &R : S->getRanges()) {
1486 assert(R.first && "InsnRange does not have first instruction!");
1487 assert(R.second && "InsnRange does not have second instruction!");
1488 requestLabelBeforeInsn(R.first);
1489 requestLabelAfterInsn(R.second);
1494 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1495 // First known non-DBG_VALUE and non-frame setup location marks
1496 // the beginning of the function body.
1497 for (const auto &MBB : *MF)
1498 for (const auto &MI : MBB)
1499 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1500 !MI.getDebugLoc().isUnknown())
1501 return MI.getDebugLoc();
1505 // Gather pre-function debug information. Assumes being called immediately
1506 // after the function entry point has been emitted.
1507 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1510 // If there's no debug info for the function we're not going to do anything.
1511 if (!MMI->hasDebugInfo())
1514 auto DI = FunctionDIs.find(MF->getFunction());
1515 if (DI == FunctionDIs.end())
1518 // Grab the lexical scopes for the function, if we don't have any of those
1519 // then we're not going to be able to do anything.
1520 LScopes.initialize(*MF);
1521 if (LScopes.empty())
1524 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1526 // Make sure that each lexical scope will have a begin/end label.
1527 identifyScopeMarkers();
1529 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1530 // belongs to so that we add to the correct per-cu line table in the
1532 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1533 // FnScope->getScopeNode() and DI->second should represent the same function,
1534 // though they may not be the same MDNode due to inline functions merged in
1535 // LTO where the debug info metadata still differs (either due to distinct
1536 // written differences - two versions of a linkonce_odr function
1537 // written/copied into two separate files, or some sub-optimal metadata that
1538 // isn't structurally identical (see: file path/name info from clang, which
1539 // includes the directory of the cpp file being built, even when the file name
1540 // is absolute (such as an <> lookup header)))
1541 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1542 assert(TheCU && "Unable to find compile unit!");
1543 if (Asm->OutStreamer.hasRawTextSupport())
1544 // Use a single line table if we are generating assembly.
1545 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1547 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1549 // Emit a label for the function so that we have a beginning address.
1550 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1551 // Assumes in correct section after the entry point.
1552 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1554 // Calculate history for local variables.
1555 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1558 // Request labels for the full history.
1559 for (const auto &I : DbgValues) {
1560 const auto &Ranges = I.second;
1564 // The first mention of a function argument gets the FunctionBeginSym
1565 // label, so arguments are visible when breaking at function entry.
1566 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1567 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1568 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1569 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1570 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1571 // Mark all non-overlapping initial pieces.
1572 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1573 DIExpression Piece = I->first->getDebugExpression();
1574 if (std::all_of(Ranges.begin(), I,
1575 [&](DbgValueHistoryMap::InstrRange Pred) {
1576 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1578 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1585 for (const auto &Range : Ranges) {
1586 requestLabelBeforeInsn(Range.first);
1588 requestLabelAfterInsn(Range.second);
1592 PrevInstLoc = DebugLoc();
1593 PrevLabel = FunctionBeginSym;
1595 // Record beginning of function.
1596 PrologEndLoc = findPrologueEndLoc(MF);
1597 if (!PrologEndLoc.isUnknown()) {
1598 DebugLoc FnStartDL =
1599 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1601 FnStartDL.getLine(), FnStartDL.getCol(),
1602 FnStartDL.getScope(MF->getFunction()->getContext()),
1603 // We'd like to list the prologue as "not statements" but GDB behaves
1604 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1605 DWARF2_FLAG_IS_STMT);
1609 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1610 if (addCurrentFnArgument(Var, LS))
1612 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1613 DIVariable DV = Var->getVariable();
1614 // Variables with positive arg numbers are parameters.
1615 if (unsigned ArgNum = DV.getArgNumber()) {
1616 // Keep all parameters in order at the start of the variable list to ensure
1617 // function types are correct (no out-of-order parameters)
1619 // This could be improved by only doing it for optimized builds (unoptimized
1620 // builds have the right order to begin with), searching from the back (this
1621 // would catch the unoptimized case quickly), or doing a binary search
1622 // rather than linear search.
1623 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1624 while (I != Vars.end()) {
1625 unsigned CurNum = (*I)->getVariable().getArgNumber();
1626 // A local (non-parameter) variable has been found, insert immediately
1630 // A later indexed parameter has been found, insert immediately before it.
1631 if (CurNum > ArgNum)
1635 Vars.insert(I, Var);
1639 Vars.push_back(Var);
1642 // Gather and emit post-function debug information.
1643 void DwarfDebug::endFunction(const MachineFunction *MF) {
1644 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1645 // though the beginFunction may not be called at all.
1646 // We should handle both cases.
1650 assert(CurFn == MF);
1651 assert(CurFn != nullptr);
1653 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1654 !FunctionDIs.count(MF->getFunction())) {
1655 // If we don't have a lexical scope for this function then there will
1656 // be a hole in the range information. Keep note of this by setting the
1657 // previously used section to nullptr.
1663 // Define end label for subprogram.
1664 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1665 // Assumes in correct section after the entry point.
1666 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1668 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1669 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1671 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1672 collectVariableInfo(ProcessedVars);
1674 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1675 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1677 // Add the range of this function to the list of ranges for the CU.
1678 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1680 // Under -gmlt, skip building the subprogram if there are no inlined
1681 // subroutines inside it.
1682 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1683 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1684 assert(ScopeVariables.empty());
1685 assert(CurrentFnArguments.empty());
1686 assert(DbgValues.empty());
1687 assert(AbstractVariables.empty());
1688 LabelsBeforeInsn.clear();
1689 LabelsAfterInsn.clear();
1690 PrevLabel = nullptr;
1695 // Construct abstract scopes.
1696 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1697 DISubprogram SP(AScope->getScopeNode());
1698 assert(SP.isSubprogram());
1699 // Collect info for variables that were optimized out.
1700 DIArray Variables = SP.getVariables();
1701 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1702 DIVariable DV(Variables.getElement(i));
1703 assert(DV && DV.isVariable());
1704 if (!ProcessedVars.insert(DV))
1706 ensureAbstractVariableIsCreated(DV, DV.getContext());
1708 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1711 constructSubprogramScopeDIE(TheCU, FnScope);
1714 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1715 // DbgVariables except those that are also in AbstractVariables (since they
1716 // can be used cross-function)
1717 ScopeVariables.clear();
1718 CurrentFnArguments.clear();
1720 LabelsBeforeInsn.clear();
1721 LabelsAfterInsn.clear();
1722 PrevLabel = nullptr;
1726 // Register a source line with debug info. Returns the unique label that was
1727 // emitted and which provides correspondence to the source line list.
1728 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1733 unsigned Discriminator = 0;
1734 if (DIScope Scope = DIScope(S)) {
1735 assert(Scope.isScope());
1736 Fn = Scope.getFilename();
1737 Dir = Scope.getDirectory();
1738 if (Scope.isLexicalBlockFile())
1739 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1741 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1742 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1743 .getOrCreateSourceID(Fn, Dir);
1745 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1749 //===----------------------------------------------------------------------===//
1751 //===----------------------------------------------------------------------===//
1753 // Emit initial Dwarf sections with a label at the start of each one.
1754 void DwarfDebug::emitSectionLabels() {
1755 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1757 // Dwarf sections base addresses.
1758 DwarfInfoSectionSym =
1759 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1760 if (useSplitDwarf()) {
1761 DwarfInfoDWOSectionSym =
1762 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1763 DwarfTypesDWOSectionSym =
1764 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1766 DwarfAbbrevSectionSym =
1767 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1768 if (useSplitDwarf())
1769 DwarfAbbrevDWOSectionSym = emitSectionSym(
1770 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1771 if (GenerateARangeSection)
1772 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1774 DwarfLineSectionSym =
1775 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1776 if (GenerateGnuPubSections) {
1777 DwarfGnuPubNamesSectionSym =
1778 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1779 DwarfGnuPubTypesSectionSym =
1780 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1781 } else if (HasDwarfPubSections) {
1782 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1783 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1786 DwarfStrSectionSym =
1787 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1788 if (useSplitDwarf()) {
1789 DwarfStrDWOSectionSym =
1790 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1791 DwarfAddrSectionSym =
1792 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1793 DwarfDebugLocSectionSym =
1794 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1796 DwarfDebugLocSectionSym =
1797 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1798 DwarfDebugRangeSectionSym =
1799 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1802 // Recursively emits a debug information entry.
1803 void DwarfDebug::emitDIE(DIE &Die) {
1804 // Get the abbreviation for this DIE.
1805 const DIEAbbrev &Abbrev = Die.getAbbrev();
1807 // Emit the code (index) for the abbreviation.
1808 if (Asm->isVerbose())
1809 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1810 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1811 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1812 dwarf::TagString(Abbrev.getTag()));
1813 Asm->EmitULEB128(Abbrev.getNumber());
1815 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1816 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1818 // Emit the DIE attribute values.
1819 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1820 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1821 dwarf::Form Form = AbbrevData[i].getForm();
1822 assert(Form && "Too many attributes for DIE (check abbreviation)");
1824 if (Asm->isVerbose()) {
1825 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1826 if (Attr == dwarf::DW_AT_accessibility)
1827 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1828 cast<DIEInteger>(Values[i])->getValue()));
1831 // Emit an attribute using the defined form.
1832 Values[i]->EmitValue(Asm, Form);
1835 // Emit the DIE children if any.
1836 if (Abbrev.hasChildren()) {
1837 for (auto &Child : Die.getChildren())
1840 Asm->OutStreamer.AddComment("End Of Children Mark");
1845 // Emit the debug info section.
1846 void DwarfDebug::emitDebugInfo() {
1847 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1849 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1852 // Emit the abbreviation section.
1853 void DwarfDebug::emitAbbreviations() {
1854 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1856 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1859 // Emit the last address of the section and the end of the line matrix.
1860 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1861 // Define last address of section.
1862 Asm->OutStreamer.AddComment("Extended Op");
1865 Asm->OutStreamer.AddComment("Op size");
1866 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1867 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1868 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1870 Asm->OutStreamer.AddComment("Section end label");
1872 Asm->OutStreamer.EmitSymbolValue(
1873 Asm->GetTempSymbol("section_end", SectionEnd),
1874 Asm->getDataLayout().getPointerSize());
1876 // Mark end of matrix.
1877 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1883 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1884 StringRef TableName, StringRef SymName) {
1885 Accel.FinalizeTable(Asm, TableName);
1886 Asm->OutStreamer.SwitchSection(Section);
1887 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1888 Asm->OutStreamer.EmitLabel(SectionBegin);
1890 // Emit the full data.
1891 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1894 // Emit visible names into a hashed accelerator table section.
1895 void DwarfDebug::emitAccelNames() {
1896 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1897 "Names", "names_begin");
1900 // Emit objective C classes and categories into a hashed accelerator table
1902 void DwarfDebug::emitAccelObjC() {
1903 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1904 "ObjC", "objc_begin");
1907 // Emit namespace dies into a hashed accelerator table.
1908 void DwarfDebug::emitAccelNamespaces() {
1909 emitAccel(AccelNamespace,
1910 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1911 "namespac", "namespac_begin");
1914 // Emit type dies into a hashed accelerator table.
1915 void DwarfDebug::emitAccelTypes() {
1916 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1917 "types", "types_begin");
1920 // Public name handling.
1921 // The format for the various pubnames:
1923 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1924 // for the DIE that is named.
1926 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1927 // into the CU and the index value is computed according to the type of value
1928 // for the DIE that is named.
1930 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1931 // it's the offset within the debug_info/debug_types dwo section, however, the
1932 // reference in the pubname header doesn't change.
1934 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1935 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1937 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1939 // We could have a specification DIE that has our most of our knowledge,
1940 // look for that now.
1941 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1943 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1944 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1945 Linkage = dwarf::GIEL_EXTERNAL;
1946 } else if (Die->findAttribute(dwarf::DW_AT_external))
1947 Linkage = dwarf::GIEL_EXTERNAL;
1949 switch (Die->getTag()) {
1950 case dwarf::DW_TAG_class_type:
1951 case dwarf::DW_TAG_structure_type:
1952 case dwarf::DW_TAG_union_type:
1953 case dwarf::DW_TAG_enumeration_type:
1954 return dwarf::PubIndexEntryDescriptor(
1955 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1956 ? dwarf::GIEL_STATIC
1957 : dwarf::GIEL_EXTERNAL);
1958 case dwarf::DW_TAG_typedef:
1959 case dwarf::DW_TAG_base_type:
1960 case dwarf::DW_TAG_subrange_type:
1961 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1962 case dwarf::DW_TAG_namespace:
1963 return dwarf::GIEK_TYPE;
1964 case dwarf::DW_TAG_subprogram:
1965 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1966 case dwarf::DW_TAG_constant:
1967 case dwarf::DW_TAG_variable:
1968 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1969 case dwarf::DW_TAG_enumerator:
1970 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1971 dwarf::GIEL_STATIC);
1973 return dwarf::GIEK_NONE;
1977 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1979 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1980 const MCSection *PSec =
1981 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1982 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1984 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1987 void DwarfDebug::emitDebugPubSection(
1988 bool GnuStyle, const MCSection *PSec, StringRef Name,
1989 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1990 for (const auto &NU : CUMap) {
1991 DwarfCompileUnit *TheU = NU.second;
1993 const auto &Globals = (TheU->*Accessor)();
1995 if (Globals.empty())
1998 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2000 unsigned ID = TheU->getUniqueID();
2002 // Start the dwarf pubnames section.
2003 Asm->OutStreamer.SwitchSection(PSec);
2006 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2007 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2008 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2009 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2011 Asm->OutStreamer.EmitLabel(BeginLabel);
2013 Asm->OutStreamer.AddComment("DWARF Version");
2014 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2016 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2017 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2019 Asm->OutStreamer.AddComment("Compilation Unit Length");
2020 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2022 // Emit the pubnames for this compilation unit.
2023 for (const auto &GI : Globals) {
2024 const char *Name = GI.getKeyData();
2025 const DIE *Entity = GI.second;
2027 Asm->OutStreamer.AddComment("DIE offset");
2028 Asm->EmitInt32(Entity->getOffset());
2031 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2032 Asm->OutStreamer.AddComment(
2033 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2034 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2035 Asm->EmitInt8(Desc.toBits());
2038 Asm->OutStreamer.AddComment("External Name");
2039 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2042 Asm->OutStreamer.AddComment("End Mark");
2044 Asm->OutStreamer.EmitLabel(EndLabel);
2048 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2049 const MCSection *PSec =
2050 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2051 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2053 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2056 // Emit visible names into a debug str section.
2057 void DwarfDebug::emitDebugStr() {
2058 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2059 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2062 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2063 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2064 const DITypeIdentifierMap &Map,
2065 ArrayRef<DebugLocEntry::Value> Values) {
2066 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2067 return P.isVariablePiece();
2068 }) && "all values are expected to be pieces");
2069 assert(std::is_sorted(Values.begin(), Values.end()) &&
2070 "pieces are expected to be sorted");
2072 unsigned Offset = 0;
2073 for (auto Piece : Values) {
2074 DIExpression Expr = Piece.getExpression();
2075 unsigned PieceOffset = Expr.getPieceOffset();
2076 unsigned PieceSize = Expr.getPieceSize();
2077 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2078 if (Offset < PieceOffset) {
2079 // The DWARF spec seriously mandates pieces with no locations for gaps.
2080 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2081 Offset += PieceOffset-Offset;
2084 Offset += PieceSize;
2086 const unsigned SizeOfByte = 8;
2088 DIVariable Var = Piece.getVariable();
2089 assert(!Var.isIndirect() && "indirect address for piece");
2090 unsigned VarSize = Var.getSizeInBits(Map);
2091 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2092 && "piece is larger than or outside of variable");
2093 assert(PieceSize*SizeOfByte != VarSize
2094 && "piece covers entire variable");
2096 if (Piece.isLocation() && Piece.getLoc().isReg())
2097 Asm->EmitDwarfRegOpPiece(Streamer,
2099 PieceSize*SizeOfByte);
2101 emitDebugLocValue(Streamer, Piece);
2102 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2108 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2109 const DebugLocEntry &Entry) {
2110 const DebugLocEntry::Value Value = Entry.getValues()[0];
2111 if (Value.isVariablePiece())
2112 // Emit all pieces that belong to the same variable and range.
2113 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2115 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2116 emitDebugLocValue(Streamer, Value);
2119 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2120 const DebugLocEntry::Value &Value) {
2121 DIVariable DV = Value.getVariable();
2123 if (Value.isInt()) {
2124 DIBasicType BTy(resolve(DV.getType()));
2125 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2126 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2127 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2128 Streamer.EmitSLEB128(Value.getInt());
2130 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2131 Streamer.EmitULEB128(Value.getInt());
2133 } else if (Value.isLocation()) {
2134 MachineLocation Loc = Value.getLoc();
2135 DIExpression Expr = Value.getExpression();
2138 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2140 // Complex address entry.
2141 unsigned N = Expr.getNumElements();
2143 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2144 if (Loc.getOffset()) {
2146 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2147 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2148 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2149 Streamer.EmitSLEB128(Expr.getElement(1));
2151 // If first address element is OpPlus then emit
2152 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2153 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2154 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2158 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2161 // Emit remaining complex address elements.
2162 for (; i < N; ++i) {
2163 uint64_t Element = Expr.getElement(i);
2164 if (Element == dwarf::DW_OP_plus) {
2165 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2166 Streamer.EmitULEB128(Expr.getElement(++i));
2167 } else if (Element == dwarf::DW_OP_deref) {
2169 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2170 } else if (Element == dwarf::DW_OP_piece) {
2172 // handled in emitDebugLocEntry.
2174 llvm_unreachable("unknown Opcode found in complex address");
2178 // else ... ignore constant fp. There is not any good way to
2179 // to represent them here in dwarf.
2183 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2184 Asm->OutStreamer.AddComment("Loc expr size");
2185 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2186 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2187 Asm->EmitLabelDifference(end, begin, 2);
2188 Asm->OutStreamer.EmitLabel(begin);
2190 APByteStreamer Streamer(*Asm);
2191 emitDebugLocEntry(Streamer, Entry);
2193 Asm->OutStreamer.EmitLabel(end);
2196 // Emit locations into the debug loc section.
2197 void DwarfDebug::emitDebugLoc() {
2198 // Start the dwarf loc section.
2199 Asm->OutStreamer.SwitchSection(
2200 Asm->getObjFileLowering().getDwarfLocSection());
2201 unsigned char Size = Asm->getDataLayout().getPointerSize();
2202 for (const auto &DebugLoc : DotDebugLocEntries) {
2203 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2204 const DwarfCompileUnit *CU = DebugLoc.CU;
2205 assert(!CU->getRanges().empty());
2206 for (const auto &Entry : DebugLoc.List) {
2207 // Set up the range. This range is relative to the entry point of the
2208 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2209 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2210 if (CU->getRanges().size() == 1) {
2211 // Grab the begin symbol from the first range as our base.
2212 const MCSymbol *Base = CU->getRanges()[0].getStart();
2213 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2214 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2216 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2217 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2220 emitDebugLocEntryLocation(Entry);
2222 Asm->OutStreamer.EmitIntValue(0, Size);
2223 Asm->OutStreamer.EmitIntValue(0, Size);
2227 void DwarfDebug::emitDebugLocDWO() {
2228 Asm->OutStreamer.SwitchSection(
2229 Asm->getObjFileLowering().getDwarfLocDWOSection());
2230 for (const auto &DebugLoc : DotDebugLocEntries) {
2231 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2232 for (const auto &Entry : DebugLoc.List) {
2233 // Just always use start_length for now - at least that's one address
2234 // rather than two. We could get fancier and try to, say, reuse an
2235 // address we know we've emitted elsewhere (the start of the function?
2236 // The start of the CU or CU subrange that encloses this range?)
2237 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2238 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2239 Asm->EmitULEB128(idx);
2240 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2242 emitDebugLocEntryLocation(Entry);
2244 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2249 const MCSymbol *Start, *End;
2252 // Emit a debug aranges section, containing a CU lookup for any
2253 // address we can tie back to a CU.
2254 void DwarfDebug::emitDebugARanges() {
2255 // Start the dwarf aranges section.
2256 Asm->OutStreamer.SwitchSection(
2257 Asm->getObjFileLowering().getDwarfARangesSection());
2259 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2263 // Build a list of sections used.
2264 std::vector<const MCSection *> Sections;
2265 for (const auto &it : SectionMap) {
2266 const MCSection *Section = it.first;
2267 Sections.push_back(Section);
2270 // Sort the sections into order.
2271 // This is only done to ensure consistent output order across different runs.
2272 std::sort(Sections.begin(), Sections.end(), SectionSort);
2274 // Build a set of address spans, sorted by CU.
2275 for (const MCSection *Section : Sections) {
2276 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2277 if (List.size() < 2)
2280 // Sort the symbols by offset within the section.
2281 std::sort(List.begin(), List.end(),
2282 [&](const SymbolCU &A, const SymbolCU &B) {
2283 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2284 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2286 // Symbols with no order assigned should be placed at the end.
2287 // (e.g. section end labels)
2295 // If we have no section (e.g. common), just write out
2296 // individual spans for each symbol.
2298 for (const SymbolCU &Cur : List) {
2300 Span.Start = Cur.Sym;
2303 Spans[Cur.CU].push_back(Span);
2306 // Build spans between each label.
2307 const MCSymbol *StartSym = List[0].Sym;
2308 for (size_t n = 1, e = List.size(); n < e; n++) {
2309 const SymbolCU &Prev = List[n - 1];
2310 const SymbolCU &Cur = List[n];
2312 // Try and build the longest span we can within the same CU.
2313 if (Cur.CU != Prev.CU) {
2315 Span.Start = StartSym;
2317 Spans[Prev.CU].push_back(Span);
2324 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2326 // Build a list of CUs used.
2327 std::vector<DwarfCompileUnit *> CUs;
2328 for (const auto &it : Spans) {
2329 DwarfCompileUnit *CU = it.first;
2333 // Sort the CU list (again, to ensure consistent output order).
2334 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2335 return A->getUniqueID() < B->getUniqueID();
2338 // Emit an arange table for each CU we used.
2339 for (DwarfCompileUnit *CU : CUs) {
2340 std::vector<ArangeSpan> &List = Spans[CU];
2342 // Emit size of content not including length itself.
2343 unsigned ContentSize =
2344 sizeof(int16_t) + // DWARF ARange version number
2345 sizeof(int32_t) + // Offset of CU in the .debug_info section
2346 sizeof(int8_t) + // Pointer Size (in bytes)
2347 sizeof(int8_t); // Segment Size (in bytes)
2349 unsigned TupleSize = PtrSize * 2;
2351 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2353 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2355 ContentSize += Padding;
2356 ContentSize += (List.size() + 1) * TupleSize;
2358 // For each compile unit, write the list of spans it covers.
2359 Asm->OutStreamer.AddComment("Length of ARange Set");
2360 Asm->EmitInt32(ContentSize);
2361 Asm->OutStreamer.AddComment("DWARF Arange version number");
2362 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2363 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2364 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2365 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2366 Asm->EmitInt8(PtrSize);
2367 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2370 Asm->OutStreamer.EmitFill(Padding, 0xff);
2372 for (const ArangeSpan &Span : List) {
2373 Asm->EmitLabelReference(Span.Start, PtrSize);
2375 // Calculate the size as being from the span start to it's end.
2377 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2379 // For symbols without an end marker (e.g. common), we
2380 // write a single arange entry containing just that one symbol.
2381 uint64_t Size = SymSize[Span.Start];
2385 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2389 Asm->OutStreamer.AddComment("ARange terminator");
2390 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2391 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2395 // Emit visible names into a debug ranges section.
2396 void DwarfDebug::emitDebugRanges() {
2397 // Start the dwarf ranges section.
2398 Asm->OutStreamer.SwitchSection(
2399 Asm->getObjFileLowering().getDwarfRangesSection());
2401 // Size for our labels.
2402 unsigned char Size = Asm->getDataLayout().getPointerSize();
2404 // Grab the specific ranges for the compile units in the module.
2405 for (const auto &I : CUMap) {
2406 DwarfCompileUnit *TheCU = I.second;
2408 // Iterate over the misc ranges for the compile units in the module.
2409 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2410 // Emit our symbol so we can find the beginning of the range.
2411 Asm->OutStreamer.EmitLabel(List.getSym());
2413 for (const RangeSpan &Range : List.getRanges()) {
2414 const MCSymbol *Begin = Range.getStart();
2415 const MCSymbol *End = Range.getEnd();
2416 assert(Begin && "Range without a begin symbol?");
2417 assert(End && "Range without an end symbol?");
2418 if (TheCU->getRanges().size() == 1) {
2419 // Grab the begin symbol from the first range as our base.
2420 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2421 Asm->EmitLabelDifference(Begin, Base, Size);
2422 Asm->EmitLabelDifference(End, Base, Size);
2424 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2425 Asm->OutStreamer.EmitSymbolValue(End, Size);
2429 // And terminate the list with two 0 values.
2430 Asm->OutStreamer.EmitIntValue(0, Size);
2431 Asm->OutStreamer.EmitIntValue(0, Size);
2434 // Now emit a range for the CU itself.
2435 if (TheCU->getRanges().size() > 1) {
2436 Asm->OutStreamer.EmitLabel(
2437 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2438 for (const RangeSpan &Range : TheCU->getRanges()) {
2439 const MCSymbol *Begin = Range.getStart();
2440 const MCSymbol *End = Range.getEnd();
2441 assert(Begin && "Range without a begin symbol?");
2442 assert(End && "Range without an end symbol?");
2443 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2444 Asm->OutStreamer.EmitSymbolValue(End, Size);
2446 // And terminate the list with two 0 values.
2447 Asm->OutStreamer.EmitIntValue(0, Size);
2448 Asm->OutStreamer.EmitIntValue(0, Size);
2453 // DWARF5 Experimental Separate Dwarf emitters.
2455 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2456 std::unique_ptr<DwarfUnit> NewU) {
2457 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2458 U.getCUNode().getSplitDebugFilename());
2460 if (!CompilationDir.empty())
2461 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2463 addGnuPubAttributes(*NewU, Die);
2465 SkeletonHolder.addUnit(std::move(NewU));
2468 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2469 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2470 // DW_AT_addr_base, DW_AT_ranges_base.
2471 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2473 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2474 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2475 DwarfCompileUnit &NewCU = *OwnedUnit;
2476 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2477 DwarfInfoSectionSym);
2479 NewCU.initStmtList(DwarfLineSectionSym);
2481 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2486 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2487 // compile units that would normally be in debug_info.
2488 void DwarfDebug::emitDebugInfoDWO() {
2489 assert(useSplitDwarf() && "No split dwarf debug info?");
2490 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2491 // emit relocations into the dwo file.
2492 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2495 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2496 // abbreviations for the .debug_info.dwo section.
2497 void DwarfDebug::emitDebugAbbrevDWO() {
2498 assert(useSplitDwarf() && "No split dwarf?");
2499 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2502 void DwarfDebug::emitDebugLineDWO() {
2503 assert(useSplitDwarf() && "No split dwarf?");
2504 Asm->OutStreamer.SwitchSection(
2505 Asm->getObjFileLowering().getDwarfLineDWOSection());
2506 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2509 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2510 // string section and is identical in format to traditional .debug_str
2512 void DwarfDebug::emitDebugStrDWO() {
2513 assert(useSplitDwarf() && "No split dwarf?");
2514 const MCSection *OffSec =
2515 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2516 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2520 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2521 if (!useSplitDwarf())
2524 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2525 return &SplitTypeUnitFileTable;
2528 static uint64_t makeTypeSignature(StringRef Identifier) {
2530 Hash.update(Identifier);
2531 // ... take the least significant 8 bytes and return those. Our MD5
2532 // implementation always returns its results in little endian, swap bytes
2534 MD5::MD5Result Result;
2536 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2539 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2540 StringRef Identifier, DIE &RefDie,
2541 DICompositeType CTy) {
2542 // Fast path if we're building some type units and one has already used the
2543 // address pool we know we're going to throw away all this work anyway, so
2544 // don't bother building dependent types.
2545 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2548 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2550 CU.addDIETypeSignature(RefDie, *TU);
2554 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2555 AddrPool.resetUsedFlag();
2557 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2558 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2559 this, &InfoHolder, getDwoLineTable(CU));
2560 DwarfTypeUnit &NewTU = *OwnedUnit;
2561 DIE &UnitDie = NewTU.getUnitDie();
2563 TypeUnitsUnderConstruction.push_back(
2564 std::make_pair(std::move(OwnedUnit), CTy));
2566 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2569 uint64_t Signature = makeTypeSignature(Identifier);
2570 NewTU.setTypeSignature(Signature);
2572 if (useSplitDwarf())
2573 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2574 DwarfTypesDWOSectionSym);
2576 CU.applyStmtList(UnitDie);
2578 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2581 NewTU.setType(NewTU.createTypeDIE(CTy));
2584 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2585 TypeUnitsUnderConstruction.clear();
2587 // Types referencing entries in the address table cannot be placed in type
2589 if (AddrPool.hasBeenUsed()) {
2591 // Remove all the types built while building this type.
2592 // This is pessimistic as some of these types might not be dependent on
2593 // the type that used an address.
2594 for (const auto &TU : TypeUnitsToAdd)
2595 DwarfTypeUnits.erase(TU.second);
2597 // Construct this type in the CU directly.
2598 // This is inefficient because all the dependent types will be rebuilt
2599 // from scratch, including building them in type units, discovering that
2600 // they depend on addresses, throwing them out and rebuilding them.
2601 CU.constructTypeDIE(RefDie, CTy);
2605 // If the type wasn't dependent on fission addresses, finish adding the type
2606 // and all its dependent types.
2607 for (auto &TU : TypeUnitsToAdd)
2608 InfoHolder.addUnit(std::move(TU.first));
2610 CU.addDIETypeSignature(RefDie, NewTU);
2613 // Accelerator table mutators - add each name along with its companion
2614 // DIE to the proper table while ensuring that the name that we're going
2615 // to reference is in the string table. We do this since the names we
2616 // add may not only be identical to the names in the DIE.
2617 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2618 if (!useDwarfAccelTables())
2620 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2624 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2625 if (!useDwarfAccelTables())
2627 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2631 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2632 if (!useDwarfAccelTables())
2634 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2638 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2639 if (!useDwarfAccelTables())
2641 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),