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 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
505 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
510 // This scope represents inlined body of a function. Construct DIE to
511 // represent this concrete inlined copy of the function.
512 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
513 LexicalScope *Scope) {
514 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
515 assert(!ScopeRanges.empty() &&
516 "LexicalScope does not have instruction markers!");
518 if (!Scope->getScopeNode())
520 DIScope DS(Scope->getScopeNode());
521 DISubprogram InlinedSP = getDISubprogram(DS);
522 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
524 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
528 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
529 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
531 // If we have multiple ranges, emit them into the range section.
532 if (ScopeRanges.size() > 1)
533 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
535 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
536 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
537 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
539 if (StartLabel == 0 || EndLabel == 0)
540 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
542 assert(StartLabel->isDefined() &&
543 "Invalid starting label for an inlined scope!");
544 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
546 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
549 InlinedSubprogramDIEs.insert(OriginDIE);
551 // Add the call site information to the DIE.
552 DILocation DL(Scope->getInlinedAt());
553 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
554 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
555 TheCU->getUniqueID()));
556 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
558 // Add name to the name table, we do this here because we're guaranteed
559 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
560 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
565 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
567 SmallVectorImpl<DIE *> &Children) {
568 DIE *ObjectPointer = NULL;
570 // Collect arguments for current function.
571 if (LScopes.isCurrentFunctionScope(Scope)) {
572 for (DbgVariable *ArgDV : CurrentFnArguments)
575 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
576 Children.push_back(Arg);
577 if (ArgDV->isObjectPointer())
581 // If this is a variadic function, add an unspecified parameter.
582 DISubprogram SP(Scope->getScopeNode());
583 DIArray FnArgs = SP.getType().getTypeArray();
584 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
585 .isUnspecifiedParameter()) {
586 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
587 Children.push_back(Ellipsis);
591 // Collect lexical scope children first.
592 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
593 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
594 Scope->isAbstractScope())) {
595 Children.push_back(Variable);
596 if (DV->isObjectPointer())
597 ObjectPointer = Variable;
599 for (LexicalScope *LS : Scope->getChildren())
600 if (DIE *Nested = constructScopeDIE(TheCU, LS))
601 Children.push_back(Nested);
602 return ObjectPointer;
605 // Construct a DIE for this scope.
606 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
607 LexicalScope *Scope) {
608 if (!Scope || !Scope->getScopeNode())
611 DIScope DS(Scope->getScopeNode());
613 SmallVector<DIE *, 8> Children;
614 DIE *ObjectPointer = NULL;
615 bool ChildrenCreated = false;
617 // We try to create the scope DIE first, then the children DIEs. This will
618 // avoid creating un-used children then removing them later when we find out
619 // the scope DIE is null.
620 DIE *ScopeDIE = NULL;
621 if (Scope->getInlinedAt())
622 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
623 else if (DS.isSubprogram()) {
624 ProcessedSPNodes.insert(DS);
625 if (Scope->isAbstractScope()) {
626 ScopeDIE = TheCU->getDIE(DS);
627 // Note down abstract DIE.
629 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
631 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
633 // Early exit when we know the scope DIE is going to be null.
634 if (isLexicalScopeDIENull(Scope))
637 // We create children here when we know the scope DIE is not going to be
638 // null and the children will be added to the scope DIE.
639 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
640 ChildrenCreated = true;
642 // There is no need to emit empty lexical block DIE.
643 std::pair<ImportedEntityMap::const_iterator,
644 ImportedEntityMap::const_iterator> Range =
646 ScopesWithImportedEntities.begin(),
647 ScopesWithImportedEntities.end(),
648 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
650 if (Children.empty() && Range.first == Range.second)
652 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
653 assert(ScopeDIE && "Scope DIE should not be null.");
654 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
656 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
660 assert(Children.empty() &&
661 "We create children only when the scope DIE is not null.");
664 if (!ChildrenCreated)
665 // We create children when the scope DIE is not null.
666 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
669 for (DIE *I : Children)
670 ScopeDIE->addChild(I);
672 if (DS.isSubprogram() && ObjectPointer != NULL)
673 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
678 // Look up the source id with the given directory and source file names.
679 // If none currently exists, create a new id and insert it in the
680 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
682 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
684 // If we print assembly, we can't separate .file entries according to
685 // compile units. Thus all files will belong to the default compile unit.
687 // FIXME: add a better feature test than hasRawTextSupport. Even better,
688 // extend .file to support this.
689 if (Asm->OutStreamer.hasRawTextSupport())
692 // If FE did not provide a file name, then assume stdin.
693 if (FileName.empty())
694 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
696 // TODO: this might not belong here. See if we can factor this better.
697 if (DirName == CompilationDir)
700 // FileIDCUMap stores the current ID for the given compile unit.
701 unsigned SrcId = FileIDCUMap[CUID] + 1;
703 // We look up the CUID/file/dir by concatenating them with a zero byte.
704 SmallString<128> NamePair;
705 NamePair += utostr(CUID);
708 NamePair += '\0'; // Zero bytes are not allowed in paths.
709 NamePair += FileName;
711 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
712 if (Ent.getValue() != SrcId)
713 return Ent.getValue();
715 FileIDCUMap[CUID] = SrcId;
716 // Print out a .file directive to specify files for .loc directives.
717 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
722 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
723 if (!GenerateGnuPubSections)
726 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
729 // Create new DwarfCompileUnit for the given metadata node with tag
730 // DW_TAG_compile_unit.
731 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
732 StringRef FN = DIUnit.getFilename();
733 CompilationDir = DIUnit.getDirectory();
735 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
736 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
737 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
738 InfoHolder.addUnit(NewCU);
740 FileIDCUMap[NewCU->getUniqueID()] = 0;
742 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
743 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
744 DIUnit.getLanguage());
745 NewCU->addString(Die, dwarf::DW_AT_name, FN);
747 if (!useSplitDwarf()) {
748 NewCU->initStmtList(DwarfLineSectionSym);
750 // If we're using split dwarf the compilation dir is going to be in the
751 // skeleton CU and so we don't need to duplicate it here.
752 if (!CompilationDir.empty())
753 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
755 addGnuPubAttributes(NewCU, Die);
758 if (DIUnit.isOptimized())
759 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
761 StringRef Flags = DIUnit.getFlags();
763 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
765 if (unsigned RVer = DIUnit.getRunTimeVersion())
766 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
767 dwarf::DW_FORM_data1, RVer);
772 if (useSplitDwarf()) {
773 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
774 DwarfInfoDWOSectionSym);
775 NewCU->setSkeleton(constructSkeletonCU(NewCU));
777 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
778 DwarfInfoSectionSym);
780 CUMap.insert(std::make_pair(DIUnit, NewCU));
781 CUDieMap.insert(std::make_pair(Die, NewCU));
785 // Construct subprogram DIE.
786 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
788 // FIXME: We should only call this routine once, however, during LTO if a
789 // program is defined in multiple CUs we could end up calling it out of
790 // beginModule as we walk the CUs.
792 DwarfCompileUnit *&CURef = SPMap[N];
798 if (!SP.isDefinition())
799 // This is a method declaration which will be handled while constructing
803 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
805 // Expose as a global name.
806 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
809 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
811 DIImportedEntity Module(N);
812 assert(Module.Verify());
813 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
814 constructImportedEntityDIE(TheCU, Module, D);
817 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
818 const MDNode *N, DIE *Context) {
819 DIImportedEntity Module(N);
820 assert(Module.Verify());
821 return constructImportedEntityDIE(TheCU, Module, Context);
824 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
825 const DIImportedEntity &Module,
827 assert(Module.Verify() &&
828 "Use one of the MDNode * overloads to handle invalid metadata");
829 assert(Context && "Should always have a context for an imported_module");
830 DIE *IMDie = new DIE(Module.getTag());
831 TheCU->insertDIE(Module, IMDie);
833 DIDescriptor Entity = Module.getEntity();
834 if (Entity.isNameSpace())
835 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
836 else if (Entity.isSubprogram())
837 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
838 else if (Entity.isType())
839 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
841 EntityDie = TheCU->getDIE(Entity);
842 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
843 Module.getContext().getDirectory(),
844 TheCU->getUniqueID());
845 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
846 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
847 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
848 StringRef Name = Module.getName();
850 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
851 Context->addChild(IMDie);
854 // Emit all Dwarf sections that should come prior to the content. Create
855 // global DIEs and emit initial debug info sections. This is invoked by
856 // the target AsmPrinter.
857 void DwarfDebug::beginModule() {
858 if (DisableDebugInfoPrinting)
861 const Module *M = MMI->getModule();
863 // If module has named metadata anchors then use them, otherwise scan the
864 // module using debug info finder to collect debug info.
865 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
868 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
870 // Emit initial sections so we can reference labels later.
873 for (MDNode *N : CU_Nodes->operands()) {
874 DICompileUnit CUNode(N);
875 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
876 DIArray ImportedEntities = CUNode.getImportedEntities();
877 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
878 ScopesWithImportedEntities.push_back(std::make_pair(
879 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
880 ImportedEntities.getElement(i)));
881 std::sort(ScopesWithImportedEntities.begin(),
882 ScopesWithImportedEntities.end(), less_first());
883 DIArray GVs = CUNode.getGlobalVariables();
884 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
885 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
886 DIArray SPs = CUNode.getSubprograms();
887 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
888 constructSubprogramDIE(CU, SPs.getElement(i));
889 DIArray EnumTypes = CUNode.getEnumTypes();
890 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
891 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
892 DIArray RetainedTypes = CUNode.getRetainedTypes();
893 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
894 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
895 // Emit imported_modules last so that the relevant context is already
897 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
898 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
901 // Tell MMI that we have debug info.
902 MMI->setDebugInfoAvailability(true);
904 // Prime section data.
905 SectionMap[Asm->getObjFileLowering().getTextSection()];
908 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
909 void DwarfDebug::computeInlinedDIEs() {
910 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
911 for (DIE *ISP : InlinedSubprogramDIEs)
912 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
914 for (const auto &AI : AbstractSPDies) {
915 DIE *ISP = AI.second;
916 if (InlinedSubprogramDIEs.count(ISP))
918 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
922 // Collect info for variables that were optimized out.
923 void DwarfDebug::collectDeadVariables() {
924 const Module *M = MMI->getModule();
926 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
927 for (MDNode *N : CU_Nodes->operands()) {
928 DICompileUnit TheCU(N);
929 DIArray Subprograms = TheCU.getSubprograms();
930 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
931 DISubprogram SP(Subprograms.getElement(i));
932 if (ProcessedSPNodes.count(SP) != 0)
934 if (!SP.isSubprogram())
936 if (!SP.isDefinition())
938 DIArray Variables = SP.getVariables();
939 if (Variables.getNumElements() == 0)
942 // Construct subprogram DIE and add variables DIEs.
943 DwarfCompileUnit *SPCU =
944 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
945 assert(SPCU && "Unable to find Compile Unit!");
946 // FIXME: See the comment in constructSubprogramDIE about duplicate
948 constructSubprogramDIE(SPCU, SP);
949 DIE *SPDIE = SPCU->getDIE(SP);
950 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
951 DIVariable DV(Variables.getElement(vi));
952 if (!DV.isVariable())
954 DbgVariable NewVar(DV, NULL, this);
955 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
956 SPDIE->addChild(VariableDIE);
963 void DwarfDebug::finalizeModuleInfo() {
964 // Collect info for variables that were optimized out.
965 collectDeadVariables();
967 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
968 computeInlinedDIEs();
970 // Handle anything that needs to be done on a per-unit basis after
971 // all other generation.
972 for (DwarfUnit *TheU : getUnits()) {
973 // Emit DW_AT_containing_type attribute to connect types with their
974 // vtable holding type.
975 TheU->constructContainingTypeDIEs();
977 // Add CU specific attributes if we need to add any.
978 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
979 // If we're splitting the dwarf out now that we've got the entire
980 // CU then add the dwo id to it.
981 DwarfCompileUnit *SkCU =
982 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
983 if (useSplitDwarf()) {
984 // This should be a unique identifier when we want to build .dwp files.
986 if (GenerateCUHash) {
988 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
990 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
991 dwarf::DW_FORM_data8, ID);
992 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
993 dwarf::DW_FORM_data8, ID);
996 // If we have code split among multiple sections or we've requested
997 // it then emit a DW_AT_ranges attribute on the unit that will remain
998 // in the .o file, otherwise add a DW_AT_low_pc.
999 // FIXME: Also add a high pc if we can.
1000 // FIXME: We should use ranges if we have multiple compile units or
1001 // allow reordering of code ala .subsections_via_symbols in mach-o.
1002 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1003 if (useCURanges() && TheU->getRanges().size()) {
1004 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1005 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1006 DwarfDebugRangeSectionSym);
1008 // A DW_AT_low_pc attribute may also be specified in combination with
1009 // DW_AT_ranges to specify the default base address for use in location
1010 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1011 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1014 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1019 // Compute DIE offsets and sizes.
1020 InfoHolder.computeSizeAndOffsets();
1021 if (useSplitDwarf())
1022 SkeletonHolder.computeSizeAndOffsets();
1025 void DwarfDebug::endSections() {
1026 // Filter labels by section.
1027 for (const SymbolCU &SCU : ArangeLabels) {
1028 if (SCU.Sym->isInSection()) {
1029 // Make a note of this symbol and it's section.
1030 const MCSection *Section = &SCU.Sym->getSection();
1031 if (!Section->getKind().isMetadata())
1032 SectionMap[Section].push_back(SCU);
1034 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1035 // appear in the output. This sucks as we rely on sections to build
1036 // arange spans. We can do it without, but it's icky.
1037 SectionMap[NULL].push_back(SCU);
1041 // Build a list of sections used.
1042 std::vector<const MCSection *> Sections;
1043 for (const auto &it : SectionMap) {
1044 const MCSection *Section = it.first;
1045 Sections.push_back(Section);
1048 // Sort the sections into order.
1049 // This is only done to ensure consistent output order across different runs.
1050 std::sort(Sections.begin(), Sections.end(), SectionSort);
1052 // Add terminating symbols for each section.
1053 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1054 const MCSection *Section = Sections[ID];
1055 MCSymbol *Sym = NULL;
1058 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1059 // if we know the section name up-front. For user-created sections, the
1060 // resulting label may not be valid to use as a label. (section names can
1061 // use a greater set of characters on some systems)
1062 Sym = Asm->GetTempSymbol("debug_end", ID);
1063 Asm->OutStreamer.SwitchSection(Section);
1064 Asm->OutStreamer.EmitLabel(Sym);
1067 // Insert a final terminator.
1068 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1071 // For now only turn on CU ranges if we've explicitly asked for it,
1072 // we have -ffunction-sections enabled, we've emitted a function
1073 // into a unique section, or we're using LTO. If we're using LTO then
1074 // we can't know that any particular function in the module is correlated
1075 // to a particular CU and so we need to be conservative. At this point all
1076 // sections should be finalized except for dwarf sections.
1077 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1078 TargetMachine::getFunctionSections();
1081 // Emit all Dwarf sections that should come after the content.
1082 void DwarfDebug::endModule() {
1089 // End any existing sections.
1090 // TODO: Does this need to happen?
1093 // Finalize the debug info for the module.
1094 finalizeModuleInfo();
1098 // Emit all the DIEs into a debug info section.
1101 // Corresponding abbreviations into a abbrev section.
1102 emitAbbreviations();
1104 // Emit info into a debug loc section.
1107 // Emit info into a debug aranges section.
1108 if (GenerateARangeSection)
1111 // Emit info into a debug ranges section.
1114 if (useSplitDwarf()) {
1117 emitDebugAbbrevDWO();
1118 // Emit DWO addresses.
1119 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1122 // Emit info into the dwarf accelerator table sections.
1123 if (useDwarfAccelTables()) {
1126 emitAccelNamespaces();
1130 // Emit the pubnames and pubtypes sections if requested.
1131 if (HasDwarfPubSections) {
1132 emitDebugPubNames(GenerateGnuPubSections);
1133 emitDebugPubTypes(GenerateGnuPubSections);
1139 // Reset these for the next Module if we have one.
1143 // Find abstract variable, if any, associated with Var.
1144 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1145 DebugLoc ScopeLoc) {
1146 LLVMContext &Ctx = DV->getContext();
1147 // More then one inlined variable corresponds to one abstract variable.
1148 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1149 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1151 return AbsDbgVariable;
1153 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1157 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1158 addScopeVariable(Scope, AbsDbgVariable);
1159 AbstractVariables[Var] = AbsDbgVariable;
1160 return AbsDbgVariable;
1163 // If Var is a current function argument then add it to CurrentFnArguments list.
1164 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1165 if (!LScopes.isCurrentFunctionScope(Scope))
1167 DIVariable DV = Var->getVariable();
1168 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1170 unsigned ArgNo = DV.getArgNumber();
1174 size_t Size = CurrentFnArguments.size();
1176 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1177 // llvm::Function argument size is not good indicator of how many
1178 // arguments does the function have at source level.
1180 CurrentFnArguments.resize(ArgNo * 2);
1181 CurrentFnArguments[ArgNo - 1] = Var;
1185 // Collect variable information from side table maintained by MMI.
1186 void DwarfDebug::collectVariableInfoFromMMITable(
1187 SmallPtrSet<const MDNode *, 16> &Processed) {
1188 for (const auto &VI : MMI->getVariableDbgInfo()) {
1189 const MDNode *Var = VI.first;
1192 Processed.insert(Var);
1194 const std::pair<unsigned, DebugLoc> &VP = VI.second;
1196 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1198 // If variable scope is not found then skip this variable.
1202 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1203 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1204 RegVar->setFrameIndex(VP.first);
1205 if (!addCurrentFnArgument(RegVar, Scope))
1206 addScopeVariable(Scope, RegVar);
1208 AbsDbgVariable->setFrameIndex(VP.first);
1212 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1214 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1215 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1216 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1217 MI->getOperand(0).getReg() &&
1218 (MI->getOperand(1).isImm() ||
1219 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1222 // Get .debug_loc entry for the instruction range starting at MI.
1223 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1224 const MCSymbol *FLabel,
1225 const MCSymbol *SLabel,
1226 const MachineInstr *MI) {
1227 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1229 assert(MI->getNumOperands() == 3);
1230 if (MI->getOperand(0).isReg()) {
1231 MachineLocation MLoc;
1232 // If the second operand is an immediate, this is a
1233 // register-indirect address.
1234 if (!MI->getOperand(1).isImm())
1235 MLoc.set(MI->getOperand(0).getReg());
1237 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1238 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1240 if (MI->getOperand(0).isImm())
1241 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1242 if (MI->getOperand(0).isFPImm())
1243 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1244 if (MI->getOperand(0).isCImm())
1245 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1247 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1250 // Find variables for each lexical scope.
1252 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1254 // Grab the variable info that was squirreled away in the MMI side-table.
1255 collectVariableInfoFromMMITable(Processed);
1257 for (const MDNode *Var : UserVariables) {
1258 if (Processed.count(Var))
1261 // History contains relevant DBG_VALUE instructions for Var and instructions
1263 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1264 if (History.empty())
1266 const MachineInstr *MInsn = History.front();
1269 LexicalScope *Scope = NULL;
1270 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1271 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1272 Scope = LScopes.getCurrentFunctionScope();
1273 else if (MDNode *IA = DV.getInlinedAt())
1274 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1276 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1277 // If variable scope is not found then skip this variable.
1281 Processed.insert(DV);
1282 assert(MInsn->isDebugValue() && "History must begin with debug value");
1283 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1284 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1285 if (!addCurrentFnArgument(RegVar, Scope))
1286 addScopeVariable(Scope, RegVar);
1288 AbsVar->setMInsn(MInsn);
1290 // Simplify ranges that are fully coalesced.
1291 if (History.size() <= 1 ||
1292 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1293 RegVar->setMInsn(MInsn);
1297 // Handle multiple DBG_VALUE instructions describing one variable.
1298 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1300 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1301 HI = History.begin(),
1304 const MachineInstr *Begin = *HI;
1305 assert(Begin->isDebugValue() && "Invalid History entry");
1307 // Check if DBG_VALUE is truncating a range.
1308 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1309 !Begin->getOperand(0).getReg())
1312 // Compute the range for a register location.
1313 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1314 const MCSymbol *SLabel = 0;
1317 // If Begin is the last instruction in History then its value is valid
1318 // until the end of the function.
1319 SLabel = FunctionEndSym;
1321 const MachineInstr *End = HI[1];
1322 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1323 << "\t" << *Begin << "\t" << *End << "\n");
1324 if (End->isDebugValue())
1325 SLabel = getLabelBeforeInsn(End);
1327 // End is a normal instruction clobbering the range.
1328 SLabel = getLabelAfterInsn(End);
1329 assert(SLabel && "Forgot label after clobber instruction");
1334 // The value is valid until the next DBG_VALUE or clobber.
1335 DotDebugLocEntries.push_back(
1336 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1338 DotDebugLocEntries.push_back(DotDebugLocEntry());
1341 // Collect info for variables that were optimized out.
1342 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1343 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1344 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1345 DIVariable DV(Variables.getElement(i));
1346 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1348 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1349 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1353 // Return Label preceding the instruction.
1354 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1355 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1356 assert(Label && "Didn't insert label before instruction");
1360 // Return Label immediately following the instruction.
1361 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1362 return LabelsAfterInsn.lookup(MI);
1365 // Process beginning of an instruction.
1366 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1369 // Check if source location changes, but ignore DBG_VALUE locations.
1370 if (!MI->isDebugValue()) {
1371 DebugLoc DL = MI->getDebugLoc();
1372 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1375 if (DL == PrologEndLoc) {
1376 Flags |= DWARF2_FLAG_PROLOGUE_END;
1377 PrologEndLoc = DebugLoc();
1379 if (PrologEndLoc.isUnknown())
1380 Flags |= DWARF2_FLAG_IS_STMT;
1382 if (!DL.isUnknown()) {
1383 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1384 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1386 recordSourceLine(0, 0, 0, 0);
1390 // Insert labels where requested.
1391 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1392 LabelsBeforeInsn.find(MI);
1395 if (I == LabelsBeforeInsn.end())
1398 // Label already assigned.
1403 PrevLabel = MMI->getContext().CreateTempSymbol();
1404 Asm->OutStreamer.EmitLabel(PrevLabel);
1406 I->second = PrevLabel;
1409 // Process end of an instruction.
1410 void DwarfDebug::endInstruction() {
1412 // Don't create a new label after DBG_VALUE instructions.
1413 // They don't generate code.
1414 if (!CurMI->isDebugValue())
1417 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1418 LabelsAfterInsn.find(CurMI);
1422 if (I == LabelsAfterInsn.end())
1425 // Label already assigned.
1429 // We need a label after this instruction.
1431 PrevLabel = MMI->getContext().CreateTempSymbol();
1432 Asm->OutStreamer.EmitLabel(PrevLabel);
1434 I->second = PrevLabel;
1437 // Each LexicalScope has first instruction and last instruction to mark
1438 // beginning and end of a scope respectively. Create an inverse map that list
1439 // scopes starts (and ends) with an instruction. One instruction may start (or
1440 // end) multiple scopes. Ignore scopes that are not reachable.
1441 void DwarfDebug::identifyScopeMarkers() {
1442 SmallVector<LexicalScope *, 4> WorkList;
1443 WorkList.push_back(LScopes.getCurrentFunctionScope());
1444 while (!WorkList.empty()) {
1445 LexicalScope *S = WorkList.pop_back_val();
1447 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1448 if (!Children.empty())
1449 WorkList.append(Children.begin(), Children.end());
1451 if (S->isAbstractScope())
1454 for (const InsnRange &R : S->getRanges()) {
1455 assert(R.first && "InsnRange does not have first instruction!");
1456 assert(R.second && "InsnRange does not have second instruction!");
1457 requestLabelBeforeInsn(R.first);
1458 requestLabelAfterInsn(R.second);
1463 // Gather pre-function debug information. Assumes being called immediately
1464 // after the function entry point has been emitted.
1465 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1468 // If there's no debug info for the function we're not going to do anything.
1469 if (!MMI->hasDebugInfo())
1472 // Grab the lexical scopes for the function, if we don't have any of those
1473 // then we're not going to be able to do anything.
1474 LScopes.initialize(*MF);
1475 if (LScopes.empty())
1478 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1480 // Make sure that each lexical scope will have a begin/end label.
1481 identifyScopeMarkers();
1483 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1484 // belongs to so that we add to the correct per-cu line table in the
1486 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1487 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1488 assert(TheCU && "Unable to find compile unit!");
1489 if (Asm->OutStreamer.hasRawTextSupport())
1490 // Use a single line table if we are generating assembly.
1491 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1493 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1495 // Check the current section against the standard text section. If different
1496 // keep track so that we will know when we're emitting functions into multiple
1498 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1499 UsedNonDefaultText = true;
1501 // Emit a label for the function so that we have a beginning address.
1502 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1503 // Assumes in correct section after the entry point.
1504 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1506 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1507 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1508 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1510 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1512 bool AtBlockEntry = true;
1513 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1515 const MachineInstr *MI = II;
1517 if (MI->isDebugValue()) {
1518 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1520 // Keep track of user variables.
1522 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1524 // Variable is in a register, we need to check for clobbers.
1525 if (isDbgValueInDefinedReg(MI))
1526 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1528 // Check the history of this variable.
1529 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1530 if (History.empty()) {
1531 UserVariables.push_back(Var);
1532 // The first mention of a function argument gets the FunctionBeginSym
1533 // label, so arguments are visible when breaking at function entry.
1535 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1536 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1537 LabelsBeforeInsn[MI] = FunctionBeginSym;
1539 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1540 const MachineInstr *Prev = History.back();
1541 if (Prev->isDebugValue()) {
1542 // Coalesce identical entries at the end of History.
1543 if (History.size() >= 2 &&
1544 Prev->isIdenticalTo(History[History.size() - 2])) {
1545 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1546 << "\t" << *Prev << "\t"
1547 << *History[History.size() - 2] << "\n");
1551 // Terminate old register assignments that don't reach MI;
1552 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1553 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1554 isDbgValueInDefinedReg(Prev)) {
1555 // Previous register assignment needs to terminate at the end of
1557 MachineBasicBlock::const_iterator LastMI =
1558 PrevMBB->getLastNonDebugInstr();
1559 if (LastMI == PrevMBB->end()) {
1560 // Drop DBG_VALUE for empty range.
1561 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1562 << "\t" << *Prev << "\n");
1564 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1565 // Terminate after LastMI.
1566 History.push_back(LastMI);
1570 History.push_back(MI);
1572 // Not a DBG_VALUE instruction.
1573 if (!MI->isPosition())
1574 AtBlockEntry = false;
1576 // First known non-DBG_VALUE and non-frame setup location marks
1577 // the beginning of the function body.
1578 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1579 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1580 PrologEndLoc = MI->getDebugLoc();
1582 // Check if the instruction clobbers any registers with debug vars.
1583 for (const MachineOperand &MO : MI->operands()) {
1584 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1586 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1589 const MDNode *Var = LiveUserVar[Reg];
1592 // Reg is now clobbered.
1593 LiveUserVar[Reg] = 0;
1595 // Was MD last defined by a DBG_VALUE referring to Reg?
1596 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1597 if (HistI == DbgValues.end())
1599 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1600 if (History.empty())
1602 const MachineInstr *Prev = History.back();
1603 // Sanity-check: Register assignments are terminated at the end of
1605 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1607 // Is the variable still in Reg?
1608 if (!isDbgValueInDefinedReg(Prev) ||
1609 Prev->getOperand(0).getReg() != Reg)
1611 // Var is clobbered. Make sure the next instruction gets a label.
1612 History.push_back(MI);
1619 for (auto &I : DbgValues) {
1620 SmallVectorImpl<const MachineInstr *> &History = I.second;
1621 if (History.empty())
1624 // Make sure the final register assignments are terminated.
1625 const MachineInstr *Prev = History.back();
1626 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1627 const MachineBasicBlock *PrevMBB = Prev->getParent();
1628 MachineBasicBlock::const_iterator LastMI =
1629 PrevMBB->getLastNonDebugInstr();
1630 if (LastMI == PrevMBB->end())
1631 // Drop DBG_VALUE for empty range.
1633 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1634 // Terminate after LastMI.
1635 History.push_back(LastMI);
1638 // Request labels for the full history.
1639 for (const MachineInstr *MI : History) {
1640 if (MI->isDebugValue())
1641 requestLabelBeforeInsn(MI);
1643 requestLabelAfterInsn(MI);
1647 PrevInstLoc = DebugLoc();
1648 PrevLabel = FunctionBeginSym;
1650 // Record beginning of function.
1651 if (!PrologEndLoc.isUnknown()) {
1652 DebugLoc FnStartDL =
1653 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1655 FnStartDL.getLine(), FnStartDL.getCol(),
1656 FnStartDL.getScope(MF->getFunction()->getContext()),
1657 // We'd like to list the prologue as "not statements" but GDB behaves
1658 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1659 DWARF2_FLAG_IS_STMT);
1663 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1664 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1665 DIVariable DV = Var->getVariable();
1666 // Variables with positive arg numbers are parameters.
1667 if (unsigned ArgNum = DV.getArgNumber()) {
1668 // Keep all parameters in order at the start of the variable list to ensure
1669 // function types are correct (no out-of-order parameters)
1671 // This could be improved by only doing it for optimized builds (unoptimized
1672 // builds have the right order to begin with), searching from the back (this
1673 // would catch the unoptimized case quickly), or doing a binary search
1674 // rather than linear search.
1675 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1676 while (I != Vars.end()) {
1677 unsigned CurNum = (*I)->getVariable().getArgNumber();
1678 // A local (non-parameter) variable has been found, insert immediately
1682 // A later indexed parameter has been found, insert immediately before it.
1683 if (CurNum > ArgNum)
1687 Vars.insert(I, Var);
1691 Vars.push_back(Var);
1694 // Gather and emit post-function debug information.
1695 void DwarfDebug::endFunction(const MachineFunction *MF) {
1696 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1697 // though the beginFunction may not be called at all.
1698 // We should handle both cases.
1702 assert(CurFn == MF);
1705 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1710 // Define end label for subprogram.
1711 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1712 // Assumes in correct section after the entry point.
1713 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1715 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1716 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1718 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1719 collectVariableInfo(ProcessedVars);
1721 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1722 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1723 assert(TheCU && "Unable to find compile unit!");
1725 // Construct abstract scopes.
1726 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1727 DISubprogram SP(AScope->getScopeNode());
1728 if (SP.isSubprogram()) {
1729 // Collect info for variables that were optimized out.
1730 DIArray Variables = SP.getVariables();
1731 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1732 DIVariable DV(Variables.getElement(i));
1733 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1735 // Check that DbgVariable for DV wasn't created earlier, when
1736 // findAbstractVariable() was called for inlined instance of DV.
1737 LLVMContext &Ctx = DV->getContext();
1738 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1739 if (AbstractVariables.lookup(CleanDV))
1741 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1742 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1745 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1746 constructScopeDIE(TheCU, AScope);
1749 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1750 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1751 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1753 // Add the range of this function to the list of ranges for the CU.
1754 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1755 TheCU->addRange(std::move(Span));
1758 for (auto &I : ScopeVariables)
1759 DeleteContainerPointers(I.second);
1760 ScopeVariables.clear();
1761 DeleteContainerPointers(CurrentFnArguments);
1762 UserVariables.clear();
1764 AbstractVariables.clear();
1765 LabelsBeforeInsn.clear();
1766 LabelsAfterInsn.clear();
1771 // Register a source line with debug info. Returns the unique label that was
1772 // emitted and which provides correspondence to the source line list.
1773 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1778 unsigned Discriminator = 0;
1780 DIDescriptor Scope(S);
1782 if (Scope.isCompileUnit()) {
1783 DICompileUnit CU(S);
1784 Fn = CU.getFilename();
1785 Dir = CU.getDirectory();
1786 } else if (Scope.isFile()) {
1788 Fn = F.getFilename();
1789 Dir = F.getDirectory();
1790 } else if (Scope.isSubprogram()) {
1792 Fn = SP.getFilename();
1793 Dir = SP.getDirectory();
1794 } else if (Scope.isLexicalBlockFile()) {
1795 DILexicalBlockFile DBF(S);
1796 Fn = DBF.getFilename();
1797 Dir = DBF.getDirectory();
1798 } else if (Scope.isLexicalBlock()) {
1799 DILexicalBlock DB(S);
1800 Fn = DB.getFilename();
1801 Dir = DB.getDirectory();
1802 Discriminator = DB.getDiscriminator();
1804 llvm_unreachable("Unexpected scope info");
1806 Src = getOrCreateSourceID(
1807 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1809 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1813 //===----------------------------------------------------------------------===//
1815 //===----------------------------------------------------------------------===//
1817 // Compute the size and offset of a DIE. The offset is relative to start of the
1818 // CU. It returns the offset after laying out the DIE.
1819 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1820 // Record the abbreviation.
1821 assignAbbrevNumber(Die->getAbbrev());
1823 // Get the abbreviation for this DIE.
1824 const DIEAbbrev &Abbrev = Die->getAbbrev();
1827 Die->setOffset(Offset);
1829 // Start the size with the size of abbreviation code.
1830 Offset += getULEB128Size(Die->getAbbrevNumber());
1832 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1833 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1835 // Size the DIE attribute values.
1836 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1837 // Size attribute value.
1838 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1840 // Get the children.
1841 const std::vector<DIE *> &Children = Die->getChildren();
1843 // Size the DIE children if any.
1844 if (!Children.empty()) {
1845 assert(Abbrev.hasChildren() && "Children flag not set");
1847 for (DIE *Child : Children)
1848 Offset = computeSizeAndOffset(Child, Offset);
1850 // End of children marker.
1851 Offset += sizeof(int8_t);
1854 Die->setSize(Offset - Die->getOffset());
1858 // Compute the size and offset for each DIE.
1859 void DwarfFile::computeSizeAndOffsets() {
1860 // Offset from the first CU in the debug info section is 0 initially.
1861 unsigned SecOffset = 0;
1863 // Iterate over each compile unit and set the size and offsets for each
1864 // DIE within each compile unit. All offsets are CU relative.
1865 for (DwarfUnit *TheU : CUs) {
1866 TheU->setDebugInfoOffset(SecOffset);
1868 // CU-relative offset is reset to 0 here.
1869 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1870 TheU->getHeaderSize(); // Unit-specific headers
1872 // EndOffset here is CU-relative, after laying out
1873 // all of the CU DIE.
1874 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1875 SecOffset += EndOffset;
1879 // Emit initial Dwarf sections with a label at the start of each one.
1880 void DwarfDebug::emitSectionLabels() {
1881 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1883 // Dwarf sections base addresses.
1884 DwarfInfoSectionSym =
1885 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1886 if (useSplitDwarf())
1887 DwarfInfoDWOSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1889 DwarfAbbrevSectionSym =
1890 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1891 if (useSplitDwarf())
1892 DwarfAbbrevDWOSectionSym = emitSectionSym(
1893 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1894 if (GenerateARangeSection)
1895 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1897 DwarfLineSectionSym =
1898 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1899 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1900 if (GenerateGnuPubSections) {
1901 DwarfGnuPubNamesSectionSym =
1902 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1903 DwarfGnuPubTypesSectionSym =
1904 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1905 } else if (HasDwarfPubSections) {
1906 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1907 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1910 DwarfStrSectionSym =
1911 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1912 if (useSplitDwarf()) {
1913 DwarfStrDWOSectionSym =
1914 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1915 DwarfAddrSectionSym =
1916 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1918 DwarfDebugRangeSectionSym =
1919 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1921 DwarfDebugLocSectionSym =
1922 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1925 // Recursively emits a debug information entry.
1926 void DwarfDebug::emitDIE(DIE *Die) {
1927 // Get the abbreviation for this DIE.
1928 const DIEAbbrev &Abbrev = Die->getAbbrev();
1930 // Emit the code (index) for the abbreviation.
1931 if (Asm->isVerbose())
1932 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1933 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1934 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1935 dwarf::TagString(Abbrev.getTag()));
1936 Asm->EmitULEB128(Abbrev.getNumber());
1938 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1939 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1941 // Emit the DIE attribute values.
1942 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1943 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1944 dwarf::Form Form = AbbrevData[i].getForm();
1945 assert(Form && "Too many attributes for DIE (check abbreviation)");
1947 if (Asm->isVerbose()) {
1948 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1949 if (Attr == dwarf::DW_AT_accessibility)
1950 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1951 cast<DIEInteger>(Values[i])->getValue()));
1954 // Emit an attribute using the defined form.
1955 Values[i]->EmitValue(Asm, Form);
1958 // Emit the DIE children if any.
1959 if (Abbrev.hasChildren()) {
1960 const std::vector<DIE *> &Children = Die->getChildren();
1962 for (DIE *Child : Children)
1965 Asm->OutStreamer.AddComment("End Of Children Mark");
1970 // Emit the various dwarf units to the unit section USection with
1971 // the abbreviations going into ASection.
1972 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1973 const MCSymbol *ASectionSym) {
1974 for (DwarfUnit *TheU : CUs) {
1975 DIE *Die = TheU->getUnitDie();
1976 const MCSection *USection = TheU->getSection();
1977 Asm->OutStreamer.SwitchSection(USection);
1979 // Emit the compile units header.
1980 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1982 // Emit size of content not including length itself
1983 Asm->OutStreamer.AddComment("Length of Unit");
1984 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1986 TheU->emitHeader(ASection, ASectionSym);
1989 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1993 // Emit the debug info section.
1994 void DwarfDebug::emitDebugInfo() {
1995 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1997 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1998 DwarfAbbrevSectionSym);
2001 // Emit the abbreviation section.
2002 void DwarfDebug::emitAbbreviations() {
2003 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2005 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2008 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2009 // Check to see if it is worth the effort.
2010 if (!Abbreviations.empty()) {
2011 // Start the debug abbrev section.
2012 Asm->OutStreamer.SwitchSection(Section);
2014 // For each abbrevation.
2015 for (const DIEAbbrev *Abbrev : Abbreviations) {
2016 // Emit the abbrevations code (base 1 index.)
2017 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2019 // Emit the abbreviations data.
2023 // Mark end of abbreviations.
2024 Asm->EmitULEB128(0, "EOM(3)");
2028 // Emit the last address of the section and the end of the line matrix.
2029 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2030 // Define last address of section.
2031 Asm->OutStreamer.AddComment("Extended Op");
2034 Asm->OutStreamer.AddComment("Op size");
2035 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2036 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2037 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2039 Asm->OutStreamer.AddComment("Section end label");
2041 Asm->OutStreamer.EmitSymbolValue(
2042 Asm->GetTempSymbol("section_end", SectionEnd),
2043 Asm->getDataLayout().getPointerSize());
2045 // Mark end of matrix.
2046 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2052 // Emit visible names into a hashed accelerator table section.
2053 void DwarfDebug::emitAccelNames() {
2055 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2056 for (DwarfUnit *TheU : getUnits()) {
2057 for (const auto &GI : TheU->getAccelNames()) {
2058 StringRef Name = GI.getKey();
2059 for (const DIE *D : GI.second)
2060 AT.AddName(Name, D);
2064 AT.FinalizeTable(Asm, "Names");
2065 Asm->OutStreamer.SwitchSection(
2066 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2067 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2068 Asm->OutStreamer.EmitLabel(SectionBegin);
2070 // Emit the full data.
2071 AT.Emit(Asm, SectionBegin, &InfoHolder);
2074 // Emit objective C classes and categories into a hashed accelerator table
2076 void DwarfDebug::emitAccelObjC() {
2078 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2079 for (DwarfUnit *TheU : getUnits()) {
2080 for (const auto &GI : TheU->getAccelObjC()) {
2081 StringRef Name = GI.getKey();
2082 for (const DIE *D : GI.second)
2083 AT.AddName(Name, D);
2087 AT.FinalizeTable(Asm, "ObjC");
2088 Asm->OutStreamer.SwitchSection(
2089 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2090 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2091 Asm->OutStreamer.EmitLabel(SectionBegin);
2093 // Emit the full data.
2094 AT.Emit(Asm, SectionBegin, &InfoHolder);
2097 // Emit namespace dies into a hashed accelerator table.
2098 void DwarfDebug::emitAccelNamespaces() {
2100 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2101 for (DwarfUnit *TheU : getUnits()) {
2102 for (const auto &GI : TheU->getAccelNamespace()) {
2103 StringRef Name = GI.getKey();
2104 for (const DIE *D : GI.second)
2105 AT.AddName(Name, D);
2109 AT.FinalizeTable(Asm, "namespac");
2110 Asm->OutStreamer.SwitchSection(
2111 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2112 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2113 Asm->OutStreamer.EmitLabel(SectionBegin);
2115 // Emit the full data.
2116 AT.Emit(Asm, SectionBegin, &InfoHolder);
2119 // Emit type dies into a hashed accelerator table.
2120 void DwarfDebug::emitAccelTypes() {
2121 std::vector<DwarfAccelTable::Atom> Atoms;
2123 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2125 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2127 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2128 DwarfAccelTable AT(Atoms);
2129 for (DwarfUnit *TheU : getUnits()) {
2130 for (const auto &GI : TheU->getAccelTypes()) {
2131 StringRef Name = GI.getKey();
2132 for (const auto &DI : GI.second)
2133 AT.AddName(Name, DI.first, DI.second);
2137 AT.FinalizeTable(Asm, "types");
2138 Asm->OutStreamer.SwitchSection(
2139 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2140 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2141 Asm->OutStreamer.EmitLabel(SectionBegin);
2143 // Emit the full data.
2144 AT.Emit(Asm, SectionBegin, &InfoHolder);
2147 // Public name handling.
2148 // The format for the various pubnames:
2150 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2151 // for the DIE that is named.
2153 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2154 // into the CU and the index value is computed according to the type of value
2155 // for the DIE that is named.
2157 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2158 // it's the offset within the debug_info/debug_types dwo section, however, the
2159 // reference in the pubname header doesn't change.
2161 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2162 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2164 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2166 // We could have a specification DIE that has our most of our knowledge,
2167 // look for that now.
2168 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2170 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2171 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2172 Linkage = dwarf::GIEL_EXTERNAL;
2173 } else if (Die->findAttribute(dwarf::DW_AT_external))
2174 Linkage = dwarf::GIEL_EXTERNAL;
2176 switch (Die->getTag()) {
2177 case dwarf::DW_TAG_class_type:
2178 case dwarf::DW_TAG_structure_type:
2179 case dwarf::DW_TAG_union_type:
2180 case dwarf::DW_TAG_enumeration_type:
2181 return dwarf::PubIndexEntryDescriptor(
2182 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2183 ? dwarf::GIEL_STATIC
2184 : dwarf::GIEL_EXTERNAL);
2185 case dwarf::DW_TAG_typedef:
2186 case dwarf::DW_TAG_base_type:
2187 case dwarf::DW_TAG_subrange_type:
2188 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2189 case dwarf::DW_TAG_namespace:
2190 return dwarf::GIEK_TYPE;
2191 case dwarf::DW_TAG_subprogram:
2192 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2193 case dwarf::DW_TAG_constant:
2194 case dwarf::DW_TAG_variable:
2195 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2196 case dwarf::DW_TAG_enumerator:
2197 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2198 dwarf::GIEL_STATIC);
2200 return dwarf::GIEK_NONE;
2204 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2206 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2207 const MCSection *PSec =
2208 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2209 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2211 for (const auto &NU : CUMap) {
2212 DwarfCompileUnit *TheU = NU.second;
2213 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2215 unsigned ID = TheU->getUniqueID();
2217 // Start the dwarf pubnames section.
2218 Asm->OutStreamer.SwitchSection(PSec);
2220 // Emit a label so we can reference the beginning of this pubname section.
2222 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2225 Asm->OutStreamer.AddComment("Length of Public Names Info");
2226 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2227 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2228 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2230 Asm->OutStreamer.EmitLabel(BeginLabel);
2232 Asm->OutStreamer.AddComment("DWARF Version");
2233 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2235 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2236 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2238 Asm->OutStreamer.AddComment("Compilation Unit Length");
2239 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2241 // Emit the pubnames for this compilation unit.
2242 for (const auto &GI : getUnits()[ID]->getGlobalNames()) {
2243 const char *Name = GI.getKeyData();
2244 const DIE *Entity = GI.second;
2246 Asm->OutStreamer.AddComment("DIE offset");
2247 Asm->EmitInt32(Entity->getOffset());
2250 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2251 Asm->OutStreamer.AddComment(
2252 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2253 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2254 Asm->EmitInt8(Desc.toBits());
2257 Asm->OutStreamer.AddComment("External Name");
2258 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2261 Asm->OutStreamer.AddComment("End Mark");
2263 Asm->OutStreamer.EmitLabel(EndLabel);
2267 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2268 const MCSection *PSec =
2269 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2270 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2272 for (const auto &NU : CUMap) {
2273 DwarfCompileUnit *TheU = NU.second;
2274 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2276 unsigned ID = TheU->getUniqueID();
2278 // Start the dwarf pubtypes section.
2279 Asm->OutStreamer.SwitchSection(PSec);
2281 // Emit a label so we can reference the beginning of this pubtype section.
2283 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2286 Asm->OutStreamer.AddComment("Length of Public Types Info");
2287 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2288 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2289 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2291 Asm->OutStreamer.EmitLabel(BeginLabel);
2293 Asm->OutStreamer.AddComment("DWARF Version");
2294 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2296 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2297 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2299 Asm->OutStreamer.AddComment("Compilation Unit Length");
2300 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2302 // Emit the pubtypes.
2303 for (const auto &GI : getUnits()[ID]->getGlobalTypes()) {
2304 const char *Name = GI.getKeyData();
2305 const DIE *Entity = GI.second;
2307 Asm->OutStreamer.AddComment("DIE offset");
2308 Asm->EmitInt32(Entity->getOffset());
2311 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2312 Asm->OutStreamer.AddComment(
2313 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2314 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2315 Asm->EmitInt8(Desc.toBits());
2318 Asm->OutStreamer.AddComment("External Name");
2320 // Emit the name with a terminating null byte.
2321 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2324 Asm->OutStreamer.AddComment("End Mark");
2326 Asm->OutStreamer.EmitLabel(EndLabel);
2330 // Emit strings into a string section.
2331 void DwarfFile::emitStrings(const MCSection *StrSection,
2332 const MCSection *OffsetSection = NULL,
2333 const MCSymbol *StrSecSym = NULL) {
2335 if (StringPool.empty())
2338 // Start the dwarf str section.
2339 Asm->OutStreamer.SwitchSection(StrSection);
2341 // Get all of the string pool entries and put them in an array by their ID so
2342 // we can sort them.
2343 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2345 for (const auto &I : StringPool)
2346 Entries.push_back(std::make_pair(I.second.second, &I));
2348 array_pod_sort(Entries.begin(), Entries.end());
2350 for (const auto &Entry : Entries) {
2351 // Emit a label for reference from debug information entries.
2352 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2354 // Emit the string itself with a terminating null byte.
2355 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2356 Entry.second->getKeyLength() + 1));
2359 // If we've got an offset section go ahead and emit that now as well.
2360 if (OffsetSection) {
2361 Asm->OutStreamer.SwitchSection(OffsetSection);
2362 unsigned offset = 0;
2363 unsigned size = 4; // FIXME: DWARF64 is 8.
2364 for (const auto &Entry : Entries) {
2365 Asm->OutStreamer.EmitIntValue(offset, size);
2366 offset += Entry.second->getKeyLength() + 1;
2371 // Emit addresses into the section given.
2372 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2374 if (AddressPool.empty())
2377 // Start the dwarf addr section.
2378 Asm->OutStreamer.SwitchSection(AddrSection);
2380 // Order the address pool entries by ID
2381 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2383 for (const auto &I : AddressPool)
2384 Entries[I.second.Number] =
2386 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2387 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2389 for (const MCExpr *Entry : Entries)
2390 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2393 // Emit visible names into a debug str section.
2394 void DwarfDebug::emitDebugStr() {
2395 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2396 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2399 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2400 const DotDebugLocEntry &Entry) {
2401 DIVariable DV(Entry.getVariable());
2402 if (Entry.isInt()) {
2403 DIBasicType BTy(DV.getType());
2404 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2405 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2406 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2407 Streamer.EmitSLEB128(Entry.getInt());
2409 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2410 Streamer.EmitULEB128(Entry.getInt());
2412 } else if (Entry.isLocation()) {
2413 MachineLocation Loc = Entry.getLoc();
2414 if (!DV.hasComplexAddress())
2416 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2418 // Complex address entry.
2419 unsigned N = DV.getNumAddrElements();
2421 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2422 if (Loc.getOffset()) {
2424 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2425 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2426 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2427 Streamer.EmitSLEB128(DV.getAddrElement(1));
2429 // If first address element is OpPlus then emit
2430 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2431 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2432 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2436 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2439 // Emit remaining complex address elements.
2440 for (; i < N; ++i) {
2441 uint64_t Element = DV.getAddrElement(i);
2442 if (Element == DIBuilder::OpPlus) {
2443 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2444 Streamer.EmitULEB128(DV.getAddrElement(++i));
2445 } else if (Element == DIBuilder::OpDeref) {
2447 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2449 llvm_unreachable("unknown Opcode found in complex address");
2453 // else ... ignore constant fp. There is not any good way to
2454 // to represent them here in dwarf.
2458 // Emit locations into the debug loc section.
2459 void DwarfDebug::emitDebugLoc() {
2460 if (DotDebugLocEntries.empty())
2463 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2464 I = DotDebugLocEntries.begin(),
2465 E = DotDebugLocEntries.end();
2467 DotDebugLocEntry &Entry = *I;
2468 if (I + 1 != DotDebugLocEntries.end())
2472 // Start the dwarf loc section.
2473 Asm->OutStreamer.SwitchSection(
2474 Asm->getObjFileLowering().getDwarfLocSection());
2475 unsigned char Size = Asm->getDataLayout().getPointerSize();
2476 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2478 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2479 I = DotDebugLocEntries.begin(),
2480 E = DotDebugLocEntries.end();
2481 I != E; ++I, ++index) {
2482 const DotDebugLocEntry &Entry = *I;
2483 if (Entry.isMerged())
2486 if (Entry.isEmpty()) {
2487 Asm->OutStreamer.EmitIntValue(0, Size);
2488 Asm->OutStreamer.EmitIntValue(0, Size);
2489 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2491 // Set up the range.
2492 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2493 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2494 Asm->OutStreamer.AddComment("Loc expr size");
2495 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2496 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2497 Asm->EmitLabelDifference(end, begin, 2);
2498 Asm->OutStreamer.EmitLabel(begin);
2500 APByteStreamer Streamer(*Asm);
2501 emitDebugLocEntry(Streamer, Entry);
2503 Asm->OutStreamer.EmitLabel(end);
2509 const MCSymbol *Start, *End;
2512 // Emit a debug aranges section, containing a CU lookup for any
2513 // address we can tie back to a CU.
2514 void DwarfDebug::emitDebugARanges() {
2515 // Start the dwarf aranges section.
2516 Asm->OutStreamer.SwitchSection(
2517 Asm->getObjFileLowering().getDwarfARangesSection());
2519 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2523 // Build a list of sections used.
2524 std::vector<const MCSection *> Sections;
2525 for (const auto &it : SectionMap) {
2526 const MCSection *Section = it.first;
2527 Sections.push_back(Section);
2530 // Sort the sections into order.
2531 // This is only done to ensure consistent output order across different runs.
2532 std::sort(Sections.begin(), Sections.end(), SectionSort);
2534 // Build a set of address spans, sorted by CU.
2535 for (const MCSection *Section : Sections) {
2536 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2537 if (List.size() < 2)
2540 // Sort the symbols by offset within the section.
2541 std::sort(List.begin(), List.end(),
2542 [&](const SymbolCU &A, const SymbolCU &B) {
2543 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2544 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2546 // Symbols with no order assigned should be placed at the end.
2547 // (e.g. section end labels)
2555 // If we have no section (e.g. common), just write out
2556 // individual spans for each symbol.
2557 if (Section == NULL) {
2558 for (const SymbolCU &Cur : List) {
2560 Span.Start = Cur.Sym;
2563 Spans[Cur.CU].push_back(Span);
2566 // Build spans between each label.
2567 const MCSymbol *StartSym = List[0].Sym;
2568 for (size_t n = 1, e = List.size(); n < e; n++) {
2569 const SymbolCU &Prev = List[n - 1];
2570 const SymbolCU &Cur = List[n];
2572 // Try and build the longest span we can within the same CU.
2573 if (Cur.CU != Prev.CU) {
2575 Span.Start = StartSym;
2577 Spans[Prev.CU].push_back(Span);
2584 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2586 // Build a list of CUs used.
2587 std::vector<DwarfCompileUnit *> CUs;
2588 for (const auto &it : Spans) {
2589 DwarfCompileUnit *CU = it.first;
2593 // Sort the CU list (again, to ensure consistent output order).
2594 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2595 return A->getUniqueID() < B->getUniqueID();
2598 // Emit an arange table for each CU we used.
2599 for (DwarfCompileUnit *CU : CUs) {
2600 std::vector<ArangeSpan> &List = Spans[CU];
2602 // Emit size of content not including length itself.
2603 unsigned ContentSize =
2604 sizeof(int16_t) + // DWARF ARange version number
2605 sizeof(int32_t) + // Offset of CU in the .debug_info section
2606 sizeof(int8_t) + // Pointer Size (in bytes)
2607 sizeof(int8_t); // Segment Size (in bytes)
2609 unsigned TupleSize = PtrSize * 2;
2611 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2613 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2615 ContentSize += Padding;
2616 ContentSize += (List.size() + 1) * TupleSize;
2618 // For each compile unit, write the list of spans it covers.
2619 Asm->OutStreamer.AddComment("Length of ARange Set");
2620 Asm->EmitInt32(ContentSize);
2621 Asm->OutStreamer.AddComment("DWARF Arange version number");
2622 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2623 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2624 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2625 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2626 Asm->EmitInt8(PtrSize);
2627 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2630 Asm->OutStreamer.EmitFill(Padding, 0xff);
2632 for (const ArangeSpan &Span : List) {
2633 Asm->EmitLabelReference(Span.Start, PtrSize);
2635 // Calculate the size as being from the span start to it's end.
2637 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2639 // For symbols without an end marker (e.g. common), we
2640 // write a single arange entry containing just that one symbol.
2641 uint64_t Size = SymSize[Span.Start];
2645 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2649 Asm->OutStreamer.AddComment("ARange terminator");
2650 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2651 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2655 // Emit visible names into a debug ranges section.
2656 void DwarfDebug::emitDebugRanges() {
2657 // Start the dwarf ranges section.
2658 Asm->OutStreamer.SwitchSection(
2659 Asm->getObjFileLowering().getDwarfRangesSection());
2661 // Size for our labels.
2662 unsigned char Size = Asm->getDataLayout().getPointerSize();
2664 // Grab the specific ranges for the compile units in the module.
2665 for (const auto &I : CUMap) {
2666 DwarfCompileUnit *TheCU = I.second;
2668 // Emit a symbol so we can find the beginning of our ranges.
2669 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2671 // Iterate over the misc ranges for the compile units in the module.
2672 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2673 // Emit our symbol so we can find the beginning of the range.
2674 Asm->OutStreamer.EmitLabel(List.getSym());
2676 for (const RangeSpan &Range : List.getRanges()) {
2677 const MCSymbol *Begin = Range.getStart();
2678 const MCSymbol *End = Range.getEnd();
2679 assert(Begin && "Range without a begin symbol?");
2680 assert(End && "Range without an end symbol?");
2681 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2682 Asm->OutStreamer.EmitSymbolValue(End, Size);
2685 // And terminate the list with two 0 values.
2686 Asm->OutStreamer.EmitIntValue(0, Size);
2687 Asm->OutStreamer.EmitIntValue(0, Size);
2690 // Now emit a range for the CU itself.
2691 if (useCURanges() && TheCU->getRanges().size()) {
2692 Asm->OutStreamer.EmitLabel(
2693 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2694 for (const RangeSpan &Range : TheCU->getRanges()) {
2695 const MCSymbol *Begin = Range.getStart();
2696 const MCSymbol *End = Range.getEnd();
2697 assert(Begin && "Range without a begin symbol?");
2698 assert(End && "Range without an end symbol?");
2699 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2700 Asm->OutStreamer.EmitSymbolValue(End, Size);
2702 // And terminate the list with two 0 values.
2703 Asm->OutStreamer.EmitIntValue(0, Size);
2704 Asm->OutStreamer.EmitIntValue(0, Size);
2709 // DWARF5 Experimental Separate Dwarf emitters.
2711 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2713 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2714 U->getCUNode().getSplitDebugFilename());
2716 // Relocate to the beginning of the addr_base section, else 0 for the
2717 // beginning of the one for this compile unit.
2718 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2719 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2721 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2723 if (!CompilationDir.empty())
2724 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2726 addGnuPubAttributes(NewU, Die);
2728 SkeletonHolder.addUnit(NewU);
2731 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2732 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2733 // DW_AT_ranges_base, DW_AT_addr_base.
2734 // TODO: Implement DW_AT_ranges_base.
2735 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2737 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2738 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2739 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2740 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2741 DwarfInfoSectionSym);
2743 NewCU->initStmtList(DwarfLineSectionSym);
2745 initSkeletonUnit(CU, Die, NewCU);
2750 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2752 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2753 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2754 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2756 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2757 DwarfTypeUnit *NewTU =
2758 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2759 NewTU->setTypeSignature(TU->getTypeSignature());
2760 NewTU->setType(NULL);
2762 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2763 CU.applyStmtList(*Die);
2765 initSkeletonUnit(TU, Die, NewTU);
2769 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2770 // compile units that would normally be in debug_info.
2771 void DwarfDebug::emitDebugInfoDWO() {
2772 assert(useSplitDwarf() && "No split dwarf debug info?");
2773 InfoHolder.emitUnits(this,
2774 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2775 DwarfAbbrevDWOSectionSym);
2778 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2779 // abbreviations for the .debug_info.dwo section.
2780 void DwarfDebug::emitDebugAbbrevDWO() {
2781 assert(useSplitDwarf() && "No split dwarf?");
2782 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2785 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2786 // string section and is identical in format to traditional .debug_str
2788 void DwarfDebug::emitDebugStrDWO() {
2789 assert(useSplitDwarf() && "No split dwarf?");
2790 const MCSection *OffSec =
2791 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2792 const MCSymbol *StrSym = DwarfStrSectionSym;
2793 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2797 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2798 StringRef Identifier, DIE *RefDie,
2799 DICompositeType CTy) {
2800 // Flag the type unit reference as a declaration so that if it contains
2801 // members (implicit special members, static data member definitions, member
2802 // declarations for definitions in this CU, etc) consumers don't get confused
2803 // and think this is a full definition.
2804 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2806 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2808 CU.addDIETypeSignature(RefDie, *TU);
2812 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2813 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2814 UnitDie, CU, Asm, this, &InfoHolder);
2816 InfoHolder.addUnit(NewTU);
2818 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2822 Hash.update(Identifier);
2823 // ... take the least significant 8 bytes and return those. Our MD5
2824 // implementation always returns its results in little endian, swap bytes
2826 MD5::MD5Result Result;
2828 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2829 NewTU->setTypeSignature(Signature);
2830 if (useSplitDwarf())
2831 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2833 CU.applyStmtList(*UnitDie);
2835 NewTU->setType(NewTU->createTypeDIE(CTy));
2839 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2840 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2842 CU.addDIETypeSignature(RefDie, *NewTU);
2845 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2846 MCSymbol *Begin, MCSymbol *End) {
2847 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2848 if (DwarfVersion < 4)
2849 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2851 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);