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 "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
53 #define DEBUG_TYPE "dwarfdebug"
56 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
57 cl::desc("Disable debug info printing"));
59 static cl::opt<bool> UnknownLocations(
60 "use-unknown-locations", cl::Hidden,
61 cl::desc("Make an absence of debug location information explicit."),
65 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
66 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
71 cl::desc("Generate dwarf aranges"),
75 enum DefaultOnOff { Default, Enable, Disable };
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 //===----------------------------------------------------------------------===//
113 /// resolve - Look in the DwarfDebug map for the MDNode that
114 /// corresponds to the reference.
115 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
116 return DD->resolve(Ref);
119 bool DbgVariable::isBlockByrefVariable() const {
120 assert(Var.isVariable() && "Invalid complex DbgVariable!");
121 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
125 DIType DbgVariable::getType() const {
126 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
127 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
128 // addresses instead.
129 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
130 /* Byref variables, in Blocks, are declared by the programmer as
131 "SomeType VarName;", but the compiler creates a
132 __Block_byref_x_VarName struct, and gives the variable VarName
133 either the struct, or a pointer to the struct, as its type. This
134 is necessary for various behind-the-scenes things the compiler
135 needs to do with by-reference variables in blocks.
137 However, as far as the original *programmer* is concerned, the
138 variable should still have type 'SomeType', as originally declared.
140 The following function dives into the __Block_byref_x_VarName
141 struct to find the original type of the variable. This will be
142 passed back to the code generating the type for the Debug
143 Information Entry for the variable 'VarName'. 'VarName' will then
144 have the original type 'SomeType' in its debug information.
146 The original type 'SomeType' will be the type of the field named
147 'VarName' inside the __Block_byref_x_VarName struct.
149 NOTE: In order for this to not completely fail on the debugger
150 side, the Debug Information Entry for the variable VarName needs to
151 have a DW_AT_location that tells the debugger how to unwind through
152 the pointers and __Block_byref_x_VarName struct to find the actual
153 value of the variable. The function addBlockByrefType does this. */
155 uint16_t tag = Ty.getTag();
157 if (tag == dwarf::DW_TAG_pointer_type)
158 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
160 DIArray Elements = DICompositeType(subType).getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDerivedType DT(Elements.getElement(i));
163 if (getName() == DT.getName())
164 return (resolve(DT.getTypeDerivedFrom()));
170 } // end llvm namespace
172 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
173 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
174 InfoHolder(A, "info_string", DIEValueAllocator),
175 UsedNonDefaultText(false),
176 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
178 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
179 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
180 DwarfAddrSectionSym = 0;
181 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
182 FunctionBeginSym = FunctionEndSym = 0;
186 // Turn on accelerator tables for Darwin by default, pubnames by
187 // default for non-Darwin, and handle split dwarf.
188 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
190 if (DwarfAccelTables == Default)
191 HasDwarfAccelTables = IsDarwin;
193 HasDwarfAccelTables = DwarfAccelTables == Enable;
195 if (SplitDwarf == Default)
196 HasSplitDwarf = false;
198 HasSplitDwarf = SplitDwarf == Enable;
200 if (DwarfPubSections == Default)
201 HasDwarfPubSections = !IsDarwin;
203 HasDwarfPubSections = DwarfPubSections == Enable;
205 DwarfVersion = DwarfVersionNumber
207 : MMI->getModule()->getDwarfVersion();
210 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
223 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
224 Asm->OutStreamer.EmitLabel(TmpSym);
228 DwarfFile::~DwarfFile() {
229 for (DwarfUnit *DU : CUs)
233 MCSymbol *DwarfFile::getStringPoolSym() {
234 return Asm->GetTempSymbol(StringPref);
237 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
238 std::pair<MCSymbol *, unsigned> &Entry =
239 StringPool.GetOrCreateValue(Str).getValue();
243 Entry.second = NextStringPoolNumber++;
244 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
247 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
259 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
260 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
262 ++NextAddrPoolNumber;
263 return P.first->second.Number;
266 // Define a unique number for the abbreviation.
268 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
269 // Check the set for priors.
270 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
272 // If it's newly added.
273 if (InSet == &Abbrev) {
274 // Add to abbreviation list.
275 Abbreviations.push_back(&Abbrev);
277 // Assign the vector position + 1 as its number.
278 Abbrev.setNumber(Abbreviations.size());
280 // Assign existing abbreviation number.
281 Abbrev.setNumber(InSet->getNumber());
285 static bool isObjCClass(StringRef Name) {
286 return Name.startswith("+") || Name.startswith("-");
289 static bool hasObjCCategory(StringRef Name) {
290 if (!isObjCClass(Name))
293 return Name.find(") ") != StringRef::npos;
296 static void getObjCClassCategory(StringRef In, StringRef &Class,
297 StringRef &Category) {
298 if (!hasObjCCategory(In)) {
299 Class = In.slice(In.find('[') + 1, In.find(' '));
304 Class = In.slice(In.find('[') + 1, In.find('('));
305 Category = In.slice(In.find('[') + 1, In.find(' '));
309 static StringRef getObjCMethodName(StringRef In) {
310 return In.slice(In.find(' ') + 1, In.find(']'));
313 // Helper for sorting sections into a stable output order.
314 static bool SectionSort(const MCSection *A, const MCSection *B) {
315 std::string LA = (A ? A->getLabelBeginName() : "");
316 std::string LB = (B ? B->getLabelBeginName() : "");
320 // Add the various names to the Dwarf accelerator table names.
321 // TODO: Determine whether or not we should add names for programs
322 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
323 // is only slightly different than the lookup of non-standard ObjC names.
324 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
325 if (!SP.isDefinition())
327 TheU->addAccelName(SP.getName(), Die);
329 // If the linkage name is different than the name, go ahead and output
330 // that as well into the name table.
331 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
332 TheU->addAccelName(SP.getLinkageName(), Die);
334 // If this is an Objective-C selector name add it to the ObjC accelerator
336 if (isObjCClass(SP.getName())) {
337 StringRef Class, Category;
338 getObjCClassCategory(SP.getName(), Class, Category);
339 TheU->addAccelObjC(Class, Die);
341 TheU->addAccelObjC(Category, Die);
342 // Also add the base method name to the name table.
343 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
347 /// isSubprogramContext - Return true if Context is either a subprogram
348 /// or another context nested inside a subprogram.
349 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
352 DIDescriptor D(Context);
353 if (D.isSubprogram())
356 return isSubprogramContext(resolve(DIType(Context).getContext()));
360 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
361 // and DW_AT_high_pc attributes. If there are global variables in this
362 // scope then create and insert DIEs for these variables.
363 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
365 DIE *SPDie = SPCU->getDIE(SP);
367 assert(SPDie && "Unable to find subprogram DIE!");
369 // If we're updating an abstract DIE, then we will be adding the children and
370 // object pointer later on. But what we don't want to do is process the
371 // concrete DIE twice.
372 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
373 // Pick up abstract subprogram DIE.
375 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
376 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
378 DISubprogram SPDecl = SP.getFunctionDeclaration();
379 if (!SPDecl.isSubprogram()) {
380 // There is not any need to generate specification DIE for a function
381 // defined at compile unit level. If a function is defined inside another
382 // function then gdb prefers the definition at top level and but does not
383 // expect specification DIE in parent function. So avoid creating
384 // specification DIE for a function defined inside a function.
385 DIScope SPContext = resolve(SP.getContext());
386 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
387 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
388 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
391 DICompositeType SPTy = SP.getType();
392 DIArray Args = SPTy.getTypeArray();
393 uint16_t SPTag = SPTy.getTag();
394 if (SPTag == dwarf::DW_TAG_subroutine_type)
395 SPCU->constructSubprogramArguments(*SPDie, Args);
396 DIE *SPDeclDie = SPDie;
397 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
398 *SPCU->getUnitDie());
399 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
404 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
406 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
407 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
408 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
410 // Add name to the name table, we do this here because we're guaranteed
411 // to have concrete versions of our DW_TAG_subprogram nodes.
412 addSubprogramNames(SPCU, SP, SPDie);
417 /// Check whether we should create a DIE for the given Scope, return true
418 /// if we don't create a DIE (the corresponding DIE is null).
419 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
420 if (Scope->isAbstractScope())
423 // We don't create a DIE if there is no Range.
424 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
428 if (Ranges.size() > 1)
431 // We don't create a DIE if we have a single Range and the end label
433 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
434 MCSymbol *End = getLabelAfterInsn(RI->second);
438 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
439 dwarf::Attribute A, const MCSymbol *L,
440 const MCSymbol *Sec) {
441 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
442 U->addSectionLabel(D, A, L);
444 U->addSectionDelta(D, A, L, Sec);
447 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
448 const SmallVectorImpl<InsnRange> &Range) {
449 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
450 // emitting it appropriately.
451 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
453 // Under fission, ranges are specified by constant offsets relative to the
454 // CU's DW_AT_GNU_ranges_base.
456 TheCU->addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
457 DwarfDebugRangeSectionSym);
459 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
460 DwarfDebugRangeSectionSym);
462 RangeSpanList List(RangeSym);
463 for (const InsnRange &R : Range) {
464 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
465 List.addRange(std::move(Span));
468 // Add the range list to the set of ranges to be emitted.
469 TheCU->addRangeList(std::move(List));
472 // Construct new DW_TAG_lexical_block for this scope and attach
473 // DW_AT_low_pc/DW_AT_high_pc labels.
474 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
475 LexicalScope *Scope) {
476 if (isLexicalScopeDIENull(Scope))
479 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
480 if (Scope->isAbstractScope())
483 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
485 // If we have multiple ranges, emit them into the range section.
486 if (ScopeRanges.size() > 1) {
487 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
491 // Construct the address range for this DIE.
492 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
493 MCSymbol *Start = getLabelBeforeInsn(RI->first);
494 MCSymbol *End = getLabelAfterInsn(RI->second);
495 assert(End && "End label should not be null!");
497 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
498 assert(End->isDefined() && "Invalid end label for an inlined scope!");
500 attachLowHighPC(TheCU, ScopeDIE, Start, End);
505 // This scope represents inlined body of a function. Construct DIE to
506 // represent this concrete inlined copy of the function.
507 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
508 LexicalScope *Scope) {
509 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
510 assert(!ScopeRanges.empty() &&
511 "LexicalScope does not have instruction markers!");
513 if (!Scope->getScopeNode())
515 DIScope DS(Scope->getScopeNode());
516 DISubprogram InlinedSP = getDISubprogram(DS);
517 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
519 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
523 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
524 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
526 // If we have multiple ranges, emit them into the range section.
527 if (ScopeRanges.size() > 1)
528 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
530 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
531 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
532 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
534 if (StartLabel == 0 || EndLabel == 0)
535 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
537 assert(StartLabel->isDefined() &&
538 "Invalid starting label for an inlined scope!");
539 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
541 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
544 InlinedSubprogramDIEs.insert(OriginDIE);
546 // Add the call site information to the DIE.
547 DILocation DL(Scope->getInlinedAt());
549 ScopeDIE, dwarf::DW_AT_call_file, None,
550 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
551 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
553 // Add name to the name table, we do this here because we're guaranteed
554 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
555 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
560 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
562 SmallVectorImpl<DIE *> &Children) {
563 DIE *ObjectPointer = NULL;
565 // Collect arguments for current function.
566 if (LScopes.isCurrentFunctionScope(Scope)) {
567 for (DbgVariable *ArgDV : CurrentFnArguments)
570 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
571 Children.push_back(Arg);
572 if (ArgDV->isObjectPointer())
576 // If this is a variadic function, add an unspecified parameter.
577 DISubprogram SP(Scope->getScopeNode());
578 DIArray FnArgs = SP.getType().getTypeArray();
579 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
580 .isUnspecifiedParameter()) {
581 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
582 Children.push_back(Ellipsis);
586 // Collect lexical scope children first.
587 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
588 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
589 Scope->isAbstractScope())) {
590 Children.push_back(Variable);
591 if (DV->isObjectPointer())
592 ObjectPointer = Variable;
594 for (LexicalScope *LS : Scope->getChildren())
595 if (DIE *Nested = constructScopeDIE(TheCU, LS))
596 Children.push_back(Nested);
597 return ObjectPointer;
600 // Construct a DIE for this scope.
601 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
602 LexicalScope *Scope) {
603 if (!Scope || !Scope->getScopeNode())
606 DIScope DS(Scope->getScopeNode());
608 SmallVector<DIE *, 8> Children;
609 DIE *ObjectPointer = NULL;
610 bool ChildrenCreated = false;
612 // We try to create the scope DIE first, then the children DIEs. This will
613 // avoid creating un-used children then removing them later when we find out
614 // the scope DIE is null.
615 DIE *ScopeDIE = NULL;
616 if (Scope->getInlinedAt())
617 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
618 else if (DS.isSubprogram()) {
619 ProcessedSPNodes.insert(DS);
620 if (Scope->isAbstractScope()) {
621 ScopeDIE = TheCU->getDIE(DS);
622 // Note down abstract DIE.
624 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
626 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
628 // Early exit when we know the scope DIE is going to be null.
629 if (isLexicalScopeDIENull(Scope))
632 // We create children here when we know the scope DIE is not going to be
633 // null and the children will be added to the scope DIE.
634 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
635 ChildrenCreated = true;
637 // There is no need to emit empty lexical block DIE.
638 std::pair<ImportedEntityMap::const_iterator,
639 ImportedEntityMap::const_iterator> Range =
641 ScopesWithImportedEntities.begin(),
642 ScopesWithImportedEntities.end(),
643 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
645 if (Children.empty() && Range.first == Range.second)
647 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
648 assert(ScopeDIE && "Scope DIE should not be null.");
649 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
651 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
655 assert(Children.empty() &&
656 "We create children only when the scope DIE is not null.");
659 if (!ChildrenCreated)
660 // We create children when the scope DIE is not null.
661 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
664 for (DIE *I : Children)
665 ScopeDIE->addChild(I);
667 if (DS.isSubprogram() && ObjectPointer != NULL)
668 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
673 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
674 if (!GenerateGnuPubSections)
677 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
680 // Create new DwarfCompileUnit for the given metadata node with tag
681 // DW_TAG_compile_unit.
682 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
683 StringRef FN = DIUnit.getFilename();
684 CompilationDir = DIUnit.getDirectory();
686 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
687 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
688 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
689 InfoHolder.addUnit(NewCU);
691 // LTO with assembly output shares a single line table amongst multiple CUs.
692 // To avoid the compilation directory being ambiguous, let the line table
693 // explicitly describe the directory of all files, never relying on the
694 // compilation directory.
695 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
696 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
697 NewCU->getUniqueID(), CompilationDir);
699 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
700 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
701 DIUnit.getLanguage());
702 NewCU->addString(Die, dwarf::DW_AT_name, FN);
704 if (!useSplitDwarf()) {
705 NewCU->initStmtList(DwarfLineSectionSym);
707 // If we're using split dwarf the compilation dir is going to be in the
708 // skeleton CU and so we don't need to duplicate it here.
709 if (!CompilationDir.empty())
710 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
712 addGnuPubAttributes(NewCU, Die);
715 if (DIUnit.isOptimized())
716 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
718 StringRef Flags = DIUnit.getFlags();
720 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
722 if (unsigned RVer = DIUnit.getRunTimeVersion())
723 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
724 dwarf::DW_FORM_data1, RVer);
729 if (useSplitDwarf()) {
730 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
731 DwarfInfoDWOSectionSym);
732 NewCU->setSkeleton(constructSkeletonCU(NewCU));
734 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
735 DwarfInfoSectionSym);
737 CUMap.insert(std::make_pair(DIUnit, NewCU));
738 CUDieMap.insert(std::make_pair(Die, NewCU));
742 // Construct subprogram DIE.
743 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
745 // FIXME: We should only call this routine once, however, during LTO if a
746 // program is defined in multiple CUs we could end up calling it out of
747 // beginModule as we walk the CUs.
749 DwarfCompileUnit *&CURef = SPMap[N];
755 if (!SP.isDefinition())
756 // This is a method declaration which will be handled while constructing
760 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
762 // Expose as a global name.
763 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
766 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
768 DIImportedEntity Module(N);
769 assert(Module.Verify());
770 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
771 constructImportedEntityDIE(TheCU, Module, D);
774 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
775 const MDNode *N, DIE *Context) {
776 DIImportedEntity Module(N);
777 assert(Module.Verify());
778 return constructImportedEntityDIE(TheCU, Module, Context);
781 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
782 const DIImportedEntity &Module,
784 assert(Module.Verify() &&
785 "Use one of the MDNode * overloads to handle invalid metadata");
786 assert(Context && "Should always have a context for an imported_module");
787 DIE *IMDie = TheCU->createAndAddDIE(Module.getTag(), *Context, Module);
789 DIDescriptor Entity = resolve(Module.getEntity());
790 if (Entity.isNameSpace())
791 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
792 else if (Entity.isSubprogram())
793 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
794 else if (Entity.isType())
795 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
797 EntityDie = TheCU->getDIE(Entity);
798 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
799 Module.getContext().getFilename(),
800 Module.getContext().getDirectory());
801 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
802 StringRef Name = Module.getName();
804 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
807 // Emit all Dwarf sections that should come prior to the content. Create
808 // global DIEs and emit initial debug info sections. This is invoked by
809 // the target AsmPrinter.
810 void DwarfDebug::beginModule() {
811 if (DisableDebugInfoPrinting)
814 const Module *M = MMI->getModule();
816 // If module has named metadata anchors then use them, otherwise scan the
817 // module using debug info finder to collect debug info.
818 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
821 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
823 // Emit initial sections so we can reference labels later.
826 SingleCU = CU_Nodes->getNumOperands() == 1;
828 for (MDNode *N : CU_Nodes->operands()) {
829 DICompileUnit CUNode(N);
830 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
831 DIArray ImportedEntities = CUNode.getImportedEntities();
832 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
833 ScopesWithImportedEntities.push_back(std::make_pair(
834 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
835 ImportedEntities.getElement(i)));
836 std::sort(ScopesWithImportedEntities.begin(),
837 ScopesWithImportedEntities.end(), less_first());
838 DIArray GVs = CUNode.getGlobalVariables();
839 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
840 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
841 DIArray SPs = CUNode.getSubprograms();
842 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
843 constructSubprogramDIE(CU, SPs.getElement(i));
844 DIArray EnumTypes = CUNode.getEnumTypes();
845 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
846 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
847 DIArray RetainedTypes = CUNode.getRetainedTypes();
848 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
849 DIType Ty(RetainedTypes.getElement(i));
850 // The retained types array by design contains pointers to
851 // MDNodes rather than DIRefs. Unique them here.
852 DIType UniqueTy(resolve(Ty.getRef()));
853 CU->getOrCreateTypeDIE(UniqueTy);
855 // Emit imported_modules last so that the relevant context is already
857 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
858 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
861 // Tell MMI that we have debug info.
862 MMI->setDebugInfoAvailability(true);
864 // Prime section data.
865 SectionMap[Asm->getObjFileLowering().getTextSection()];
868 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
869 void DwarfDebug::computeInlinedDIEs() {
870 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
871 for (DIE *ISP : InlinedSubprogramDIEs)
872 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
874 for (const auto &AI : AbstractSPDies) {
875 DIE *ISP = AI.second;
876 if (InlinedSubprogramDIEs.count(ISP))
878 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
882 // Collect info for variables that were optimized out.
883 void DwarfDebug::collectDeadVariables() {
884 const Module *M = MMI->getModule();
886 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
887 for (MDNode *N : CU_Nodes->operands()) {
888 DICompileUnit TheCU(N);
889 DIArray Subprograms = TheCU.getSubprograms();
890 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
891 DISubprogram SP(Subprograms.getElement(i));
892 if (ProcessedSPNodes.count(SP) != 0)
894 if (!SP.isSubprogram())
896 if (!SP.isDefinition())
898 DIArray Variables = SP.getVariables();
899 if (Variables.getNumElements() == 0)
902 // Construct subprogram DIE and add variables DIEs.
903 DwarfCompileUnit *SPCU =
904 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
905 assert(SPCU && "Unable to find Compile Unit!");
906 // FIXME: See the comment in constructSubprogramDIE about duplicate
908 constructSubprogramDIE(SPCU, SP);
909 DIE *SPDIE = SPCU->getDIE(SP);
910 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
911 DIVariable DV(Variables.getElement(vi));
912 if (!DV.isVariable())
914 DbgVariable NewVar(DV, NULL, this);
915 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
916 SPDIE->addChild(VariableDIE);
923 void DwarfDebug::finalizeModuleInfo() {
924 // Collect info for variables that were optimized out.
925 collectDeadVariables();
927 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
928 computeInlinedDIEs();
930 // Handle anything that needs to be done on a per-unit basis after
931 // all other generation.
932 for (DwarfUnit *TheU : getUnits()) {
933 // Emit DW_AT_containing_type attribute to connect types with their
934 // vtable holding type.
935 TheU->constructContainingTypeDIEs();
937 // Add CU specific attributes if we need to add any.
938 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
939 // If we're splitting the dwarf out now that we've got the entire
940 // CU then add the dwo id to it.
941 DwarfCompileUnit *SkCU =
942 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
943 if (useSplitDwarf()) {
944 // Emit a unique identifier for this CU.
945 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
946 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
947 dwarf::DW_FORM_data8, ID);
948 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
949 dwarf::DW_FORM_data8, ID);
951 // We don't keep track of which addresses are used in which CU so this
952 // is a bit pessimistic under LTO.
953 if (!InfoHolder.getAddrPool()->empty())
954 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
955 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
956 DwarfAddrSectionSym);
957 if (!TheU->getRangeLists().empty())
958 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
959 dwarf::DW_AT_GNU_ranges_base,
960 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
963 // If we have code split among multiple sections or non-contiguous
964 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
965 // remain in the .o file, otherwise add a DW_AT_low_pc.
966 // FIXME: We should use ranges allow reordering of code ala
967 // .subsections_via_symbols in mach-o. This would mean turning on
968 // ranges for all subprogram DIEs for mach-o.
969 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
970 unsigned NumRanges = TheU->getRanges().size();
973 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
974 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
975 DwarfDebugRangeSectionSym);
977 // A DW_AT_low_pc attribute may also be specified in combination with
978 // DW_AT_ranges to specify the default base address for use in
979 // location lists (see Section 2.6.2) and range lists (see Section
981 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
984 RangeSpan &Range = TheU->getRanges().back();
985 U->addLocalLabelAddress(U->getUnitDie(), dwarf::DW_AT_low_pc,
987 U->addLabelDelta(U->getUnitDie(), dwarf::DW_AT_high_pc,
988 Range.getEnd(), Range.getStart());
994 // Compute DIE offsets and sizes.
995 InfoHolder.computeSizeAndOffsets();
997 SkeletonHolder.computeSizeAndOffsets();
1000 void DwarfDebug::endSections() {
1001 // Filter labels by section.
1002 for (const SymbolCU &SCU : ArangeLabels) {
1003 if (SCU.Sym->isInSection()) {
1004 // Make a note of this symbol and it's section.
1005 const MCSection *Section = &SCU.Sym->getSection();
1006 if (!Section->getKind().isMetadata())
1007 SectionMap[Section].push_back(SCU);
1009 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1010 // appear in the output. This sucks as we rely on sections to build
1011 // arange spans. We can do it without, but it's icky.
1012 SectionMap[NULL].push_back(SCU);
1016 // Build a list of sections used.
1017 std::vector<const MCSection *> Sections;
1018 for (const auto &it : SectionMap) {
1019 const MCSection *Section = it.first;
1020 Sections.push_back(Section);
1023 // Sort the sections into order.
1024 // This is only done to ensure consistent output order across different runs.
1025 std::sort(Sections.begin(), Sections.end(), SectionSort);
1027 // Add terminating symbols for each section.
1028 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1029 const MCSection *Section = Sections[ID];
1030 MCSymbol *Sym = NULL;
1033 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1034 // if we know the section name up-front. For user-created sections, the
1035 // resulting label may not be valid to use as a label. (section names can
1036 // use a greater set of characters on some systems)
1037 Sym = Asm->GetTempSymbol("debug_end", ID);
1038 Asm->OutStreamer.SwitchSection(Section);
1039 Asm->OutStreamer.EmitLabel(Sym);
1042 // Insert a final terminator.
1043 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1047 // Emit all Dwarf sections that should come after the content.
1048 void DwarfDebug::endModule() {
1055 // End any existing sections.
1056 // TODO: Does this need to happen?
1059 // Finalize the debug info for the module.
1060 finalizeModuleInfo();
1064 // Emit all the DIEs into a debug info section.
1067 // Corresponding abbreviations into a abbrev section.
1068 emitAbbreviations();
1070 // Emit info into a debug aranges section.
1071 if (GenerateARangeSection)
1074 // Emit info into a debug ranges section.
1077 if (useSplitDwarf()) {
1080 emitDebugAbbrevDWO();
1082 // Emit DWO addresses.
1083 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1086 // Emit info into a debug loc section.
1089 // Emit info into the dwarf accelerator table sections.
1090 if (useDwarfAccelTables()) {
1093 emitAccelNamespaces();
1097 // Emit the pubnames and pubtypes sections if requested.
1098 if (HasDwarfPubSections) {
1099 emitDebugPubNames(GenerateGnuPubSections);
1100 emitDebugPubTypes(GenerateGnuPubSections);
1106 // Reset these for the next Module if we have one.
1110 // Find abstract variable, if any, associated with Var.
1111 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1112 DebugLoc ScopeLoc) {
1113 LLVMContext &Ctx = DV->getContext();
1114 // More then one inlined variable corresponds to one abstract variable.
1115 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1116 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1118 return AbsDbgVariable;
1120 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1124 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1125 addScopeVariable(Scope, AbsDbgVariable);
1126 AbstractVariables[Var] = AbsDbgVariable;
1127 return AbsDbgVariable;
1130 // If Var is a current function argument then add it to CurrentFnArguments list.
1131 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1132 if (!LScopes.isCurrentFunctionScope(Scope))
1134 DIVariable DV = Var->getVariable();
1135 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1137 unsigned ArgNo = DV.getArgNumber();
1141 size_t Size = CurrentFnArguments.size();
1143 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1144 // llvm::Function argument size is not good indicator of how many
1145 // arguments does the function have at source level.
1147 CurrentFnArguments.resize(ArgNo * 2);
1148 CurrentFnArguments[ArgNo - 1] = Var;
1152 // Collect variable information from side table maintained by MMI.
1153 void DwarfDebug::collectVariableInfoFromMMITable(
1154 SmallPtrSet<const MDNode *, 16> &Processed) {
1155 for (const auto &VI : MMI->getVariableDbgInfo()) {
1158 Processed.insert(VI.Var);
1159 DIVariable DV(VI.Var);
1160 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1162 // If variable scope is not found then skip this variable.
1166 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1167 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1168 RegVar->setFrameIndex(VI.Slot);
1169 if (!addCurrentFnArgument(RegVar, Scope))
1170 addScopeVariable(Scope, RegVar);
1172 AbsDbgVariable->setFrameIndex(VI.Slot);
1176 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1178 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1179 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1180 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1181 MI->getOperand(0).getReg() &&
1182 (MI->getOperand(1).isImm() ||
1183 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1186 // Get .debug_loc entry for the instruction range starting at MI.
1187 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1188 const MCSymbol *FLabel,
1189 const MCSymbol *SLabel,
1190 const MachineInstr *MI,
1191 DwarfCompileUnit *Unit) {
1192 const MDNode *Var = MI->getDebugVariable();
1194 assert(MI->getNumOperands() == 3);
1195 if (MI->getOperand(0).isReg()) {
1196 MachineLocation MLoc;
1197 // If the second operand is an immediate, this is a
1198 // register-indirect address.
1199 if (!MI->getOperand(1).isImm())
1200 MLoc.set(MI->getOperand(0).getReg());
1202 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1203 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1205 if (MI->getOperand(0).isImm())
1206 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1207 if (MI->getOperand(0).isFPImm())
1208 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1210 if (MI->getOperand(0).isCImm())
1211 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1214 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1217 // Find variables for each lexical scope.
1219 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1221 // Grab the variable info that was squirreled away in the MMI side-table.
1222 collectVariableInfoFromMMITable(Processed);
1224 for (const MDNode *Var : UserVariables) {
1225 if (Processed.count(Var))
1228 // History contains relevant DBG_VALUE instructions for Var and instructions
1230 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1231 if (History.empty())
1233 const MachineInstr *MInsn = History.front();
1236 LexicalScope *Scope = NULL;
1237 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1238 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1239 Scope = LScopes.getCurrentFunctionScope();
1240 else if (MDNode *IA = DV.getInlinedAt())
1241 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1243 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1244 // If variable scope is not found then skip this variable.
1248 Processed.insert(DV);
1249 assert(MInsn->isDebugValue() && "History must begin with debug value");
1250 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1251 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1252 if (!addCurrentFnArgument(RegVar, Scope))
1253 addScopeVariable(Scope, RegVar);
1255 AbsVar->setMInsn(MInsn);
1257 // Simplify ranges that are fully coalesced.
1258 if (History.size() <= 1 ||
1259 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1260 RegVar->setMInsn(MInsn);
1264 // Handle multiple DBG_VALUE instructions describing one variable.
1265 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1267 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1268 DebugLocList &LocList = DotDebugLocEntries.back();
1270 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1271 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1272 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1273 HI = History.begin(),
1276 const MachineInstr *Begin = *HI;
1277 assert(Begin->isDebugValue() && "Invalid History entry");
1279 // Check if DBG_VALUE is truncating a range.
1280 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1281 !Begin->getOperand(0).getReg())
1284 // Compute the range for a register location.
1285 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1286 const MCSymbol *SLabel = 0;
1289 // If Begin is the last instruction in History then its value is valid
1290 // until the end of the function.
1291 SLabel = FunctionEndSym;
1293 const MachineInstr *End = HI[1];
1294 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1295 << "\t" << *Begin << "\t" << *End << "\n");
1296 if (End->isDebugValue())
1297 SLabel = getLabelBeforeInsn(End);
1299 // End is a normal instruction clobbering the range.
1300 SLabel = getLabelAfterInsn(End);
1301 assert(SLabel && "Forgot label after clobber instruction");
1306 // The value is valid until the next DBG_VALUE or clobber.
1307 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1308 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1309 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1310 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1311 DebugLoc.push_back(std::move(Loc));
1315 // Collect info for variables that were optimized out.
1316 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1317 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1318 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1319 DIVariable DV(Variables.getElement(i));
1320 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1322 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1323 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1327 // Return Label preceding the instruction.
1328 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1329 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1330 assert(Label && "Didn't insert label before instruction");
1334 // Return Label immediately following the instruction.
1335 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1336 return LabelsAfterInsn.lookup(MI);
1339 // Process beginning of an instruction.
1340 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1343 // Check if source location changes, but ignore DBG_VALUE locations.
1344 if (!MI->isDebugValue()) {
1345 DebugLoc DL = MI->getDebugLoc();
1346 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1349 if (DL == PrologEndLoc) {
1350 Flags |= DWARF2_FLAG_PROLOGUE_END;
1351 PrologEndLoc = DebugLoc();
1353 if (PrologEndLoc.isUnknown())
1354 Flags |= DWARF2_FLAG_IS_STMT;
1356 if (!DL.isUnknown()) {
1357 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1358 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1360 recordSourceLine(0, 0, 0, 0);
1364 // Insert labels where requested.
1365 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1366 LabelsBeforeInsn.find(MI);
1369 if (I == LabelsBeforeInsn.end())
1372 // Label already assigned.
1377 PrevLabel = MMI->getContext().CreateTempSymbol();
1378 Asm->OutStreamer.EmitLabel(PrevLabel);
1380 I->second = PrevLabel;
1383 // Process end of an instruction.
1384 void DwarfDebug::endInstruction() {
1386 // Don't create a new label after DBG_VALUE instructions.
1387 // They don't generate code.
1388 if (!CurMI->isDebugValue())
1391 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1392 LabelsAfterInsn.find(CurMI);
1396 if (I == LabelsAfterInsn.end())
1399 // Label already assigned.
1403 // We need a label after this instruction.
1405 PrevLabel = MMI->getContext().CreateTempSymbol();
1406 Asm->OutStreamer.EmitLabel(PrevLabel);
1408 I->second = PrevLabel;
1411 // Each LexicalScope has first instruction and last instruction to mark
1412 // beginning and end of a scope respectively. Create an inverse map that list
1413 // scopes starts (and ends) with an instruction. One instruction may start (or
1414 // end) multiple scopes. Ignore scopes that are not reachable.
1415 void DwarfDebug::identifyScopeMarkers() {
1416 SmallVector<LexicalScope *, 4> WorkList;
1417 WorkList.push_back(LScopes.getCurrentFunctionScope());
1418 while (!WorkList.empty()) {
1419 LexicalScope *S = WorkList.pop_back_val();
1421 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1422 if (!Children.empty())
1423 WorkList.append(Children.begin(), Children.end());
1425 if (S->isAbstractScope())
1428 for (const InsnRange &R : S->getRanges()) {
1429 assert(R.first && "InsnRange does not have first instruction!");
1430 assert(R.second && "InsnRange does not have second instruction!");
1431 requestLabelBeforeInsn(R.first);
1432 requestLabelAfterInsn(R.second);
1437 // Gather pre-function debug information. Assumes being called immediately
1438 // after the function entry point has been emitted.
1439 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1442 // If there's no debug info for the function we're not going to do anything.
1443 if (!MMI->hasDebugInfo())
1446 // Grab the lexical scopes for the function, if we don't have any of those
1447 // then we're not going to be able to do anything.
1448 LScopes.initialize(*MF);
1449 if (LScopes.empty())
1452 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1454 // Make sure that each lexical scope will have a begin/end label.
1455 identifyScopeMarkers();
1457 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1458 // belongs to so that we add to the correct per-cu line table in the
1460 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1461 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1462 assert(TheCU && "Unable to find compile unit!");
1463 if (Asm->OutStreamer.hasRawTextSupport())
1464 // Use a single line table if we are generating assembly.
1465 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1467 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1469 // Emit a label for the function so that we have a beginning address.
1470 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1471 // Assumes in correct section after the entry point.
1472 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1474 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1475 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1476 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1478 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1480 bool AtBlockEntry = true;
1481 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1483 const MachineInstr *MI = II;
1485 if (MI->isDebugValue()) {
1486 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1488 // Keep track of user variables.
1489 const MDNode *Var = MI->getDebugVariable();
1491 // Variable is in a register, we need to check for clobbers.
1492 if (isDbgValueInDefinedReg(MI))
1493 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1495 // Check the history of this variable.
1496 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1497 if (History.empty()) {
1498 UserVariables.push_back(Var);
1499 // The first mention of a function argument gets the FunctionBeginSym
1500 // label, so arguments are visible when breaking at function entry.
1502 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1503 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1504 LabelsBeforeInsn[MI] = FunctionBeginSym;
1506 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1507 const MachineInstr *Prev = History.back();
1508 if (Prev->isDebugValue()) {
1509 // Coalesce identical entries at the end of History.
1510 if (History.size() >= 2 &&
1511 Prev->isIdenticalTo(History[History.size() - 2])) {
1512 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1513 << "\t" << *Prev << "\t"
1514 << *History[History.size() - 2] << "\n");
1518 // Terminate old register assignments that don't reach MI;
1519 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1520 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1521 isDbgValueInDefinedReg(Prev)) {
1522 // Previous register assignment needs to terminate at the end of
1524 MachineBasicBlock::const_iterator LastMI =
1525 PrevMBB->getLastNonDebugInstr();
1526 if (LastMI == PrevMBB->end()) {
1527 // Drop DBG_VALUE for empty range.
1528 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1529 << "\t" << *Prev << "\n");
1531 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1532 // Terminate after LastMI.
1533 History.push_back(LastMI);
1537 History.push_back(MI);
1539 // Not a DBG_VALUE instruction.
1540 if (!MI->isPosition())
1541 AtBlockEntry = false;
1543 // First known non-DBG_VALUE and non-frame setup location marks
1544 // the beginning of the function body.
1545 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1546 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1547 PrologEndLoc = MI->getDebugLoc();
1549 // Check if the instruction clobbers any registers with debug vars.
1550 for (const MachineOperand &MO : MI->operands()) {
1551 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1553 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1556 const MDNode *Var = LiveUserVar[Reg];
1559 // Reg is now clobbered.
1560 LiveUserVar[Reg] = 0;
1562 // Was MD last defined by a DBG_VALUE referring to Reg?
1563 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1564 if (HistI == DbgValues.end())
1566 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1567 if (History.empty())
1569 const MachineInstr *Prev = History.back();
1570 // Sanity-check: Register assignments are terminated at the end of
1572 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1574 // Is the variable still in Reg?
1575 if (!isDbgValueInDefinedReg(Prev) ||
1576 Prev->getOperand(0).getReg() != Reg)
1578 // Var is clobbered. Make sure the next instruction gets a label.
1579 History.push_back(MI);
1586 for (auto &I : DbgValues) {
1587 SmallVectorImpl<const MachineInstr *> &History = I.second;
1588 if (History.empty())
1591 // Make sure the final register assignments are terminated.
1592 const MachineInstr *Prev = History.back();
1593 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1594 const MachineBasicBlock *PrevMBB = Prev->getParent();
1595 MachineBasicBlock::const_iterator LastMI =
1596 PrevMBB->getLastNonDebugInstr();
1597 if (LastMI == PrevMBB->end())
1598 // Drop DBG_VALUE for empty range.
1600 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1601 // Terminate after LastMI.
1602 History.push_back(LastMI);
1605 // Request labels for the full history.
1606 for (const MachineInstr *MI : History) {
1607 if (MI->isDebugValue())
1608 requestLabelBeforeInsn(MI);
1610 requestLabelAfterInsn(MI);
1614 PrevInstLoc = DebugLoc();
1615 PrevLabel = FunctionBeginSym;
1617 // Record beginning of function.
1618 if (!PrologEndLoc.isUnknown()) {
1619 DebugLoc FnStartDL =
1620 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1622 FnStartDL.getLine(), FnStartDL.getCol(),
1623 FnStartDL.getScope(MF->getFunction()->getContext()),
1624 // We'd like to list the prologue as "not statements" but GDB behaves
1625 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1626 DWARF2_FLAG_IS_STMT);
1630 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1631 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1632 DIVariable DV = Var->getVariable();
1633 // Variables with positive arg numbers are parameters.
1634 if (unsigned ArgNum = DV.getArgNumber()) {
1635 // Keep all parameters in order at the start of the variable list to ensure
1636 // function types are correct (no out-of-order parameters)
1638 // This could be improved by only doing it for optimized builds (unoptimized
1639 // builds have the right order to begin with), searching from the back (this
1640 // would catch the unoptimized case quickly), or doing a binary search
1641 // rather than linear search.
1642 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1643 while (I != Vars.end()) {
1644 unsigned CurNum = (*I)->getVariable().getArgNumber();
1645 // A local (non-parameter) variable has been found, insert immediately
1649 // A later indexed parameter has been found, insert immediately before it.
1650 if (CurNum > ArgNum)
1654 Vars.insert(I, Var);
1658 Vars.push_back(Var);
1661 // Gather and emit post-function debug information.
1662 void DwarfDebug::endFunction(const MachineFunction *MF) {
1663 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1664 // though the beginFunction may not be called at all.
1665 // We should handle both cases.
1669 assert(CurFn == MF);
1672 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1673 // If we don't have a lexical scope for this function then there will
1674 // be a hole in the range information. Keep note of this by setting the
1675 // previously used section to nullptr.
1676 PrevSection = nullptr;
1682 // Define end label for subprogram.
1683 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1684 // Assumes in correct section after the entry point.
1685 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1687 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1688 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1690 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1691 collectVariableInfo(ProcessedVars);
1693 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1694 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1695 assert(TheCU && "Unable to find compile unit!");
1697 // Construct abstract scopes.
1698 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1699 DISubprogram SP(AScope->getScopeNode());
1700 if (SP.isSubprogram()) {
1701 // Collect info for variables that were optimized out.
1702 DIArray Variables = SP.getVariables();
1703 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1704 DIVariable DV(Variables.getElement(i));
1705 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1707 // Check that DbgVariable for DV wasn't created earlier, when
1708 // findAbstractVariable() was called for inlined instance of DV.
1709 LLVMContext &Ctx = DV->getContext();
1710 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1711 if (AbstractVariables.lookup(CleanDV))
1713 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1714 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1717 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1718 constructScopeDIE(TheCU, AScope);
1721 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1722 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1723 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1725 // Add the range of this function to the list of ranges for the CU.
1726 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1727 TheCU->addRange(std::move(Span));
1728 PrevSection = Asm->getCurrentSection();
1732 for (auto &I : ScopeVariables)
1733 DeleteContainerPointers(I.second);
1734 ScopeVariables.clear();
1735 DeleteContainerPointers(CurrentFnArguments);
1736 UserVariables.clear();
1738 AbstractVariables.clear();
1739 LabelsBeforeInsn.clear();
1740 LabelsAfterInsn.clear();
1745 // Register a source line with debug info. Returns the unique label that was
1746 // emitted and which provides correspondence to the source line list.
1747 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1752 unsigned Discriminator = 0;
1754 DIDescriptor Scope(S);
1756 if (Scope.isCompileUnit()) {
1757 DICompileUnit CU(S);
1758 Fn = CU.getFilename();
1759 Dir = CU.getDirectory();
1760 } else if (Scope.isFile()) {
1762 Fn = F.getFilename();
1763 Dir = F.getDirectory();
1764 } else if (Scope.isSubprogram()) {
1766 Fn = SP.getFilename();
1767 Dir = SP.getDirectory();
1768 } else if (Scope.isLexicalBlockFile()) {
1769 DILexicalBlockFile DBF(S);
1770 Fn = DBF.getFilename();
1771 Dir = DBF.getDirectory();
1772 } else if (Scope.isLexicalBlock()) {
1773 DILexicalBlock DB(S);
1774 Fn = DB.getFilename();
1775 Dir = DB.getDirectory();
1776 Discriminator = DB.getDiscriminator();
1778 llvm_unreachable("Unexpected scope info");
1780 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1781 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1782 ->getOrCreateSourceID(Fn, Dir);
1784 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1788 //===----------------------------------------------------------------------===//
1790 //===----------------------------------------------------------------------===//
1792 // Compute the size and offset of a DIE. The offset is relative to start of the
1793 // CU. It returns the offset after laying out the DIE.
1794 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) {
1795 // Record the abbreviation.
1796 assignAbbrevNumber(Die.getAbbrev());
1798 // Get the abbreviation for this DIE.
1799 const DIEAbbrev &Abbrev = Die.getAbbrev();
1802 Die.setOffset(Offset);
1804 // Start the size with the size of abbreviation code.
1805 Offset += getULEB128Size(Die.getAbbrevNumber());
1807 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1808 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1810 // Size the DIE attribute values.
1811 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1812 // Size attribute value.
1813 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1815 // Get the children.
1816 const auto &Children = Die.getChildren();
1818 // Size the DIE children if any.
1819 if (!Children.empty()) {
1820 assert(Abbrev.hasChildren() && "Children flag not set");
1822 for (auto &Child : Children)
1823 Offset = computeSizeAndOffset(*Child, Offset);
1825 // End of children marker.
1826 Offset += sizeof(int8_t);
1829 Die.setSize(Offset - Die.getOffset());
1833 // Compute the size and offset for each DIE.
1834 void DwarfFile::computeSizeAndOffsets() {
1835 // Offset from the first CU in the debug info section is 0 initially.
1836 unsigned SecOffset = 0;
1838 // Iterate over each compile unit and set the size and offsets for each
1839 // DIE within each compile unit. All offsets are CU relative.
1840 for (DwarfUnit *TheU : CUs) {
1841 TheU->setDebugInfoOffset(SecOffset);
1843 // CU-relative offset is reset to 0 here.
1844 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1845 TheU->getHeaderSize(); // Unit-specific headers
1847 // EndOffset here is CU-relative, after laying out
1848 // all of the CU DIE.
1849 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset);
1850 SecOffset += EndOffset;
1854 // Emit initial Dwarf sections with a label at the start of each one.
1855 void DwarfDebug::emitSectionLabels() {
1856 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1858 // Dwarf sections base addresses.
1859 DwarfInfoSectionSym =
1860 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1861 if (useSplitDwarf())
1862 DwarfInfoDWOSectionSym =
1863 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1864 DwarfAbbrevSectionSym =
1865 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1866 if (useSplitDwarf())
1867 DwarfAbbrevDWOSectionSym = emitSectionSym(
1868 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1869 if (GenerateARangeSection)
1870 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1872 DwarfLineSectionSym =
1873 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1874 if (GenerateGnuPubSections) {
1875 DwarfGnuPubNamesSectionSym =
1876 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1877 DwarfGnuPubTypesSectionSym =
1878 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1879 } else if (HasDwarfPubSections) {
1880 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1881 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1884 DwarfStrSectionSym =
1885 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1886 if (useSplitDwarf()) {
1887 DwarfStrDWOSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1889 DwarfAddrSectionSym =
1890 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1891 DwarfDebugLocSectionSym =
1892 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1894 DwarfDebugLocSectionSym =
1895 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1896 DwarfDebugRangeSectionSym =
1897 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1900 // Recursively emits a debug information entry.
1901 void DwarfDebug::emitDIE(DIE &Die) {
1902 // Get the abbreviation for this DIE.
1903 const DIEAbbrev &Abbrev = Die.getAbbrev();
1905 // Emit the code (index) for the abbreviation.
1906 if (Asm->isVerbose())
1907 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1908 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1909 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1910 dwarf::TagString(Abbrev.getTag()));
1911 Asm->EmitULEB128(Abbrev.getNumber());
1913 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1914 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1916 // Emit the DIE attribute values.
1917 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1918 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1919 dwarf::Form Form = AbbrevData[i].getForm();
1920 assert(Form && "Too many attributes for DIE (check abbreviation)");
1922 if (Asm->isVerbose()) {
1923 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1924 if (Attr == dwarf::DW_AT_accessibility)
1925 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1926 cast<DIEInteger>(Values[i])->getValue()));
1929 // Emit an attribute using the defined form.
1930 Values[i]->EmitValue(Asm, Form);
1933 // Emit the DIE children if any.
1934 if (Abbrev.hasChildren()) {
1935 for (auto &Child : Die.getChildren())
1938 Asm->OutStreamer.AddComment("End Of Children Mark");
1943 // Emit the various dwarf units to the unit section USection with
1944 // the abbreviations going into ASection.
1945 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) {
1946 for (DwarfUnit *TheU : CUs) {
1947 DIE *Die = TheU->getUnitDie();
1948 const MCSection *USection = TheU->getSection();
1949 Asm->OutStreamer.SwitchSection(USection);
1951 // Emit the compile units header.
1952 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1954 // Emit size of content not including length itself
1955 Asm->OutStreamer.AddComment("Length of Unit");
1956 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1958 TheU->emitHeader(ASectionSym);
1961 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1965 // Emit the debug info section.
1966 void DwarfDebug::emitDebugInfo() {
1967 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1969 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1972 // Emit the abbreviation section.
1973 void DwarfDebug::emitAbbreviations() {
1974 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1976 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1979 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1980 // Check to see if it is worth the effort.
1981 if (!Abbreviations.empty()) {
1982 // Start the debug abbrev section.
1983 Asm->OutStreamer.SwitchSection(Section);
1985 // For each abbrevation.
1986 for (const DIEAbbrev *Abbrev : Abbreviations) {
1987 // Emit the abbrevations code (base 1 index.)
1988 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1990 // Emit the abbreviations data.
1994 // Mark end of abbreviations.
1995 Asm->EmitULEB128(0, "EOM(3)");
1999 // Emit the last address of the section and the end of the line matrix.
2000 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2001 // Define last address of section.
2002 Asm->OutStreamer.AddComment("Extended Op");
2005 Asm->OutStreamer.AddComment("Op size");
2006 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2007 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2008 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2010 Asm->OutStreamer.AddComment("Section end label");
2012 Asm->OutStreamer.EmitSymbolValue(
2013 Asm->GetTempSymbol("section_end", SectionEnd),
2014 Asm->getDataLayout().getPointerSize());
2016 // Mark end of matrix.
2017 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2023 // Emit visible names into a hashed accelerator table section.
2024 void DwarfDebug::emitAccelNames() {
2026 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2027 for (DwarfUnit *TheU : getUnits()) {
2028 for (const auto &GI : TheU->getAccelNames()) {
2029 StringRef Name = GI.getKey();
2030 for (const DIE *D : GI.second)
2031 AT.AddName(Name, D);
2035 AT.FinalizeTable(Asm, "Names");
2036 Asm->OutStreamer.SwitchSection(
2037 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2038 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2039 Asm->OutStreamer.EmitLabel(SectionBegin);
2041 // Emit the full data.
2042 AT.Emit(Asm, SectionBegin, &InfoHolder);
2045 // Emit objective C classes and categories into a hashed accelerator table
2047 void DwarfDebug::emitAccelObjC() {
2049 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2050 for (DwarfUnit *TheU : getUnits()) {
2051 for (const auto &GI : TheU->getAccelObjC()) {
2052 StringRef Name = GI.getKey();
2053 for (const DIE *D : GI.second)
2054 AT.AddName(Name, D);
2058 AT.FinalizeTable(Asm, "ObjC");
2059 Asm->OutStreamer.SwitchSection(
2060 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2061 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2062 Asm->OutStreamer.EmitLabel(SectionBegin);
2064 // Emit the full data.
2065 AT.Emit(Asm, SectionBegin, &InfoHolder);
2068 // Emit namespace dies into a hashed accelerator table.
2069 void DwarfDebug::emitAccelNamespaces() {
2071 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2072 for (DwarfUnit *TheU : getUnits()) {
2073 for (const auto &GI : TheU->getAccelNamespace()) {
2074 StringRef Name = GI.getKey();
2075 for (const DIE *D : GI.second)
2076 AT.AddName(Name, D);
2080 AT.FinalizeTable(Asm, "namespac");
2081 Asm->OutStreamer.SwitchSection(
2082 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2083 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2084 Asm->OutStreamer.EmitLabel(SectionBegin);
2086 // Emit the full data.
2087 AT.Emit(Asm, SectionBegin, &InfoHolder);
2090 // Emit type dies into a hashed accelerator table.
2091 void DwarfDebug::emitAccelTypes() {
2092 std::vector<DwarfAccelTable::Atom> Atoms;
2094 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2096 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2098 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2099 DwarfAccelTable AT(Atoms);
2100 for (DwarfUnit *TheU : getUnits()) {
2101 for (const auto &GI : TheU->getAccelTypes()) {
2102 StringRef Name = GI.getKey();
2103 for (const auto &DI : GI.second)
2104 AT.AddName(Name, DI.first, DI.second);
2108 AT.FinalizeTable(Asm, "types");
2109 Asm->OutStreamer.SwitchSection(
2110 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2111 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2112 Asm->OutStreamer.EmitLabel(SectionBegin);
2114 // Emit the full data.
2115 AT.Emit(Asm, SectionBegin, &InfoHolder);
2118 // Public name handling.
2119 // The format for the various pubnames:
2121 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2122 // for the DIE that is named.
2124 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2125 // into the CU and the index value is computed according to the type of value
2126 // for the DIE that is named.
2128 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2129 // it's the offset within the debug_info/debug_types dwo section, however, the
2130 // reference in the pubname header doesn't change.
2132 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2133 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2135 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2137 // We could have a specification DIE that has our most of our knowledge,
2138 // look for that now.
2139 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2141 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2142 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2143 Linkage = dwarf::GIEL_EXTERNAL;
2144 } else if (Die->findAttribute(dwarf::DW_AT_external))
2145 Linkage = dwarf::GIEL_EXTERNAL;
2147 switch (Die->getTag()) {
2148 case dwarf::DW_TAG_class_type:
2149 case dwarf::DW_TAG_structure_type:
2150 case dwarf::DW_TAG_union_type:
2151 case dwarf::DW_TAG_enumeration_type:
2152 return dwarf::PubIndexEntryDescriptor(
2153 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2154 ? dwarf::GIEL_STATIC
2155 : dwarf::GIEL_EXTERNAL);
2156 case dwarf::DW_TAG_typedef:
2157 case dwarf::DW_TAG_base_type:
2158 case dwarf::DW_TAG_subrange_type:
2159 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2160 case dwarf::DW_TAG_namespace:
2161 return dwarf::GIEK_TYPE;
2162 case dwarf::DW_TAG_subprogram:
2163 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2164 case dwarf::DW_TAG_constant:
2165 case dwarf::DW_TAG_variable:
2166 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2167 case dwarf::DW_TAG_enumerator:
2168 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2169 dwarf::GIEL_STATIC);
2171 return dwarf::GIEK_NONE;
2175 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2177 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2178 const MCSection *PSec =
2179 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2180 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2182 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2185 void DwarfDebug::emitDebugPubSection(
2186 bool GnuStyle, const MCSection *PSec, StringRef Name,
2187 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2188 for (const auto &NU : CUMap) {
2189 DwarfCompileUnit *TheU = NU.second;
2191 const auto &Globals = (TheU->*Accessor)();
2193 if (Globals.empty())
2196 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2198 unsigned ID = TheU->getUniqueID();
2200 // Start the dwarf pubnames section.
2201 Asm->OutStreamer.SwitchSection(PSec);
2204 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2205 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2206 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2207 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2209 Asm->OutStreamer.EmitLabel(BeginLabel);
2211 Asm->OutStreamer.AddComment("DWARF Version");
2212 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2214 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2215 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2217 Asm->OutStreamer.AddComment("Compilation Unit Length");
2218 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2220 // Emit the pubnames for this compilation unit.
2221 for (const auto &GI : Globals) {
2222 const char *Name = GI.getKeyData();
2223 const DIE *Entity = GI.second;
2225 Asm->OutStreamer.AddComment("DIE offset");
2226 Asm->EmitInt32(Entity->getOffset());
2229 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2230 Asm->OutStreamer.AddComment(
2231 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2232 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2233 Asm->EmitInt8(Desc.toBits());
2236 Asm->OutStreamer.AddComment("External Name");
2237 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2240 Asm->OutStreamer.AddComment("End Mark");
2242 Asm->OutStreamer.EmitLabel(EndLabel);
2246 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2247 const MCSection *PSec =
2248 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2249 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2251 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2254 // Emit strings into a string section.
2255 void DwarfFile::emitStrings(const MCSection *StrSection,
2256 const MCSection *OffsetSection = NULL,
2257 const MCSymbol *StrSecSym = NULL) {
2259 if (StringPool.empty())
2262 // Start the dwarf str section.
2263 Asm->OutStreamer.SwitchSection(StrSection);
2265 // Get all of the string pool entries and put them in an array by their ID so
2266 // we can sort them.
2267 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2269 for (const auto &I : StringPool)
2270 Entries.push_back(std::make_pair(I.second.second, &I));
2272 array_pod_sort(Entries.begin(), Entries.end());
2274 for (const auto &Entry : Entries) {
2275 // Emit a label for reference from debug information entries.
2276 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2278 // Emit the string itself with a terminating null byte.
2279 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2280 Entry.second->getKeyLength() + 1));
2283 // If we've got an offset section go ahead and emit that now as well.
2284 if (OffsetSection) {
2285 Asm->OutStreamer.SwitchSection(OffsetSection);
2286 unsigned offset = 0;
2287 unsigned size = 4; // FIXME: DWARF64 is 8.
2288 for (const auto &Entry : Entries) {
2289 Asm->OutStreamer.EmitIntValue(offset, size);
2290 offset += Entry.second->getKeyLength() + 1;
2295 // Emit addresses into the section given.
2296 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2298 if (AddressPool.empty())
2301 // Start the dwarf addr section.
2302 Asm->OutStreamer.SwitchSection(AddrSection);
2304 // Order the address pool entries by ID
2305 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2307 for (const auto &I : AddressPool)
2308 Entries[I.second.Number] =
2310 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2311 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2313 for (const MCExpr *Entry : Entries)
2314 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2317 // Emit visible names into a debug str section.
2318 void DwarfDebug::emitDebugStr() {
2319 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2320 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2323 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2324 const DebugLocEntry &Entry) {
2325 DIVariable DV(Entry.getVariable());
2326 if (Entry.isInt()) {
2327 DIBasicType BTy(resolve(DV.getType()));
2328 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2329 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2330 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2331 Streamer.EmitSLEB128(Entry.getInt());
2333 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2334 Streamer.EmitULEB128(Entry.getInt());
2336 } else if (Entry.isLocation()) {
2337 MachineLocation Loc = Entry.getLoc();
2338 if (!DV.hasComplexAddress())
2340 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2342 // Complex address entry.
2343 unsigned N = DV.getNumAddrElements();
2345 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2346 if (Loc.getOffset()) {
2348 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2349 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2350 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2351 Streamer.EmitSLEB128(DV.getAddrElement(1));
2353 // If first address element is OpPlus then emit
2354 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2355 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2356 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2360 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2363 // Emit remaining complex address elements.
2364 for (; i < N; ++i) {
2365 uint64_t Element = DV.getAddrElement(i);
2366 if (Element == DIBuilder::OpPlus) {
2367 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2368 Streamer.EmitULEB128(DV.getAddrElement(++i));
2369 } else if (Element == DIBuilder::OpDeref) {
2371 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2373 llvm_unreachable("unknown Opcode found in complex address");
2377 // else ... ignore constant fp. There is not any good way to
2378 // to represent them here in dwarf.
2382 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2383 Asm->OutStreamer.AddComment("Loc expr size");
2384 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2385 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2386 Asm->EmitLabelDifference(end, begin, 2);
2387 Asm->OutStreamer.EmitLabel(begin);
2389 APByteStreamer Streamer(*Asm);
2390 emitDebugLocEntry(Streamer, Entry);
2392 Asm->OutStreamer.EmitLabel(end);
2395 // Emit locations into the debug loc section.
2396 void DwarfDebug::emitDebugLoc() {
2397 // Start the dwarf loc section.
2398 Asm->OutStreamer.SwitchSection(
2399 Asm->getObjFileLowering().getDwarfLocSection());
2400 unsigned char Size = Asm->getDataLayout().getPointerSize();
2401 for (const auto &DebugLoc : DotDebugLocEntries) {
2402 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2403 for (const auto &Entry : DebugLoc.List) {
2404 // Set up the range. This range is relative to the entry point of the
2405 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2406 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2407 const DwarfCompileUnit *CU = Entry.getCU();
2408 if (CU->getRanges().size() == 1) {
2409 // Grab the begin symbol from the first range as our base.
2410 const MCSymbol *Base = CU->getRanges()[0].getStart();
2411 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2412 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2414 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2415 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2418 emitDebugLocEntryLocation(Entry);
2420 Asm->OutStreamer.EmitIntValue(0, Size);
2421 Asm->OutStreamer.EmitIntValue(0, Size);
2425 void DwarfDebug::emitDebugLocDWO() {
2426 Asm->OutStreamer.SwitchSection(
2427 Asm->getObjFileLowering().getDwarfLocDWOSection());
2428 for (const auto &DebugLoc : DotDebugLocEntries) {
2429 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2430 for (const auto &Entry : DebugLoc.List) {
2431 // Just always use start_length for now - at least that's one address
2432 // rather than two. We could get fancier and try to, say, reuse an
2433 // address we know we've emitted elsewhere (the start of the function?
2434 // The start of the CU or CU subrange that encloses this range?)
2435 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2436 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2437 Asm->EmitULEB128(idx);
2438 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2440 emitDebugLocEntryLocation(Entry);
2442 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2447 const MCSymbol *Start, *End;
2450 // Emit a debug aranges section, containing a CU lookup for any
2451 // address we can tie back to a CU.
2452 void DwarfDebug::emitDebugARanges() {
2453 // Start the dwarf aranges section.
2454 Asm->OutStreamer.SwitchSection(
2455 Asm->getObjFileLowering().getDwarfARangesSection());
2457 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2461 // Build a list of sections used.
2462 std::vector<const MCSection *> Sections;
2463 for (const auto &it : SectionMap) {
2464 const MCSection *Section = it.first;
2465 Sections.push_back(Section);
2468 // Sort the sections into order.
2469 // This is only done to ensure consistent output order across different runs.
2470 std::sort(Sections.begin(), Sections.end(), SectionSort);
2472 // Build a set of address spans, sorted by CU.
2473 for (const MCSection *Section : Sections) {
2474 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2475 if (List.size() < 2)
2478 // Sort the symbols by offset within the section.
2479 std::sort(List.begin(), List.end(),
2480 [&](const SymbolCU &A, const SymbolCU &B) {
2481 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2482 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2484 // Symbols with no order assigned should be placed at the end.
2485 // (e.g. section end labels)
2493 // If we have no section (e.g. common), just write out
2494 // individual spans for each symbol.
2495 if (Section == NULL) {
2496 for (const SymbolCU &Cur : List) {
2498 Span.Start = Cur.Sym;
2501 Spans[Cur.CU].push_back(Span);
2504 // Build spans between each label.
2505 const MCSymbol *StartSym = List[0].Sym;
2506 for (size_t n = 1, e = List.size(); n < e; n++) {
2507 const SymbolCU &Prev = List[n - 1];
2508 const SymbolCU &Cur = List[n];
2510 // Try and build the longest span we can within the same CU.
2511 if (Cur.CU != Prev.CU) {
2513 Span.Start = StartSym;
2515 Spans[Prev.CU].push_back(Span);
2522 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2524 // Build a list of CUs used.
2525 std::vector<DwarfCompileUnit *> CUs;
2526 for (const auto &it : Spans) {
2527 DwarfCompileUnit *CU = it.first;
2531 // Sort the CU list (again, to ensure consistent output order).
2532 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2533 return A->getUniqueID() < B->getUniqueID();
2536 // Emit an arange table for each CU we used.
2537 for (DwarfCompileUnit *CU : CUs) {
2538 std::vector<ArangeSpan> &List = Spans[CU];
2540 // Emit size of content not including length itself.
2541 unsigned ContentSize =
2542 sizeof(int16_t) + // DWARF ARange version number
2543 sizeof(int32_t) + // Offset of CU in the .debug_info section
2544 sizeof(int8_t) + // Pointer Size (in bytes)
2545 sizeof(int8_t); // Segment Size (in bytes)
2547 unsigned TupleSize = PtrSize * 2;
2549 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2551 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2553 ContentSize += Padding;
2554 ContentSize += (List.size() + 1) * TupleSize;
2556 // For each compile unit, write the list of spans it covers.
2557 Asm->OutStreamer.AddComment("Length of ARange Set");
2558 Asm->EmitInt32(ContentSize);
2559 Asm->OutStreamer.AddComment("DWARF Arange version number");
2560 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2561 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2562 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2563 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2564 Asm->EmitInt8(PtrSize);
2565 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2568 Asm->OutStreamer.EmitFill(Padding, 0xff);
2570 for (const ArangeSpan &Span : List) {
2571 Asm->EmitLabelReference(Span.Start, PtrSize);
2573 // Calculate the size as being from the span start to it's end.
2575 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2577 // For symbols without an end marker (e.g. common), we
2578 // write a single arange entry containing just that one symbol.
2579 uint64_t Size = SymSize[Span.Start];
2583 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2587 Asm->OutStreamer.AddComment("ARange terminator");
2588 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2589 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2593 // Emit visible names into a debug ranges section.
2594 void DwarfDebug::emitDebugRanges() {
2595 // Start the dwarf ranges section.
2596 Asm->OutStreamer.SwitchSection(
2597 Asm->getObjFileLowering().getDwarfRangesSection());
2599 // Size for our labels.
2600 unsigned char Size = Asm->getDataLayout().getPointerSize();
2602 // Grab the specific ranges for the compile units in the module.
2603 for (const auto &I : CUMap) {
2604 DwarfCompileUnit *TheCU = I.second;
2606 // Emit a symbol so we can find the beginning of our ranges.
2607 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2609 // Iterate over the misc ranges for the compile units in the module.
2610 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2611 // Emit our symbol so we can find the beginning of the range.
2612 Asm->OutStreamer.EmitLabel(List.getSym());
2614 for (const RangeSpan &Range : List.getRanges()) {
2615 const MCSymbol *Begin = Range.getStart();
2616 const MCSymbol *End = Range.getEnd();
2617 assert(Begin && "Range without a begin symbol?");
2618 assert(End && "Range without an end symbol?");
2619 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2620 Asm->OutStreamer.EmitSymbolValue(End, Size);
2623 // And terminate the list with two 0 values.
2624 Asm->OutStreamer.EmitIntValue(0, Size);
2625 Asm->OutStreamer.EmitIntValue(0, Size);
2628 // Now emit a range for the CU itself.
2629 if (TheCU->getRanges().size() > 1) {
2630 Asm->OutStreamer.EmitLabel(
2631 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2632 for (const RangeSpan &Range : TheCU->getRanges()) {
2633 const MCSymbol *Begin = Range.getStart();
2634 const MCSymbol *End = Range.getEnd();
2635 assert(Begin && "Range without a begin symbol?");
2636 assert(End && "Range without an end symbol?");
2637 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2638 Asm->OutStreamer.EmitSymbolValue(End, Size);
2640 // And terminate the list with two 0 values.
2641 Asm->OutStreamer.EmitIntValue(0, Size);
2642 Asm->OutStreamer.EmitIntValue(0, Size);
2647 // DWARF5 Experimental Separate Dwarf emitters.
2649 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2651 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2652 U->getCUNode().getSplitDebugFilename());
2654 if (!CompilationDir.empty())
2655 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2657 addGnuPubAttributes(NewU, Die);
2659 SkeletonHolder.addUnit(NewU);
2662 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2663 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2664 // DW_AT_addr_base, DW_AT_ranges_base.
2665 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2667 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2668 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2669 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2670 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2671 DwarfInfoSectionSym);
2673 NewCU->initStmtList(DwarfLineSectionSym);
2675 initSkeletonUnit(CU, Die, NewCU);
2680 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2682 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2683 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2684 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2686 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2687 DwarfTypeUnit *NewTU =
2688 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2689 NewTU->setTypeSignature(TU->getTypeSignature());
2690 NewTU->setType(NULL);
2692 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2694 initSkeletonUnit(TU, Die, NewTU);
2698 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2699 // compile units that would normally be in debug_info.
2700 void DwarfDebug::emitDebugInfoDWO() {
2701 assert(useSplitDwarf() && "No split dwarf debug info?");
2702 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2703 // emit relocations into the dwo file.
2704 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2707 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2708 // abbreviations for the .debug_info.dwo section.
2709 void DwarfDebug::emitDebugAbbrevDWO() {
2710 assert(useSplitDwarf() && "No split dwarf?");
2711 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2714 void DwarfDebug::emitDebugLineDWO() {
2715 assert(useSplitDwarf() && "No split dwarf?");
2716 Asm->OutStreamer.SwitchSection(
2717 Asm->getObjFileLowering().getDwarfLineDWOSection());
2718 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2721 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2722 // string section and is identical in format to traditional .debug_str
2724 void DwarfDebug::emitDebugStrDWO() {
2725 assert(useSplitDwarf() && "No split dwarf?");
2726 const MCSection *OffSec =
2727 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2728 const MCSymbol *StrSym = DwarfStrSectionSym;
2729 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2733 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2734 if (!useSplitDwarf())
2737 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2738 return &SplitTypeUnitFileTable;
2741 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2742 StringRef Identifier, DIE *RefDie,
2743 DICompositeType CTy) {
2744 // Flag the type unit reference as a declaration so that if it contains
2745 // members (implicit special members, static data member definitions, member
2746 // declarations for definitions in this CU, etc) consumers don't get confused
2747 // and think this is a full definition.
2748 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2750 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2752 CU.addDIETypeSignature(RefDie, *TU);
2756 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2757 DwarfTypeUnit *NewTU =
2758 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, CU, Asm, this,
2759 &InfoHolder, getDwoLineTable(CU));
2761 InfoHolder.addUnit(NewTU);
2763 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2767 Hash.update(Identifier);
2768 // ... take the least significant 8 bytes and return those. Our MD5
2769 // implementation always returns its results in little endian, swap bytes
2771 MD5::MD5Result Result;
2773 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2774 NewTU->setTypeSignature(Signature);
2775 if (useSplitDwarf())
2776 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2778 CU.applyStmtList(*UnitDie);
2780 NewTU->setType(NewTU->createTypeDIE(CTy));
2784 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2785 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2787 CU.addDIETypeSignature(RefDie, *NewTU);
2790 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2791 MCSymbol *Begin, MCSymbol *End) {
2792 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2793 if (DwarfVersion < 4)
2794 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2796 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);