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 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
63 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
64 cl::desc("Add the CU hash as the dwo_id."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static cl::opt<unsigned>
106 DwarfVersionNumber("dwarf-version", cl::Hidden,
107 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
110 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
111 cl::desc("Generate DW_AT_ranges for compile units"),
114 static const char *const DWARFGroupName = "DWARF Emission";
115 static const char *const DbgTimerName = "DWARF Debug Writer";
117 //===----------------------------------------------------------------------===//
121 /// resolve - Look in the DwarfDebug map for the MDNode that
122 /// corresponds to the reference.
123 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
124 return DD->resolve(Ref);
127 DIType DbgVariable::getType() const {
128 DIType Ty = Var.getType();
129 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
130 // addresses instead.
131 if (Var.isBlockByrefVariable()) {
132 /* Byref variables, in Blocks, are declared by the programmer as
133 "SomeType VarName;", but the compiler creates a
134 __Block_byref_x_VarName struct, and gives the variable VarName
135 either the struct, or a pointer to the struct, as its type. This
136 is necessary for various behind-the-scenes things the compiler
137 needs to do with by-reference variables in blocks.
139 However, as far as the original *programmer* is concerned, the
140 variable should still have type 'SomeType', as originally declared.
142 The following function dives into the __Block_byref_x_VarName
143 struct to find the original type of the variable. This will be
144 passed back to the code generating the type for the Debug
145 Information Entry for the variable 'VarName'. 'VarName' will then
146 have the original type 'SomeType' in its debug information.
148 The original type 'SomeType' will be the type of the field named
149 'VarName' inside the __Block_byref_x_VarName struct.
151 NOTE: In order for this to not completely fail on the debugger
152 side, the Debug Information Entry for the variable VarName needs to
153 have a DW_AT_location that tells the debugger how to unwind through
154 the pointers and __Block_byref_x_VarName struct to find the actual
155 value of the variable. The function addBlockByrefType does this. */
157 uint16_t tag = Ty.getTag();
159 if (tag == dwarf::DW_TAG_pointer_type)
160 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
162 DIArray Elements = DICompositeType(subType).getTypeArray();
163 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
164 DIDerivedType DT(Elements.getElement(i));
165 if (getName() == DT.getName())
166 return (resolve(DT.getTypeDerivedFrom()));
172 } // end llvm namespace
174 /// Return Dwarf Version by checking module flags.
175 static unsigned getDwarfVersionFromModule(const Module *M) {
176 Value *Val = M->getModuleFlag("Dwarf Version");
178 return dwarf::DWARF_VERSION;
179 return cast<ConstantInt>(Val)->getZExtValue();
182 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
183 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
184 PrevLabel(NULL), GlobalRangeCount(0),
185 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
186 UsedNonDefaultText(false),
187 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
189 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
190 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
191 DwarfAddrSectionSym = 0;
192 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
193 FunctionBeginSym = FunctionEndSym = 0;
197 // Turn on accelerator tables for Darwin by default, pubnames by
198 // default for non-Darwin, and handle split dwarf.
199 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
201 if (DwarfAccelTables == Default)
202 HasDwarfAccelTables = IsDarwin;
204 HasDwarfAccelTables = DwarfAccelTables == Enable;
206 if (SplitDwarf == Default)
207 HasSplitDwarf = false;
209 HasSplitDwarf = SplitDwarf == Enable;
211 if (DwarfPubSections == Default)
212 HasDwarfPubSections = !IsDarwin;
214 HasDwarfPubSections = DwarfPubSections == Enable;
216 DwarfVersion = DwarfVersionNumber
218 : getDwarfVersionFromModule(MMI->getModule());
221 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = 0) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 DwarfFile::~DwarfFile() {
240 for (DwarfUnit *DU : CUs)
244 MCSymbol *DwarfFile::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol *, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
264 Entry.second = NextStringPoolNumber++;
265 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
273 ++NextAddrPoolNumber;
274 return P.first->second.Number;
277 // Define a unique number for the abbreviation.
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280 // Check the set for priors.
281 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
283 // If it's newly added.
284 if (InSet == &Abbrev) {
285 // Add to abbreviation list.
286 Abbreviations.push_back(&Abbrev);
288 // Assign the vector position + 1 as its number.
289 Abbrev.setNumber(Abbreviations.size());
291 // Assign existing abbreviation number.
292 Abbrev.setNumber(InSet->getNumber());
296 static bool isObjCClass(StringRef Name) {
297 return Name.startswith("+") || Name.startswith("-");
300 static bool hasObjCCategory(StringRef Name) {
301 if (!isObjCClass(Name))
304 return Name.find(") ") != StringRef::npos;
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326 std::string LA = (A ? A->getLabelBeginName() : "");
327 std::string LB = (B ? B->getLabelBeginName() : "");
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336 if (!SP.isDefinition())
338 TheU->addAccelName(SP.getName(), Die);
340 // If the linkage name is different than the name, go ahead and output
341 // that as well into the name table.
342 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343 TheU->addAccelName(SP.getLinkageName(), Die);
345 // If this is an Objective-C selector name add it to the ObjC accelerator
347 if (isObjCClass(SP.getName())) {
348 StringRef Class, Category;
349 getObjCClassCategory(SP.getName(), Class, Category);
350 TheU->addAccelObjC(Class, Die);
352 TheU->addAccelObjC(Category, Die);
353 // Also add the base method name to the name table.
354 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
363 DIDescriptor D(Context);
364 if (D.isSubprogram())
367 return isSubprogramContext(resolve(DIType(Context).getContext()));
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
376 DIE *SPDie = SPCU->getDIE(SP);
378 assert(SPDie && "Unable to find subprogram DIE!");
380 // If we're updating an abstract DIE, then we will be adding the children and
381 // object pointer later on. But what we don't want to do is process the
382 // concrete DIE twice.
383 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384 // Pick up abstract subprogram DIE.
386 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 SPCU->constructSubprogramArguments(*SPDie, Args);
407 DIE *SPDeclDie = SPDie;
408 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
409 *SPCU->getUnitDie());
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
415 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
417 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
418 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
419 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
421 // Add name to the name table, we do this here because we're guaranteed
422 // to have concrete versions of our DW_TAG_subprogram nodes.
423 addSubprogramNames(SPCU, SP, SPDie);
428 /// Check whether we should create a DIE for the given Scope, return true
429 /// if we don't create a DIE (the corresponding DIE is null).
430 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
431 if (Scope->isAbstractScope())
434 // We don't create a DIE if there is no Range.
435 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
439 if (Ranges.size() > 1)
442 // We don't create a DIE if we have a single Range and the end label
444 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
445 MCSymbol *End = getLabelAfterInsn(RI->second);
449 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
450 dwarf::Attribute A, const MCSymbol *L,
451 const MCSymbol *Sec) {
452 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
453 U->addSectionLabel(D, A, L);
455 U->addSectionDelta(D, A, L, Sec);
458 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
459 const SmallVectorImpl<InsnRange> &Range) {
460 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
461 // emitting it appropriately.
462 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
463 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
464 DwarfDebugRangeSectionSym);
466 RangeSpanList List(RangeSym);
467 for (const InsnRange &R : Range) {
468 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
469 List.addRange(std::move(Span));
472 // Add the range list to the set of ranges to be emitted.
473 TheCU->addRangeList(std::move(List));
476 // Construct new DW_TAG_lexical_block for this scope and attach
477 // DW_AT_low_pc/DW_AT_high_pc labels.
478 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
479 LexicalScope *Scope) {
480 if (isLexicalScopeDIENull(Scope))
483 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
484 if (Scope->isAbstractScope())
487 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
489 // If we have multiple ranges, emit them into the range section.
490 if (ScopeRanges.size() > 1) {
491 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
495 // Construct the address range for this DIE.
496 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
497 MCSymbol *Start = getLabelBeforeInsn(RI->first);
498 MCSymbol *End = getLabelAfterInsn(RI->second);
499 assert(End && "End label should not be null!");
501 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
502 assert(End->isDefined() && "Invalid end label for an inlined scope!");
504 attachLowHighPC(TheCU, ScopeDIE, Start, End);
509 // This scope represents inlined body of a function. Construct DIE to
510 // represent this concrete inlined copy of the function.
511 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
512 LexicalScope *Scope) {
513 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
514 assert(!ScopeRanges.empty() &&
515 "LexicalScope does not have instruction markers!");
517 if (!Scope->getScopeNode())
519 DIScope DS(Scope->getScopeNode());
520 DISubprogram InlinedSP = getDISubprogram(DS);
521 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
523 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
527 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
528 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
530 // If we have multiple ranges, emit them into the range section.
531 if (ScopeRanges.size() > 1)
532 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
534 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
535 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
536 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
538 if (StartLabel == 0 || EndLabel == 0)
539 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
541 assert(StartLabel->isDefined() &&
542 "Invalid starting label for an inlined scope!");
543 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
545 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
548 InlinedSubprogramDIEs.insert(OriginDIE);
550 // Add the call site information to the DIE.
551 DILocation DL(Scope->getInlinedAt());
552 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
553 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
554 TheCU->getUniqueID()));
555 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
557 // Add name to the name table, we do this here because we're guaranteed
558 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
559 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
564 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
566 SmallVectorImpl<DIE *> &Children) {
567 DIE *ObjectPointer = NULL;
569 // Collect arguments for current function.
570 if (LScopes.isCurrentFunctionScope(Scope)) {
571 for (DbgVariable *ArgDV : CurrentFnArguments)
574 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
575 Children.push_back(Arg);
576 if (ArgDV->isObjectPointer())
580 // If this is a variadic function, add an unspecified parameter.
581 DISubprogram SP(Scope->getScopeNode());
582 DIArray FnArgs = SP.getType().getTypeArray();
583 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
584 .isUnspecifiedParameter()) {
585 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
586 Children.push_back(Ellipsis);
590 // Collect lexical scope children first.
591 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
592 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
593 Scope->isAbstractScope())) {
594 Children.push_back(Variable);
595 if (DV->isObjectPointer())
596 ObjectPointer = Variable;
598 for (LexicalScope *LS : Scope->getChildren())
599 if (DIE *Nested = constructScopeDIE(TheCU, LS))
600 Children.push_back(Nested);
601 return ObjectPointer;
604 // Construct a DIE for this scope.
605 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
606 LexicalScope *Scope) {
607 if (!Scope || !Scope->getScopeNode())
610 DIScope DS(Scope->getScopeNode());
612 SmallVector<DIE *, 8> Children;
613 DIE *ObjectPointer = NULL;
614 bool ChildrenCreated = false;
616 // We try to create the scope DIE first, then the children DIEs. This will
617 // avoid creating un-used children then removing them later when we find out
618 // the scope DIE is null.
619 DIE *ScopeDIE = NULL;
620 if (Scope->getInlinedAt())
621 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
622 else if (DS.isSubprogram()) {
623 ProcessedSPNodes.insert(DS);
624 if (Scope->isAbstractScope()) {
625 ScopeDIE = TheCU->getDIE(DS);
626 // Note down abstract DIE.
628 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
630 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
632 // Early exit when we know the scope DIE is going to be null.
633 if (isLexicalScopeDIENull(Scope))
636 // We create children here when we know the scope DIE is not going to be
637 // null and the children will be added to the scope DIE.
638 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
639 ChildrenCreated = true;
641 // There is no need to emit empty lexical block DIE.
642 std::pair<ImportedEntityMap::const_iterator,
643 ImportedEntityMap::const_iterator> Range =
645 ScopesWithImportedEntities.begin(),
646 ScopesWithImportedEntities.end(),
647 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
649 if (Children.empty() && Range.first == Range.second)
651 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
652 assert(ScopeDIE && "Scope DIE should not be null.");
653 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
655 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
659 assert(Children.empty() &&
660 "We create children only when the scope DIE is not null.");
663 if (!ChildrenCreated)
664 // We create children when the scope DIE is not null.
665 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
668 for (DIE *I : Children)
669 ScopeDIE->addChild(I);
671 if (DS.isSubprogram() && ObjectPointer != NULL)
672 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
677 // Look up the source id with the given directory and source file names.
678 // If none currently exists, create a new id and insert it in the
679 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
681 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
683 // If we print assembly, we can't separate .file entries according to
684 // compile units. Thus all files will belong to the default compile unit.
686 // FIXME: add a better feature test than hasRawTextSupport. Even better,
687 // extend .file to support this.
688 if (Asm->OutStreamer.hasRawTextSupport())
691 // If FE did not provide a file name, then assume stdin.
692 if (FileName.empty())
693 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
695 // TODO: this might not belong here. See if we can factor this better.
696 if (DirName == CompilationDir)
699 // FileIDCUMap stores the current ID for the given compile unit.
700 unsigned SrcId = FileIDCUMap[CUID] + 1;
702 // We look up the CUID/file/dir by concatenating them with a zero byte.
703 SmallString<128> NamePair;
704 NamePair += utostr(CUID);
707 NamePair += '\0'; // Zero bytes are not allowed in paths.
708 NamePair += FileName;
710 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
711 if (Ent.getValue() != SrcId)
712 return Ent.getValue();
714 FileIDCUMap[CUID] = SrcId;
715 // Print out a .file directive to specify files for .loc directives.
716 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
721 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
722 if (!GenerateGnuPubSections)
725 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
728 // Create new DwarfCompileUnit for the given metadata node with tag
729 // DW_TAG_compile_unit.
730 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
731 StringRef FN = DIUnit.getFilename();
732 CompilationDir = DIUnit.getDirectory();
734 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
735 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
736 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
737 InfoHolder.addUnit(NewCU);
739 FileIDCUMap[NewCU->getUniqueID()] = 0;
741 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
742 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
743 DIUnit.getLanguage());
744 NewCU->addString(Die, dwarf::DW_AT_name, FN);
746 if (!useSplitDwarf()) {
747 NewCU->initStmtList(DwarfLineSectionSym);
749 // If we're using split dwarf the compilation dir is going to be in the
750 // skeleton CU and so we don't need to duplicate it here.
751 if (!CompilationDir.empty())
752 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
754 addGnuPubAttributes(NewCU, Die);
757 if (DIUnit.isOptimized())
758 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
760 StringRef Flags = DIUnit.getFlags();
762 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
764 if (unsigned RVer = DIUnit.getRunTimeVersion())
765 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
766 dwarf::DW_FORM_data1, RVer);
771 if (useSplitDwarf()) {
772 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
773 DwarfInfoDWOSectionSym);
774 NewCU->setSkeleton(constructSkeletonCU(NewCU));
776 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
777 DwarfInfoSectionSym);
779 CUMap.insert(std::make_pair(DIUnit, NewCU));
780 CUDieMap.insert(std::make_pair(Die, NewCU));
784 // Construct subprogram DIE.
785 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
787 // FIXME: We should only call this routine once, however, during LTO if a
788 // program is defined in multiple CUs we could end up calling it out of
789 // beginModule as we walk the CUs.
791 DwarfCompileUnit *&CURef = SPMap[N];
797 if (!SP.isDefinition())
798 // This is a method declaration which will be handled while constructing
802 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
804 // Expose as a global name.
805 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
808 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
810 DIImportedEntity Module(N);
811 assert(Module.Verify());
812 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
813 constructImportedEntityDIE(TheCU, Module, D);
816 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
817 const MDNode *N, DIE *Context) {
818 DIImportedEntity Module(N);
819 assert(Module.Verify());
820 return constructImportedEntityDIE(TheCU, Module, Context);
823 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
824 const DIImportedEntity &Module,
826 assert(Module.Verify() &&
827 "Use one of the MDNode * overloads to handle invalid metadata");
828 assert(Context && "Should always have a context for an imported_module");
829 DIE *IMDie = new DIE(Module.getTag());
830 TheCU->insertDIE(Module, IMDie);
832 DIDescriptor Entity = Module.getEntity();
833 if (Entity.isNameSpace())
834 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
835 else if (Entity.isSubprogram())
836 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
837 else if (Entity.isType())
838 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
840 EntityDie = TheCU->getDIE(Entity);
841 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
842 Module.getContext().getDirectory(),
843 TheCU->getUniqueID());
844 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
845 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
846 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
847 StringRef Name = Module.getName();
849 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
850 Context->addChild(IMDie);
853 // Emit all Dwarf sections that should come prior to the content. Create
854 // global DIEs and emit initial debug info sections. This is invoked by
855 // the target AsmPrinter.
856 void DwarfDebug::beginModule() {
857 if (DisableDebugInfoPrinting)
860 const Module *M = MMI->getModule();
862 // If module has named metadata anchors then use them, otherwise scan the
863 // module using debug info finder to collect debug info.
864 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
867 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
869 // Emit initial sections so we can reference labels later.
872 for (MDNode *N : CU_Nodes->operands()) {
873 DICompileUnit CUNode(N);
874 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
875 DIArray ImportedEntities = CUNode.getImportedEntities();
876 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
877 ScopesWithImportedEntities.push_back(std::make_pair(
878 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
879 ImportedEntities.getElement(i)));
880 std::sort(ScopesWithImportedEntities.begin(),
881 ScopesWithImportedEntities.end(), less_first());
882 DIArray GVs = CUNode.getGlobalVariables();
883 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
884 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
885 DIArray SPs = CUNode.getSubprograms();
886 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
887 constructSubprogramDIE(CU, SPs.getElement(i));
888 DIArray EnumTypes = CUNode.getEnumTypes();
889 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
890 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
891 DIArray RetainedTypes = CUNode.getRetainedTypes();
892 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
893 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
894 // Emit imported_modules last so that the relevant context is already
896 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
897 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
900 // Tell MMI that we have debug info.
901 MMI->setDebugInfoAvailability(true);
903 // Prime section data.
904 SectionMap[Asm->getObjFileLowering().getTextSection()];
907 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
908 void DwarfDebug::computeInlinedDIEs() {
909 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
910 for (DIE *ISP : InlinedSubprogramDIEs)
911 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
913 for (const auto &AI : AbstractSPDies) {
914 DIE *ISP = AI.second;
915 if (InlinedSubprogramDIEs.count(ISP))
917 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
921 // Collect info for variables that were optimized out.
922 void DwarfDebug::collectDeadVariables() {
923 const Module *M = MMI->getModule();
925 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
926 for (MDNode *N : CU_Nodes->operands()) {
927 DICompileUnit TheCU(N);
928 DIArray Subprograms = TheCU.getSubprograms();
929 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
930 DISubprogram SP(Subprograms.getElement(i));
931 if (ProcessedSPNodes.count(SP) != 0)
933 if (!SP.isSubprogram())
935 if (!SP.isDefinition())
937 DIArray Variables = SP.getVariables();
938 if (Variables.getNumElements() == 0)
941 // Construct subprogram DIE and add variables DIEs.
942 DwarfCompileUnit *SPCU =
943 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
944 assert(SPCU && "Unable to find Compile Unit!");
945 // FIXME: See the comment in constructSubprogramDIE about duplicate
947 constructSubprogramDIE(SPCU, SP);
948 DIE *SPDIE = SPCU->getDIE(SP);
949 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
950 DIVariable DV(Variables.getElement(vi));
951 if (!DV.isVariable())
953 DbgVariable NewVar(DV, NULL, this);
954 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
955 SPDIE->addChild(VariableDIE);
962 void DwarfDebug::finalizeModuleInfo() {
963 // Collect info for variables that were optimized out.
964 collectDeadVariables();
966 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
967 computeInlinedDIEs();
969 // Handle anything that needs to be done on a per-unit basis after
970 // all other generation.
971 for (DwarfUnit *TheU : getUnits()) {
972 // Emit DW_AT_containing_type attribute to connect types with their
973 // vtable holding type.
974 TheU->constructContainingTypeDIEs();
976 // Add CU specific attributes if we need to add any.
977 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
978 // If we're splitting the dwarf out now that we've got the entire
979 // CU then add the dwo id to it.
980 DwarfCompileUnit *SkCU =
981 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
982 if (useSplitDwarf()) {
983 // This should be a unique identifier when we want to build .dwp files.
985 if (GenerateCUHash) {
987 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
989 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
990 dwarf::DW_FORM_data8, ID);
991 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
992 dwarf::DW_FORM_data8, ID);
995 // If we have code split among multiple sections or we've requested
996 // it then emit a DW_AT_ranges attribute on the unit that will remain
997 // in the .o file, otherwise add a DW_AT_low_pc.
998 // FIXME: Also add a high pc if we can.
999 // FIXME: We should use ranges if we have multiple compile units or
1000 // allow reordering of code ala .subsections_via_symbols in mach-o.
1001 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1002 if (useCURanges() && TheU->getRanges().size()) {
1003 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1004 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1005 DwarfDebugRangeSectionSym);
1007 // A DW_AT_low_pc attribute may also be specified in combination with
1008 // DW_AT_ranges to specify the default base address for use in location
1009 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1010 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1013 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1018 // Compute DIE offsets and sizes.
1019 InfoHolder.computeSizeAndOffsets();
1020 if (useSplitDwarf())
1021 SkeletonHolder.computeSizeAndOffsets();
1024 void DwarfDebug::endSections() {
1025 // Filter labels by section.
1026 for (const SymbolCU &SCU : ArangeLabels) {
1027 if (SCU.Sym->isInSection()) {
1028 // Make a note of this symbol and it's section.
1029 const MCSection *Section = &SCU.Sym->getSection();
1030 if (!Section->getKind().isMetadata())
1031 SectionMap[Section].push_back(SCU);
1033 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1034 // appear in the output. This sucks as we rely on sections to build
1035 // arange spans. We can do it without, but it's icky.
1036 SectionMap[NULL].push_back(SCU);
1040 // Build a list of sections used.
1041 std::vector<const MCSection *> Sections;
1042 for (const auto &it : SectionMap) {
1043 const MCSection *Section = it.first;
1044 Sections.push_back(Section);
1047 // Sort the sections into order.
1048 // This is only done to ensure consistent output order across different runs.
1049 std::sort(Sections.begin(), Sections.end(), SectionSort);
1051 // Add terminating symbols for each section.
1052 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1053 const MCSection *Section = Sections[ID];
1054 MCSymbol *Sym = NULL;
1057 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1058 // if we know the section name up-front. For user-created sections, the
1059 // resulting label may not be valid to use as a label. (section names can
1060 // use a greater set of characters on some systems)
1061 Sym = Asm->GetTempSymbol("debug_end", ID);
1062 Asm->OutStreamer.SwitchSection(Section);
1063 Asm->OutStreamer.EmitLabel(Sym);
1066 // Insert a final terminator.
1067 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1070 // For now only turn on CU ranges if we've explicitly asked for it,
1071 // we have -ffunction-sections enabled, we've emitted a function
1072 // into a unique section, or we're using LTO. If we're using LTO then
1073 // we can't know that any particular function in the module is correlated
1074 // to a particular CU and so we need to be conservative. At this point all
1075 // sections should be finalized except for dwarf sections.
1076 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1077 TargetMachine::getFunctionSections();
1080 // Emit all Dwarf sections that should come after the content.
1081 void DwarfDebug::endModule() {
1088 // End any existing sections.
1089 // TODO: Does this need to happen?
1092 // Finalize the debug info for the module.
1093 finalizeModuleInfo();
1097 // Emit all the DIEs into a debug info section.
1100 // Corresponding abbreviations into a abbrev section.
1101 emitAbbreviations();
1103 // Emit info into a debug loc section.
1106 // Emit info into a debug aranges section.
1107 if (GenerateARangeSection)
1110 // Emit info into a debug ranges section.
1113 if (useSplitDwarf()) {
1116 emitDebugAbbrevDWO();
1117 // Emit DWO addresses.
1118 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1121 // Emit info into the dwarf accelerator table sections.
1122 if (useDwarfAccelTables()) {
1125 emitAccelNamespaces();
1129 // Emit the pubnames and pubtypes sections if requested.
1130 if (HasDwarfPubSections) {
1131 emitDebugPubNames(GenerateGnuPubSections);
1132 emitDebugPubTypes(GenerateGnuPubSections);
1138 // Reset these for the next Module if we have one.
1142 // Find abstract variable, if any, associated with Var.
1143 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1144 DebugLoc ScopeLoc) {
1145 LLVMContext &Ctx = DV->getContext();
1146 // More then one inlined variable corresponds to one abstract variable.
1147 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1148 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1150 return AbsDbgVariable;
1152 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1156 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1157 addScopeVariable(Scope, AbsDbgVariable);
1158 AbstractVariables[Var] = AbsDbgVariable;
1159 return AbsDbgVariable;
1162 // If Var is a current function argument then add it to CurrentFnArguments list.
1163 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1164 if (!LScopes.isCurrentFunctionScope(Scope))
1166 DIVariable DV = Var->getVariable();
1167 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1169 unsigned ArgNo = DV.getArgNumber();
1173 size_t Size = CurrentFnArguments.size();
1175 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1176 // llvm::Function argument size is not good indicator of how many
1177 // arguments does the function have at source level.
1179 CurrentFnArguments.resize(ArgNo * 2);
1180 CurrentFnArguments[ArgNo - 1] = Var;
1184 // Collect variable information from side table maintained by MMI.
1185 void DwarfDebug::collectVariableInfoFromMMITable(
1186 SmallPtrSet<const MDNode *, 16> &Processed) {
1187 for (const auto &VI : MMI->getVariableDbgInfo()) {
1190 Processed.insert(VI.Var);
1191 DIVariable DV(VI.Var);
1192 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1194 // If variable scope is not found then skip this variable.
1198 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1199 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1200 RegVar->setFrameIndex(VI.Slot);
1201 if (!addCurrentFnArgument(RegVar, Scope))
1202 addScopeVariable(Scope, RegVar);
1204 AbsDbgVariable->setFrameIndex(VI.Slot);
1208 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1210 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1211 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1212 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1213 MI->getOperand(0).getReg() &&
1214 (MI->getOperand(1).isImm() ||
1215 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1218 // Get .debug_loc entry for the instruction range starting at MI.
1219 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1220 const MCSymbol *FLabel,
1221 const MCSymbol *SLabel,
1222 const MachineInstr *MI) {
1223 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1225 assert(MI->getNumOperands() == 3);
1226 if (MI->getOperand(0).isReg()) {
1227 MachineLocation MLoc;
1228 // If the second operand is an immediate, this is a
1229 // register-indirect address.
1230 if (!MI->getOperand(1).isImm())
1231 MLoc.set(MI->getOperand(0).getReg());
1233 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1234 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1236 if (MI->getOperand(0).isImm())
1237 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1238 if (MI->getOperand(0).isFPImm())
1239 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1240 if (MI->getOperand(0).isCImm())
1241 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1243 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1246 // Find variables for each lexical scope.
1248 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1250 // Grab the variable info that was squirreled away in the MMI side-table.
1251 collectVariableInfoFromMMITable(Processed);
1253 for (const MDNode *Var : UserVariables) {
1254 if (Processed.count(Var))
1257 // History contains relevant DBG_VALUE instructions for Var and instructions
1259 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1260 if (History.empty())
1262 const MachineInstr *MInsn = History.front();
1265 LexicalScope *Scope = NULL;
1266 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1267 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1268 Scope = LScopes.getCurrentFunctionScope();
1269 else if (MDNode *IA = DV.getInlinedAt())
1270 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1272 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1273 // If variable scope is not found then skip this variable.
1277 Processed.insert(DV);
1278 assert(MInsn->isDebugValue() && "History must begin with debug value");
1279 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1280 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1281 if (!addCurrentFnArgument(RegVar, Scope))
1282 addScopeVariable(Scope, RegVar);
1284 AbsVar->setMInsn(MInsn);
1286 // Simplify ranges that are fully coalesced.
1287 if (History.size() <= 1 ||
1288 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1289 RegVar->setMInsn(MInsn);
1293 // Handle multiple DBG_VALUE instructions describing one variable.
1294 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1296 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1297 HI = History.begin(),
1300 const MachineInstr *Begin = *HI;
1301 assert(Begin->isDebugValue() && "Invalid History entry");
1303 // Check if DBG_VALUE is truncating a range.
1304 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1305 !Begin->getOperand(0).getReg())
1308 // Compute the range for a register location.
1309 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1310 const MCSymbol *SLabel = 0;
1313 // If Begin is the last instruction in History then its value is valid
1314 // until the end of the function.
1315 SLabel = FunctionEndSym;
1317 const MachineInstr *End = HI[1];
1318 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1319 << "\t" << *Begin << "\t" << *End << "\n");
1320 if (End->isDebugValue())
1321 SLabel = getLabelBeforeInsn(End);
1323 // End is a normal instruction clobbering the range.
1324 SLabel = getLabelAfterInsn(End);
1325 assert(SLabel && "Forgot label after clobber instruction");
1330 // The value is valid until the next DBG_VALUE or clobber.
1331 DotDebugLocEntries.push_back(
1332 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1334 DotDebugLocEntries.push_back(DotDebugLocEntry());
1337 // Collect info for variables that were optimized out.
1338 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1339 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1340 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1341 DIVariable DV(Variables.getElement(i));
1342 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1344 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1345 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1349 // Return Label preceding the instruction.
1350 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1351 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1352 assert(Label && "Didn't insert label before instruction");
1356 // Return Label immediately following the instruction.
1357 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1358 return LabelsAfterInsn.lookup(MI);
1361 // Process beginning of an instruction.
1362 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1365 // Check if source location changes, but ignore DBG_VALUE locations.
1366 if (!MI->isDebugValue()) {
1367 DebugLoc DL = MI->getDebugLoc();
1368 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1371 if (DL == PrologEndLoc) {
1372 Flags |= DWARF2_FLAG_PROLOGUE_END;
1373 PrologEndLoc = DebugLoc();
1375 if (PrologEndLoc.isUnknown())
1376 Flags |= DWARF2_FLAG_IS_STMT;
1378 if (!DL.isUnknown()) {
1379 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1380 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1382 recordSourceLine(0, 0, 0, 0);
1386 // Insert labels where requested.
1387 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1388 LabelsBeforeInsn.find(MI);
1391 if (I == LabelsBeforeInsn.end())
1394 // Label already assigned.
1399 PrevLabel = MMI->getContext().CreateTempSymbol();
1400 Asm->OutStreamer.EmitLabel(PrevLabel);
1402 I->second = PrevLabel;
1405 // Process end of an instruction.
1406 void DwarfDebug::endInstruction() {
1408 // Don't create a new label after DBG_VALUE instructions.
1409 // They don't generate code.
1410 if (!CurMI->isDebugValue())
1413 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1414 LabelsAfterInsn.find(CurMI);
1418 if (I == LabelsAfterInsn.end())
1421 // Label already assigned.
1425 // We need a label after this instruction.
1427 PrevLabel = MMI->getContext().CreateTempSymbol();
1428 Asm->OutStreamer.EmitLabel(PrevLabel);
1430 I->second = PrevLabel;
1433 // Each LexicalScope has first instruction and last instruction to mark
1434 // beginning and end of a scope respectively. Create an inverse map that list
1435 // scopes starts (and ends) with an instruction. One instruction may start (or
1436 // end) multiple scopes. Ignore scopes that are not reachable.
1437 void DwarfDebug::identifyScopeMarkers() {
1438 SmallVector<LexicalScope *, 4> WorkList;
1439 WorkList.push_back(LScopes.getCurrentFunctionScope());
1440 while (!WorkList.empty()) {
1441 LexicalScope *S = WorkList.pop_back_val();
1443 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1444 if (!Children.empty())
1445 WorkList.append(Children.begin(), Children.end());
1447 if (S->isAbstractScope())
1450 for (const InsnRange &R : S->getRanges()) {
1451 assert(R.first && "InsnRange does not have first instruction!");
1452 assert(R.second && "InsnRange does not have second instruction!");
1453 requestLabelBeforeInsn(R.first);
1454 requestLabelAfterInsn(R.second);
1459 // Gather pre-function debug information. Assumes being called immediately
1460 // after the function entry point has been emitted.
1461 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1464 // If there's no debug info for the function we're not going to do anything.
1465 if (!MMI->hasDebugInfo())
1468 // Grab the lexical scopes for the function, if we don't have any of those
1469 // then we're not going to be able to do anything.
1470 LScopes.initialize(*MF);
1471 if (LScopes.empty())
1474 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1476 // Make sure that each lexical scope will have a begin/end label.
1477 identifyScopeMarkers();
1479 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1480 // belongs to so that we add to the correct per-cu line table in the
1482 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1483 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1484 assert(TheCU && "Unable to find compile unit!");
1485 if (Asm->OutStreamer.hasRawTextSupport())
1486 // Use a single line table if we are generating assembly.
1487 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1489 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1491 // Check the current section against the standard text section. If different
1492 // keep track so that we will know when we're emitting functions into multiple
1494 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1495 UsedNonDefaultText = true;
1497 // Emit a label for the function so that we have a beginning address.
1498 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1499 // Assumes in correct section after the entry point.
1500 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1502 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1503 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1504 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1506 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1508 bool AtBlockEntry = true;
1509 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1511 const MachineInstr *MI = II;
1513 if (MI->isDebugValue()) {
1514 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1516 // Keep track of user variables.
1518 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1520 // Variable is in a register, we need to check for clobbers.
1521 if (isDbgValueInDefinedReg(MI))
1522 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1524 // Check the history of this variable.
1525 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1526 if (History.empty()) {
1527 UserVariables.push_back(Var);
1528 // The first mention of a function argument gets the FunctionBeginSym
1529 // label, so arguments are visible when breaking at function entry.
1531 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1532 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1533 LabelsBeforeInsn[MI] = FunctionBeginSym;
1535 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1536 const MachineInstr *Prev = History.back();
1537 if (Prev->isDebugValue()) {
1538 // Coalesce identical entries at the end of History.
1539 if (History.size() >= 2 &&
1540 Prev->isIdenticalTo(History[History.size() - 2])) {
1541 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1542 << "\t" << *Prev << "\t"
1543 << *History[History.size() - 2] << "\n");
1547 // Terminate old register assignments that don't reach MI;
1548 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1549 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1550 isDbgValueInDefinedReg(Prev)) {
1551 // Previous register assignment needs to terminate at the end of
1553 MachineBasicBlock::const_iterator LastMI =
1554 PrevMBB->getLastNonDebugInstr();
1555 if (LastMI == PrevMBB->end()) {
1556 // Drop DBG_VALUE for empty range.
1557 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1558 << "\t" << *Prev << "\n");
1560 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1561 // Terminate after LastMI.
1562 History.push_back(LastMI);
1566 History.push_back(MI);
1568 // Not a DBG_VALUE instruction.
1569 if (!MI->isPosition())
1570 AtBlockEntry = false;
1572 // First known non-DBG_VALUE and non-frame setup location marks
1573 // the beginning of the function body.
1574 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1575 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1576 PrologEndLoc = MI->getDebugLoc();
1578 // Check if the instruction clobbers any registers with debug vars.
1579 for (const MachineOperand &MO : MI->operands()) {
1580 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1582 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1585 const MDNode *Var = LiveUserVar[Reg];
1588 // Reg is now clobbered.
1589 LiveUserVar[Reg] = 0;
1591 // Was MD last defined by a DBG_VALUE referring to Reg?
1592 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1593 if (HistI == DbgValues.end())
1595 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1596 if (History.empty())
1598 const MachineInstr *Prev = History.back();
1599 // Sanity-check: Register assignments are terminated at the end of
1601 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1603 // Is the variable still in Reg?
1604 if (!isDbgValueInDefinedReg(Prev) ||
1605 Prev->getOperand(0).getReg() != Reg)
1607 // Var is clobbered. Make sure the next instruction gets a label.
1608 History.push_back(MI);
1615 for (auto &I : DbgValues) {
1616 SmallVectorImpl<const MachineInstr *> &History = I.second;
1617 if (History.empty())
1620 // Make sure the final register assignments are terminated.
1621 const MachineInstr *Prev = History.back();
1622 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1623 const MachineBasicBlock *PrevMBB = Prev->getParent();
1624 MachineBasicBlock::const_iterator LastMI =
1625 PrevMBB->getLastNonDebugInstr();
1626 if (LastMI == PrevMBB->end())
1627 // Drop DBG_VALUE for empty range.
1629 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1630 // Terminate after LastMI.
1631 History.push_back(LastMI);
1634 // Request labels for the full history.
1635 for (const MachineInstr *MI : History) {
1636 if (MI->isDebugValue())
1637 requestLabelBeforeInsn(MI);
1639 requestLabelAfterInsn(MI);
1643 PrevInstLoc = DebugLoc();
1644 PrevLabel = FunctionBeginSym;
1646 // Record beginning of function.
1647 if (!PrologEndLoc.isUnknown()) {
1648 DebugLoc FnStartDL =
1649 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1651 FnStartDL.getLine(), FnStartDL.getCol(),
1652 FnStartDL.getScope(MF->getFunction()->getContext()),
1653 // We'd like to list the prologue as "not statements" but GDB behaves
1654 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1655 DWARF2_FLAG_IS_STMT);
1659 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1660 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1661 DIVariable DV = Var->getVariable();
1662 // Variables with positive arg numbers are parameters.
1663 if (unsigned ArgNum = DV.getArgNumber()) {
1664 // Keep all parameters in order at the start of the variable list to ensure
1665 // function types are correct (no out-of-order parameters)
1667 // This could be improved by only doing it for optimized builds (unoptimized
1668 // builds have the right order to begin with), searching from the back (this
1669 // would catch the unoptimized case quickly), or doing a binary search
1670 // rather than linear search.
1671 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1672 while (I != Vars.end()) {
1673 unsigned CurNum = (*I)->getVariable().getArgNumber();
1674 // A local (non-parameter) variable has been found, insert immediately
1678 // A later indexed parameter has been found, insert immediately before it.
1679 if (CurNum > ArgNum)
1683 Vars.insert(I, Var);
1687 Vars.push_back(Var);
1690 // Gather and emit post-function debug information.
1691 void DwarfDebug::endFunction(const MachineFunction *MF) {
1692 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1693 // though the beginFunction may not be called at all.
1694 // We should handle both cases.
1698 assert(CurFn == MF);
1701 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1706 // Define end label for subprogram.
1707 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1708 // Assumes in correct section after the entry point.
1709 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1711 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1712 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1714 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1715 collectVariableInfo(ProcessedVars);
1717 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1718 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1719 assert(TheCU && "Unable to find compile unit!");
1721 // Construct abstract scopes.
1722 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1723 DISubprogram SP(AScope->getScopeNode());
1724 if (SP.isSubprogram()) {
1725 // Collect info for variables that were optimized out.
1726 DIArray Variables = SP.getVariables();
1727 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1728 DIVariable DV(Variables.getElement(i));
1729 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1731 // Check that DbgVariable for DV wasn't created earlier, when
1732 // findAbstractVariable() was called for inlined instance of DV.
1733 LLVMContext &Ctx = DV->getContext();
1734 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1735 if (AbstractVariables.lookup(CleanDV))
1737 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1738 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1741 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1742 constructScopeDIE(TheCU, AScope);
1745 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1746 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1747 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1749 // Add the range of this function to the list of ranges for the CU.
1750 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1751 TheCU->addRange(std::move(Span));
1754 for (auto &I : ScopeVariables)
1755 DeleteContainerPointers(I.second);
1756 ScopeVariables.clear();
1757 DeleteContainerPointers(CurrentFnArguments);
1758 UserVariables.clear();
1760 AbstractVariables.clear();
1761 LabelsBeforeInsn.clear();
1762 LabelsAfterInsn.clear();
1767 // Register a source line with debug info. Returns the unique label that was
1768 // emitted and which provides correspondence to the source line list.
1769 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1774 unsigned Discriminator = 0;
1776 DIDescriptor Scope(S);
1778 if (Scope.isCompileUnit()) {
1779 DICompileUnit CU(S);
1780 Fn = CU.getFilename();
1781 Dir = CU.getDirectory();
1782 } else if (Scope.isFile()) {
1784 Fn = F.getFilename();
1785 Dir = F.getDirectory();
1786 } else if (Scope.isSubprogram()) {
1788 Fn = SP.getFilename();
1789 Dir = SP.getDirectory();
1790 } else if (Scope.isLexicalBlockFile()) {
1791 DILexicalBlockFile DBF(S);
1792 Fn = DBF.getFilename();
1793 Dir = DBF.getDirectory();
1794 } else if (Scope.isLexicalBlock()) {
1795 DILexicalBlock DB(S);
1796 Fn = DB.getFilename();
1797 Dir = DB.getDirectory();
1798 Discriminator = DB.getDiscriminator();
1800 llvm_unreachable("Unexpected scope info");
1802 Src = getOrCreateSourceID(
1803 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1805 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1809 //===----------------------------------------------------------------------===//
1811 //===----------------------------------------------------------------------===//
1813 // Compute the size and offset of a DIE. The offset is relative to start of the
1814 // CU. It returns the offset after laying out the DIE.
1815 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1816 // Record the abbreviation.
1817 assignAbbrevNumber(Die->getAbbrev());
1819 // Get the abbreviation for this DIE.
1820 const DIEAbbrev &Abbrev = Die->getAbbrev();
1823 Die->setOffset(Offset);
1825 // Start the size with the size of abbreviation code.
1826 Offset += getULEB128Size(Die->getAbbrevNumber());
1828 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1829 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1831 // Size the DIE attribute values.
1832 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1833 // Size attribute value.
1834 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1836 // Get the children.
1837 const std::vector<DIE *> &Children = Die->getChildren();
1839 // Size the DIE children if any.
1840 if (!Children.empty()) {
1841 assert(Abbrev.hasChildren() && "Children flag not set");
1843 for (DIE *Child : Children)
1844 Offset = computeSizeAndOffset(Child, Offset);
1846 // End of children marker.
1847 Offset += sizeof(int8_t);
1850 Die->setSize(Offset - Die->getOffset());
1854 // Compute the size and offset for each DIE.
1855 void DwarfFile::computeSizeAndOffsets() {
1856 // Offset from the first CU in the debug info section is 0 initially.
1857 unsigned SecOffset = 0;
1859 // Iterate over each compile unit and set the size and offsets for each
1860 // DIE within each compile unit. All offsets are CU relative.
1861 for (DwarfUnit *TheU : CUs) {
1862 TheU->setDebugInfoOffset(SecOffset);
1864 // CU-relative offset is reset to 0 here.
1865 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1866 TheU->getHeaderSize(); // Unit-specific headers
1868 // EndOffset here is CU-relative, after laying out
1869 // all of the CU DIE.
1870 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1871 SecOffset += EndOffset;
1875 // Emit initial Dwarf sections with a label at the start of each one.
1876 void DwarfDebug::emitSectionLabels() {
1877 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1879 // Dwarf sections base addresses.
1880 DwarfInfoSectionSym =
1881 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1882 if (useSplitDwarf())
1883 DwarfInfoDWOSectionSym =
1884 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1885 DwarfAbbrevSectionSym =
1886 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1887 if (useSplitDwarf())
1888 DwarfAbbrevDWOSectionSym = emitSectionSym(
1889 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1890 if (GenerateARangeSection)
1891 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1893 DwarfLineSectionSym =
1894 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1895 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1896 if (GenerateGnuPubSections) {
1897 DwarfGnuPubNamesSectionSym =
1898 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1899 DwarfGnuPubTypesSectionSym =
1900 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1901 } else if (HasDwarfPubSections) {
1902 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1903 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1906 DwarfStrSectionSym =
1907 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1908 if (useSplitDwarf()) {
1909 DwarfStrDWOSectionSym =
1910 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1911 DwarfAddrSectionSym =
1912 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1914 DwarfDebugRangeSectionSym =
1915 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1917 DwarfDebugLocSectionSym =
1918 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1921 // Recursively emits a debug information entry.
1922 void DwarfDebug::emitDIE(DIE *Die) {
1923 // Get the abbreviation for this DIE.
1924 const DIEAbbrev &Abbrev = Die->getAbbrev();
1926 // Emit the code (index) for the abbreviation.
1927 if (Asm->isVerbose())
1928 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1929 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1930 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1931 dwarf::TagString(Abbrev.getTag()));
1932 Asm->EmitULEB128(Abbrev.getNumber());
1934 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1935 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1937 // Emit the DIE attribute values.
1938 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1939 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1940 dwarf::Form Form = AbbrevData[i].getForm();
1941 assert(Form && "Too many attributes for DIE (check abbreviation)");
1943 if (Asm->isVerbose()) {
1944 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1945 if (Attr == dwarf::DW_AT_accessibility)
1946 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1947 cast<DIEInteger>(Values[i])->getValue()));
1950 // Emit an attribute using the defined form.
1951 Values[i]->EmitValue(Asm, Form);
1954 // Emit the DIE children if any.
1955 if (Abbrev.hasChildren()) {
1956 const std::vector<DIE *> &Children = Die->getChildren();
1958 for (DIE *Child : Children)
1961 Asm->OutStreamer.AddComment("End Of Children Mark");
1966 // Emit the various dwarf units to the unit section USection with
1967 // the abbreviations going into ASection.
1968 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1969 const MCSymbol *ASectionSym) {
1970 for (DwarfUnit *TheU : CUs) {
1971 DIE *Die = TheU->getUnitDie();
1972 const MCSection *USection = TheU->getSection();
1973 Asm->OutStreamer.SwitchSection(USection);
1975 // Emit the compile units header.
1976 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1978 // Emit size of content not including length itself
1979 Asm->OutStreamer.AddComment("Length of Unit");
1980 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1982 TheU->emitHeader(ASection, ASectionSym);
1985 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1989 // Emit the debug info section.
1990 void DwarfDebug::emitDebugInfo() {
1991 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1993 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1994 DwarfAbbrevSectionSym);
1997 // Emit the abbreviation section.
1998 void DwarfDebug::emitAbbreviations() {
1999 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2001 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2004 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2005 // Check to see if it is worth the effort.
2006 if (!Abbreviations.empty()) {
2007 // Start the debug abbrev section.
2008 Asm->OutStreamer.SwitchSection(Section);
2010 // For each abbrevation.
2011 for (const DIEAbbrev *Abbrev : Abbreviations) {
2012 // Emit the abbrevations code (base 1 index.)
2013 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2015 // Emit the abbreviations data.
2019 // Mark end of abbreviations.
2020 Asm->EmitULEB128(0, "EOM(3)");
2024 // Emit the last address of the section and the end of the line matrix.
2025 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2026 // Define last address of section.
2027 Asm->OutStreamer.AddComment("Extended Op");
2030 Asm->OutStreamer.AddComment("Op size");
2031 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2032 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2033 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2035 Asm->OutStreamer.AddComment("Section end label");
2037 Asm->OutStreamer.EmitSymbolValue(
2038 Asm->GetTempSymbol("section_end", SectionEnd),
2039 Asm->getDataLayout().getPointerSize());
2041 // Mark end of matrix.
2042 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2048 // Emit visible names into a hashed accelerator table section.
2049 void DwarfDebug::emitAccelNames() {
2051 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2052 for (DwarfUnit *TheU : getUnits()) {
2053 for (const auto &GI : TheU->getAccelNames()) {
2054 StringRef Name = GI.getKey();
2055 for (const DIE *D : GI.second)
2056 AT.AddName(Name, D);
2060 AT.FinalizeTable(Asm, "Names");
2061 Asm->OutStreamer.SwitchSection(
2062 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2063 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2064 Asm->OutStreamer.EmitLabel(SectionBegin);
2066 // Emit the full data.
2067 AT.Emit(Asm, SectionBegin, &InfoHolder);
2070 // Emit objective C classes and categories into a hashed accelerator table
2072 void DwarfDebug::emitAccelObjC() {
2074 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2075 for (DwarfUnit *TheU : getUnits()) {
2076 for (const auto &GI : TheU->getAccelObjC()) {
2077 StringRef Name = GI.getKey();
2078 for (const DIE *D : GI.second)
2079 AT.AddName(Name, D);
2083 AT.FinalizeTable(Asm, "ObjC");
2084 Asm->OutStreamer.SwitchSection(
2085 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2086 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2087 Asm->OutStreamer.EmitLabel(SectionBegin);
2089 // Emit the full data.
2090 AT.Emit(Asm, SectionBegin, &InfoHolder);
2093 // Emit namespace dies into a hashed accelerator table.
2094 void DwarfDebug::emitAccelNamespaces() {
2096 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2097 for (DwarfUnit *TheU : getUnits()) {
2098 for (const auto &GI : TheU->getAccelNamespace()) {
2099 StringRef Name = GI.getKey();
2100 for (const DIE *D : GI.second)
2101 AT.AddName(Name, D);
2105 AT.FinalizeTable(Asm, "namespac");
2106 Asm->OutStreamer.SwitchSection(
2107 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2108 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2109 Asm->OutStreamer.EmitLabel(SectionBegin);
2111 // Emit the full data.
2112 AT.Emit(Asm, SectionBegin, &InfoHolder);
2115 // Emit type dies into a hashed accelerator table.
2116 void DwarfDebug::emitAccelTypes() {
2117 std::vector<DwarfAccelTable::Atom> Atoms;
2119 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2121 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2123 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2124 DwarfAccelTable AT(Atoms);
2125 for (DwarfUnit *TheU : getUnits()) {
2126 for (const auto &GI : TheU->getAccelTypes()) {
2127 StringRef Name = GI.getKey();
2128 for (const auto &DI : GI.second)
2129 AT.AddName(Name, DI.first, DI.second);
2133 AT.FinalizeTable(Asm, "types");
2134 Asm->OutStreamer.SwitchSection(
2135 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2136 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2137 Asm->OutStreamer.EmitLabel(SectionBegin);
2139 // Emit the full data.
2140 AT.Emit(Asm, SectionBegin, &InfoHolder);
2143 // Public name handling.
2144 // The format for the various pubnames:
2146 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2147 // for the DIE that is named.
2149 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2150 // into the CU and the index value is computed according to the type of value
2151 // for the DIE that is named.
2153 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2154 // it's the offset within the debug_info/debug_types dwo section, however, the
2155 // reference in the pubname header doesn't change.
2157 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2158 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2160 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2162 // We could have a specification DIE that has our most of our knowledge,
2163 // look for that now.
2164 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2166 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2167 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2168 Linkage = dwarf::GIEL_EXTERNAL;
2169 } else if (Die->findAttribute(dwarf::DW_AT_external))
2170 Linkage = dwarf::GIEL_EXTERNAL;
2172 switch (Die->getTag()) {
2173 case dwarf::DW_TAG_class_type:
2174 case dwarf::DW_TAG_structure_type:
2175 case dwarf::DW_TAG_union_type:
2176 case dwarf::DW_TAG_enumeration_type:
2177 return dwarf::PubIndexEntryDescriptor(
2178 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2179 ? dwarf::GIEL_STATIC
2180 : dwarf::GIEL_EXTERNAL);
2181 case dwarf::DW_TAG_typedef:
2182 case dwarf::DW_TAG_base_type:
2183 case dwarf::DW_TAG_subrange_type:
2184 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2185 case dwarf::DW_TAG_namespace:
2186 return dwarf::GIEK_TYPE;
2187 case dwarf::DW_TAG_subprogram:
2188 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2189 case dwarf::DW_TAG_constant:
2190 case dwarf::DW_TAG_variable:
2191 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2192 case dwarf::DW_TAG_enumerator:
2193 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2194 dwarf::GIEL_STATIC);
2196 return dwarf::GIEK_NONE;
2200 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2202 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2203 const MCSection *PSec =
2204 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2205 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2207 for (const auto &NU : CUMap) {
2208 DwarfCompileUnit *TheU = NU.second;
2209 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2211 unsigned ID = TheU->getUniqueID();
2213 // Start the dwarf pubnames section.
2214 Asm->OutStreamer.SwitchSection(PSec);
2216 // Emit a label so we can reference the beginning of this pubname section.
2218 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2221 Asm->OutStreamer.AddComment("Length of Public Names Info");
2222 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2223 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2224 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2226 Asm->OutStreamer.EmitLabel(BeginLabel);
2228 Asm->OutStreamer.AddComment("DWARF Version");
2229 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2231 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2232 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2234 Asm->OutStreamer.AddComment("Compilation Unit Length");
2235 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2237 // Emit the pubnames for this compilation unit.
2238 for (const auto &GI : getUnits()[ID]->getGlobalNames()) {
2239 const char *Name = GI.getKeyData();
2240 const DIE *Entity = GI.second;
2242 Asm->OutStreamer.AddComment("DIE offset");
2243 Asm->EmitInt32(Entity->getOffset());
2246 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2247 Asm->OutStreamer.AddComment(
2248 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2249 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2250 Asm->EmitInt8(Desc.toBits());
2253 Asm->OutStreamer.AddComment("External Name");
2254 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2257 Asm->OutStreamer.AddComment("End Mark");
2259 Asm->OutStreamer.EmitLabel(EndLabel);
2263 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2264 const MCSection *PSec =
2265 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2266 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2268 for (const auto &NU : CUMap) {
2269 DwarfCompileUnit *TheU = NU.second;
2270 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2272 unsigned ID = TheU->getUniqueID();
2274 // Start the dwarf pubtypes section.
2275 Asm->OutStreamer.SwitchSection(PSec);
2277 // Emit a label so we can reference the beginning of this pubtype section.
2279 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2282 Asm->OutStreamer.AddComment("Length of Public Types Info");
2283 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2284 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2285 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2287 Asm->OutStreamer.EmitLabel(BeginLabel);
2289 Asm->OutStreamer.AddComment("DWARF Version");
2290 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2292 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2293 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2295 Asm->OutStreamer.AddComment("Compilation Unit Length");
2296 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2298 // Emit the pubtypes.
2299 for (const auto &GI : getUnits()[ID]->getGlobalTypes()) {
2300 const char *Name = GI.getKeyData();
2301 const DIE *Entity = GI.second;
2303 Asm->OutStreamer.AddComment("DIE offset");
2304 Asm->EmitInt32(Entity->getOffset());
2307 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2308 Asm->OutStreamer.AddComment(
2309 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2310 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2311 Asm->EmitInt8(Desc.toBits());
2314 Asm->OutStreamer.AddComment("External Name");
2316 // Emit the name with a terminating null byte.
2317 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2320 Asm->OutStreamer.AddComment("End Mark");
2322 Asm->OutStreamer.EmitLabel(EndLabel);
2326 // Emit strings into a string section.
2327 void DwarfFile::emitStrings(const MCSection *StrSection,
2328 const MCSection *OffsetSection = NULL,
2329 const MCSymbol *StrSecSym = NULL) {
2331 if (StringPool.empty())
2334 // Start the dwarf str section.
2335 Asm->OutStreamer.SwitchSection(StrSection);
2337 // Get all of the string pool entries and put them in an array by their ID so
2338 // we can sort them.
2339 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2341 for (const auto &I : StringPool)
2342 Entries.push_back(std::make_pair(I.second.second, &I));
2344 array_pod_sort(Entries.begin(), Entries.end());
2346 for (const auto &Entry : Entries) {
2347 // Emit a label for reference from debug information entries.
2348 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2350 // Emit the string itself with a terminating null byte.
2351 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2352 Entry.second->getKeyLength() + 1));
2355 // If we've got an offset section go ahead and emit that now as well.
2356 if (OffsetSection) {
2357 Asm->OutStreamer.SwitchSection(OffsetSection);
2358 unsigned offset = 0;
2359 unsigned size = 4; // FIXME: DWARF64 is 8.
2360 for (const auto &Entry : Entries) {
2361 Asm->OutStreamer.EmitIntValue(offset, size);
2362 offset += Entry.second->getKeyLength() + 1;
2367 // Emit addresses into the section given.
2368 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2370 if (AddressPool.empty())
2373 // Start the dwarf addr section.
2374 Asm->OutStreamer.SwitchSection(AddrSection);
2376 // Order the address pool entries by ID
2377 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2379 for (const auto &I : AddressPool)
2380 Entries[I.second.Number] =
2382 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2383 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2385 for (const MCExpr *Entry : Entries)
2386 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2389 // Emit visible names into a debug str section.
2390 void DwarfDebug::emitDebugStr() {
2391 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2392 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2395 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2396 const DotDebugLocEntry &Entry) {
2397 DIVariable DV(Entry.getVariable());
2398 if (Entry.isInt()) {
2399 DIBasicType BTy(DV.getType());
2400 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2401 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2402 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2403 Streamer.EmitSLEB128(Entry.getInt());
2405 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2406 Streamer.EmitULEB128(Entry.getInt());
2408 } else if (Entry.isLocation()) {
2409 MachineLocation Loc = Entry.getLoc();
2410 if (!DV.hasComplexAddress())
2412 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2414 // Complex address entry.
2415 unsigned N = DV.getNumAddrElements();
2417 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2418 if (Loc.getOffset()) {
2420 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2421 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2422 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2423 Streamer.EmitSLEB128(DV.getAddrElement(1));
2425 // If first address element is OpPlus then emit
2426 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2427 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2428 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2432 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2435 // Emit remaining complex address elements.
2436 for (; i < N; ++i) {
2437 uint64_t Element = DV.getAddrElement(i);
2438 if (Element == DIBuilder::OpPlus) {
2439 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2440 Streamer.EmitULEB128(DV.getAddrElement(++i));
2441 } else if (Element == DIBuilder::OpDeref) {
2443 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2445 llvm_unreachable("unknown Opcode found in complex address");
2449 // else ... ignore constant fp. There is not any good way to
2450 // to represent them here in dwarf.
2454 // Emit locations into the debug loc section.
2455 void DwarfDebug::emitDebugLoc() {
2456 if (DotDebugLocEntries.empty())
2459 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2460 I = DotDebugLocEntries.begin(),
2461 E = DotDebugLocEntries.end();
2463 DotDebugLocEntry &Entry = *I;
2464 if (I + 1 != DotDebugLocEntries.end())
2468 // Start the dwarf loc section.
2469 Asm->OutStreamer.SwitchSection(
2470 Asm->getObjFileLowering().getDwarfLocSection());
2471 unsigned char Size = Asm->getDataLayout().getPointerSize();
2472 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2474 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2475 I = DotDebugLocEntries.begin(),
2476 E = DotDebugLocEntries.end();
2477 I != E; ++I, ++index) {
2478 const DotDebugLocEntry &Entry = *I;
2479 if (Entry.isMerged())
2482 if (Entry.isEmpty()) {
2483 Asm->OutStreamer.EmitIntValue(0, Size);
2484 Asm->OutStreamer.EmitIntValue(0, Size);
2485 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2487 // Set up the range.
2488 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2489 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2490 Asm->OutStreamer.AddComment("Loc expr size");
2491 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2492 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2493 Asm->EmitLabelDifference(end, begin, 2);
2494 Asm->OutStreamer.EmitLabel(begin);
2496 APByteStreamer Streamer(*Asm);
2497 emitDebugLocEntry(Streamer, Entry);
2499 Asm->OutStreamer.EmitLabel(end);
2505 const MCSymbol *Start, *End;
2508 // Emit a debug aranges section, containing a CU lookup for any
2509 // address we can tie back to a CU.
2510 void DwarfDebug::emitDebugARanges() {
2511 // Start the dwarf aranges section.
2512 Asm->OutStreamer.SwitchSection(
2513 Asm->getObjFileLowering().getDwarfARangesSection());
2515 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2519 // Build a list of sections used.
2520 std::vector<const MCSection *> Sections;
2521 for (const auto &it : SectionMap) {
2522 const MCSection *Section = it.first;
2523 Sections.push_back(Section);
2526 // Sort the sections into order.
2527 // This is only done to ensure consistent output order across different runs.
2528 std::sort(Sections.begin(), Sections.end(), SectionSort);
2530 // Build a set of address spans, sorted by CU.
2531 for (const MCSection *Section : Sections) {
2532 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2533 if (List.size() < 2)
2536 // Sort the symbols by offset within the section.
2537 std::sort(List.begin(), List.end(),
2538 [&](const SymbolCU &A, const SymbolCU &B) {
2539 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2540 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2542 // Symbols with no order assigned should be placed at the end.
2543 // (e.g. section end labels)
2551 // If we have no section (e.g. common), just write out
2552 // individual spans for each symbol.
2553 if (Section == NULL) {
2554 for (const SymbolCU &Cur : List) {
2556 Span.Start = Cur.Sym;
2559 Spans[Cur.CU].push_back(Span);
2562 // Build spans between each label.
2563 const MCSymbol *StartSym = List[0].Sym;
2564 for (size_t n = 1, e = List.size(); n < e; n++) {
2565 const SymbolCU &Prev = List[n - 1];
2566 const SymbolCU &Cur = List[n];
2568 // Try and build the longest span we can within the same CU.
2569 if (Cur.CU != Prev.CU) {
2571 Span.Start = StartSym;
2573 Spans[Prev.CU].push_back(Span);
2580 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2582 // Build a list of CUs used.
2583 std::vector<DwarfCompileUnit *> CUs;
2584 for (const auto &it : Spans) {
2585 DwarfCompileUnit *CU = it.first;
2589 // Sort the CU list (again, to ensure consistent output order).
2590 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2591 return A->getUniqueID() < B->getUniqueID();
2594 // Emit an arange table for each CU we used.
2595 for (DwarfCompileUnit *CU : CUs) {
2596 std::vector<ArangeSpan> &List = Spans[CU];
2598 // Emit size of content not including length itself.
2599 unsigned ContentSize =
2600 sizeof(int16_t) + // DWARF ARange version number
2601 sizeof(int32_t) + // Offset of CU in the .debug_info section
2602 sizeof(int8_t) + // Pointer Size (in bytes)
2603 sizeof(int8_t); // Segment Size (in bytes)
2605 unsigned TupleSize = PtrSize * 2;
2607 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2609 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2611 ContentSize += Padding;
2612 ContentSize += (List.size() + 1) * TupleSize;
2614 // For each compile unit, write the list of spans it covers.
2615 Asm->OutStreamer.AddComment("Length of ARange Set");
2616 Asm->EmitInt32(ContentSize);
2617 Asm->OutStreamer.AddComment("DWARF Arange version number");
2618 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2619 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2620 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2621 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2622 Asm->EmitInt8(PtrSize);
2623 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2626 Asm->OutStreamer.EmitFill(Padding, 0xff);
2628 for (const ArangeSpan &Span : List) {
2629 Asm->EmitLabelReference(Span.Start, PtrSize);
2631 // Calculate the size as being from the span start to it's end.
2633 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2635 // For symbols without an end marker (e.g. common), we
2636 // write a single arange entry containing just that one symbol.
2637 uint64_t Size = SymSize[Span.Start];
2641 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2645 Asm->OutStreamer.AddComment("ARange terminator");
2646 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2647 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2651 // Emit visible names into a debug ranges section.
2652 void DwarfDebug::emitDebugRanges() {
2653 // Start the dwarf ranges section.
2654 Asm->OutStreamer.SwitchSection(
2655 Asm->getObjFileLowering().getDwarfRangesSection());
2657 // Size for our labels.
2658 unsigned char Size = Asm->getDataLayout().getPointerSize();
2660 // Grab the specific ranges for the compile units in the module.
2661 for (const auto &I : CUMap) {
2662 DwarfCompileUnit *TheCU = I.second;
2664 // Emit a symbol so we can find the beginning of our ranges.
2665 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2667 // Iterate over the misc ranges for the compile units in the module.
2668 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2669 // Emit our symbol so we can find the beginning of the range.
2670 Asm->OutStreamer.EmitLabel(List.getSym());
2672 for (const RangeSpan &Range : List.getRanges()) {
2673 const MCSymbol *Begin = Range.getStart();
2674 const MCSymbol *End = Range.getEnd();
2675 assert(Begin && "Range without a begin symbol?");
2676 assert(End && "Range without an end symbol?");
2677 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2678 Asm->OutStreamer.EmitSymbolValue(End, Size);
2681 // And terminate the list with two 0 values.
2682 Asm->OutStreamer.EmitIntValue(0, Size);
2683 Asm->OutStreamer.EmitIntValue(0, Size);
2686 // Now emit a range for the CU itself.
2687 if (useCURanges() && TheCU->getRanges().size()) {
2688 Asm->OutStreamer.EmitLabel(
2689 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2690 for (const RangeSpan &Range : TheCU->getRanges()) {
2691 const MCSymbol *Begin = Range.getStart();
2692 const MCSymbol *End = Range.getEnd();
2693 assert(Begin && "Range without a begin symbol?");
2694 assert(End && "Range without an end symbol?");
2695 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2696 Asm->OutStreamer.EmitSymbolValue(End, Size);
2698 // And terminate the list with two 0 values.
2699 Asm->OutStreamer.EmitIntValue(0, Size);
2700 Asm->OutStreamer.EmitIntValue(0, Size);
2705 // DWARF5 Experimental Separate Dwarf emitters.
2707 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2709 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2710 U->getCUNode().getSplitDebugFilename());
2712 // Relocate to the beginning of the addr_base section, else 0 for the
2713 // beginning of the one for this compile unit.
2714 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2715 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2717 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2719 if (!CompilationDir.empty())
2720 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2722 addGnuPubAttributes(NewU, Die);
2724 SkeletonHolder.addUnit(NewU);
2727 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2728 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2729 // DW_AT_ranges_base, DW_AT_addr_base.
2730 // TODO: Implement DW_AT_ranges_base.
2731 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2733 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2734 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2735 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2736 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2737 DwarfInfoSectionSym);
2739 NewCU->initStmtList(DwarfLineSectionSym);
2741 initSkeletonUnit(CU, Die, NewCU);
2746 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2748 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2749 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2750 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2752 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2753 DwarfTypeUnit *NewTU =
2754 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2755 NewTU->setTypeSignature(TU->getTypeSignature());
2756 NewTU->setType(NULL);
2758 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2759 CU.applyStmtList(*Die);
2761 initSkeletonUnit(TU, Die, NewTU);
2765 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2766 // compile units that would normally be in debug_info.
2767 void DwarfDebug::emitDebugInfoDWO() {
2768 assert(useSplitDwarf() && "No split dwarf debug info?");
2769 InfoHolder.emitUnits(this,
2770 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2771 DwarfAbbrevDWOSectionSym);
2774 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2775 // abbreviations for the .debug_info.dwo section.
2776 void DwarfDebug::emitDebugAbbrevDWO() {
2777 assert(useSplitDwarf() && "No split dwarf?");
2778 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2781 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2782 // string section and is identical in format to traditional .debug_str
2784 void DwarfDebug::emitDebugStrDWO() {
2785 assert(useSplitDwarf() && "No split dwarf?");
2786 const MCSection *OffSec =
2787 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2788 const MCSymbol *StrSym = DwarfStrSectionSym;
2789 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2793 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2794 StringRef Identifier, DIE *RefDie,
2795 DICompositeType CTy) {
2796 // Flag the type unit reference as a declaration so that if it contains
2797 // members (implicit special members, static data member definitions, member
2798 // declarations for definitions in this CU, etc) consumers don't get confused
2799 // and think this is a full definition.
2800 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2802 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2804 CU.addDIETypeSignature(RefDie, *TU);
2808 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2809 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2810 UnitDie, CU, Asm, this, &InfoHolder);
2812 InfoHolder.addUnit(NewTU);
2814 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2818 Hash.update(Identifier);
2819 // ... take the least significant 8 bytes and return those. Our MD5
2820 // implementation always returns its results in little endian, swap bytes
2822 MD5::MD5Result Result;
2824 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2825 NewTU->setTypeSignature(Signature);
2826 if (useSplitDwarf())
2827 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2829 CU.applyStmtList(*UnitDie);
2831 NewTU->setType(NewTU->createTypeDIE(CTy));
2835 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2836 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2838 CU.addDIETypeSignature(RefDie, *NewTU);
2841 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2842 MCSymbol *Begin, MCSymbol *End) {
2843 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2844 if (DwarfVersion < 4)
2845 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2847 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);