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."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
112 /// resolve - Look in the DwarfDebug map for the MDNode that
113 /// corresponds to the reference.
114 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
115 return DD->resolve(Ref);
118 DIType DbgVariable::getType() const {
119 DIType Ty = Var.getType();
120 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
121 // addresses instead.
122 if (Var.isBlockByrefVariable()) {
123 /* Byref variables, in Blocks, are declared by the programmer as
124 "SomeType VarName;", but the compiler creates a
125 __Block_byref_x_VarName struct, and gives the variable VarName
126 either the struct, or a pointer to the struct, as its type. This
127 is necessary for various behind-the-scenes things the compiler
128 needs to do with by-reference variables in blocks.
130 However, as far as the original *programmer* is concerned, the
131 variable should still have type 'SomeType', as originally declared.
133 The following function dives into the __Block_byref_x_VarName
134 struct to find the original type of the variable. This will be
135 passed back to the code generating the type for the Debug
136 Information Entry for the variable 'VarName'. 'VarName' will then
137 have the original type 'SomeType' in its debug information.
139 The original type 'SomeType' will be the type of the field named
140 'VarName' inside the __Block_byref_x_VarName struct.
142 NOTE: In order for this to not completely fail on the debugger
143 side, the Debug Information Entry for the variable VarName needs to
144 have a DW_AT_location that tells the debugger how to unwind through
145 the pointers and __Block_byref_x_VarName struct to find the actual
146 value of the variable. The function addBlockByrefType does this. */
148 uint16_t tag = Ty.getTag();
150 if (tag == dwarf::DW_TAG_pointer_type)
151 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
153 DIArray Elements = DICompositeType(subType).getTypeArray();
154 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
155 DIDerivedType DT(Elements.getElement(i));
156 if (getName() == DT.getName())
157 return (resolve(DT.getTypeDerivedFrom()));
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 Value *Val = M->getModuleFlag("Dwarf Version");
169 return dwarf::DWARF_VERSION;
170 return cast<ConstantInt>(Val)->getZExtValue();
173 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
174 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
175 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
176 UsedNonDefaultText(false),
177 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
179 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
180 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
181 DwarfAddrSectionSym = 0;
182 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
183 FunctionBeginSym = FunctionEndSym = 0;
187 // Turn on accelerator tables for Darwin by default, pubnames by
188 // default for non-Darwin, and handle split dwarf.
189 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
191 if (DwarfAccelTables == Default)
192 HasDwarfAccelTables = IsDarwin;
194 HasDwarfAccelTables = DwarfAccelTables == Enable;
196 if (SplitDwarf == Default)
197 HasSplitDwarf = false;
199 HasSplitDwarf = SplitDwarf == Enable;
201 if (DwarfPubSections == Default)
202 HasDwarfPubSections = !IsDarwin;
204 HasDwarfPubSections = DwarfPubSections == Enable;
206 DwarfVersion = DwarfVersionNumber
208 : getDwarfVersionFromModule(MMI->getModule());
211 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
216 // Switch to the specified MCSection and emit an assembler
217 // temporary label to it if SymbolStem is specified.
218 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
219 const char *SymbolStem = 0) {
220 Asm->OutStreamer.SwitchSection(Section);
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
229 DwarfFile::~DwarfFile() {
230 for (DwarfUnit *DU : CUs)
234 MCSymbol *DwarfFile::getStringPoolSym() {
235 return Asm->GetTempSymbol(StringPref);
238 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
239 std::pair<MCSymbol *, unsigned> &Entry =
240 StringPool.GetOrCreateValue(Str).getValue();
244 Entry.second = NextStringPoolNumber++;
245 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
248 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
259 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
260 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
261 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
263 ++NextAddrPoolNumber;
264 return P.first->second.Number;
267 // Define a unique number for the abbreviation.
269 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
270 // Check the set for priors.
271 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
273 // If it's newly added.
274 if (InSet == &Abbrev) {
275 // Add to abbreviation list.
276 Abbreviations.push_back(&Abbrev);
278 // Assign the vector position + 1 as its number.
279 Abbrev.setNumber(Abbreviations.size());
281 // Assign existing abbreviation number.
282 Abbrev.setNumber(InSet->getNumber());
286 static bool isObjCClass(StringRef Name) {
287 return Name.startswith("+") || Name.startswith("-");
290 static bool hasObjCCategory(StringRef Name) {
291 if (!isObjCClass(Name))
294 return Name.find(") ") != StringRef::npos;
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
314 // Helper for sorting sections into a stable output order.
315 static bool SectionSort(const MCSection *A, const MCSection *B) {
316 std::string LA = (A ? A->getLabelBeginName() : "");
317 std::string LB = (B ? B->getLabelBeginName() : "");
321 // Add the various names to the Dwarf accelerator table names.
322 // TODO: Determine whether or not we should add names for programs
323 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
324 // is only slightly different than the lookup of non-standard ObjC names.
325 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
326 if (!SP.isDefinition())
328 TheU->addAccelName(SP.getName(), Die);
330 // If the linkage name is different than the name, go ahead and output
331 // that as well into the name table.
332 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
333 TheU->addAccelName(SP.getLinkageName(), Die);
335 // If this is an Objective-C selector name add it to the ObjC accelerator
337 if (isObjCClass(SP.getName())) {
338 StringRef Class, Category;
339 getObjCClassCategory(SP.getName(), Class, Category);
340 TheU->addAccelObjC(Class, Die);
342 TheU->addAccelObjC(Category, Die);
343 // Also add the base method name to the name table.
344 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
348 /// isSubprogramContext - Return true if Context is either a subprogram
349 /// or another context nested inside a subprogram.
350 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
353 DIDescriptor D(Context);
354 if (D.isSubprogram())
357 return isSubprogramContext(resolve(DIType(Context).getContext()));
361 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
362 // and DW_AT_high_pc attributes. If there are global variables in this
363 // scope then create and insert DIEs for these variables.
364 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
366 SP = SPCU->getOdrUniqueSubprogram(resolve(SP.getContext()), SP);
367 DIE *SPDie = SPCU->getDIE(SP);
369 assert(SPDie && "Unable to find subprogram DIE!");
371 // If we're updating an abstract DIE, then we will be adding the children and
372 // object pointer later on. But what we don't want to do is process the
373 // concrete DIE twice.
374 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
375 // Pick up abstract subprogram DIE.
377 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
378 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 DIScope SPContext = resolve(SP.getContext());
388 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
389 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
390 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 uint16_t SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 SPCU->constructSubprogramArguments(*SPDie, Args);
398 DIE *SPDeclDie = SPDie;
399 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
400 *SPCU->getUnitDie());
401 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
406 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
408 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
409 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
410 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
412 // Add name to the name table, we do this here because we're guaranteed
413 // to have concrete versions of our DW_TAG_subprogram nodes.
414 addSubprogramNames(SPCU, SP, SPDie);
419 /// Check whether we should create a DIE for the given Scope, return true
420 /// if we don't create a DIE (the corresponding DIE is null).
421 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
422 if (Scope->isAbstractScope())
425 // We don't create a DIE if there is no Range.
426 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
430 if (Ranges.size() > 1)
433 // We don't create a DIE if we have a single Range and the end label
435 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
436 MCSymbol *End = getLabelAfterInsn(RI->second);
440 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
441 dwarf::Attribute A, const MCSymbol *L,
442 const MCSymbol *Sec) {
443 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
444 U->addSectionLabel(D, A, L);
446 U->addSectionDelta(D, A, L, Sec);
449 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
450 const SmallVectorImpl<InsnRange> &Range) {
451 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
452 // emitting it appropriately.
453 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
454 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
455 DwarfDebugRangeSectionSym);
457 RangeSpanList List(RangeSym);
458 for (const InsnRange &R : Range) {
459 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
460 List.addRange(std::move(Span));
463 // Add the range list to the set of ranges to be emitted.
464 TheCU->addRangeList(std::move(List));
467 // Construct new DW_TAG_lexical_block for this scope and attach
468 // DW_AT_low_pc/DW_AT_high_pc labels.
469 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
470 LexicalScope *Scope) {
471 if (isLexicalScopeDIENull(Scope))
474 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
475 if (Scope->isAbstractScope())
478 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
480 // If we have multiple ranges, emit them into the range section.
481 if (ScopeRanges.size() > 1) {
482 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
486 // Construct the address range for this DIE.
487 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
488 MCSymbol *Start = getLabelBeforeInsn(RI->first);
489 MCSymbol *End = getLabelAfterInsn(RI->second);
490 assert(End && "End label should not be null!");
492 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
493 assert(End->isDefined() && "Invalid end label for an inlined scope!");
495 attachLowHighPC(TheCU, ScopeDIE, Start, End);
500 // This scope represents inlined body of a function. Construct DIE to
501 // represent this concrete inlined copy of the function.
502 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
503 LexicalScope *Scope) {
504 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
505 assert(!ScopeRanges.empty() &&
506 "LexicalScope does not have instruction markers!");
508 if (!Scope->getScopeNode())
510 DIScope DS(Scope->getScopeNode());
511 DISubprogram InlinedSP = getDISubprogram(DS);
512 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
514 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
518 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
519 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
521 // If we have multiple ranges, emit them into the range section.
522 if (ScopeRanges.size() > 1)
523 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
525 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
526 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
527 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
529 if (StartLabel == 0 || EndLabel == 0)
530 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
532 assert(StartLabel->isDefined() &&
533 "Invalid starting label for an inlined scope!");
534 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
536 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
539 InlinedSubprogramDIEs.insert(OriginDIE);
541 // Add the call site information to the DIE.
542 DILocation DL(Scope->getInlinedAt());
544 ScopeDIE, dwarf::DW_AT_call_file, None,
545 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
546 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
548 // Add name to the name table, we do this here because we're guaranteed
549 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
550 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
555 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
557 SmallVectorImpl<DIE *> &Children) {
558 DIE *ObjectPointer = NULL;
560 // Collect arguments for current function.
561 if (LScopes.isCurrentFunctionScope(Scope)) {
562 for (DbgVariable *ArgDV : CurrentFnArguments)
565 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
566 Children.push_back(Arg);
567 if (ArgDV->isObjectPointer())
571 // If this is a variadic function, add an unspecified parameter.
572 DISubprogram SP(Scope->getScopeNode());
573 DIArray FnArgs = SP.getType().getTypeArray();
574 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
575 .isUnspecifiedParameter()) {
576 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
577 Children.push_back(Ellipsis);
581 // Collect lexical scope children first.
582 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
583 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
584 Scope->isAbstractScope())) {
585 Children.push_back(Variable);
586 if (DV->isObjectPointer())
587 ObjectPointer = Variable;
589 for (LexicalScope *LS : Scope->getChildren())
590 if (DIE *Nested = constructScopeDIE(TheCU, LS))
591 Children.push_back(Nested);
592 return ObjectPointer;
595 // Construct a DIE for this scope.
596 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
597 LexicalScope *Scope) {
598 if (!Scope || !Scope->getScopeNode())
601 DIScope DS(Scope->getScopeNode());
603 SmallVector<DIE *, 8> Children;
604 DIE *ObjectPointer = NULL;
605 bool ChildrenCreated = false;
607 // We try to create the scope DIE first, then the children DIEs. This will
608 // avoid creating un-used children then removing them later when we find out
609 // the scope DIE is null.
610 DIE *ScopeDIE = NULL;
611 if (Scope->getInlinedAt())
612 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
613 else if (DS.isSubprogram()) {
614 ProcessedSPNodes.insert(DS);
615 if (Scope->isAbstractScope()) {
616 ScopeDIE = TheCU->getDIE(DS);
617 // Note down abstract DIE.
619 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
621 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
623 // Early exit when we know the scope DIE is going to be null.
624 if (isLexicalScopeDIENull(Scope))
627 // We create children here when we know the scope DIE is not going to be
628 // null and the children will be added to the scope DIE.
629 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
630 ChildrenCreated = true;
632 // There is no need to emit empty lexical block DIE.
633 std::pair<ImportedEntityMap::const_iterator,
634 ImportedEntityMap::const_iterator> Range =
636 ScopesWithImportedEntities.begin(),
637 ScopesWithImportedEntities.end(),
638 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
640 if (Children.empty() && Range.first == Range.second)
642 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
643 assert(ScopeDIE && "Scope DIE should not be null.");
644 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
646 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
650 assert(Children.empty() &&
651 "We create children only when the scope DIE is not null.");
654 if (!ChildrenCreated)
655 // We create children when the scope DIE is not null.
656 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
659 for (DIE *I : Children)
660 ScopeDIE->addChild(I);
662 if (DS.isSubprogram() && ObjectPointer != NULL)
663 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
668 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
669 if (!GenerateGnuPubSections)
672 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
675 // Create new DwarfCompileUnit for the given metadata node with tag
676 // DW_TAG_compile_unit.
677 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit,
679 StringRef FN = DIUnit.getFilename();
680 CompilationDir = DIUnit.getDirectory();
682 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
683 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
684 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
685 InfoHolder.addUnit(NewCU);
686 if (!Asm->OutStreamer.hasRawTextSupport() || Singular)
687 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
688 NewCU->getUniqueID(), CompilationDir);
690 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
691 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
692 DIUnit.getLanguage());
693 NewCU->addString(Die, dwarf::DW_AT_name, FN);
695 if (!useSplitDwarf()) {
696 NewCU->initStmtList(DwarfLineSectionSym);
698 // If we're using split dwarf the compilation dir is going to be in the
699 // skeleton CU and so we don't need to duplicate it here.
700 if (!CompilationDir.empty())
701 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
703 addGnuPubAttributes(NewCU, Die);
706 if (DIUnit.isOptimized())
707 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
709 StringRef Flags = DIUnit.getFlags();
711 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
713 if (unsigned RVer = DIUnit.getRunTimeVersion())
714 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
715 dwarf::DW_FORM_data1, RVer);
720 if (useSplitDwarf()) {
721 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
722 DwarfInfoDWOSectionSym);
723 NewCU->setSkeleton(constructSkeletonCU(NewCU));
725 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
726 DwarfInfoSectionSym);
728 CUMap.insert(std::make_pair(DIUnit, NewCU));
729 CUDieMap.insert(std::make_pair(Die, NewCU));
733 // Construct subprogram DIE.
734 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
736 // FIXME: We should only call this routine once, however, during LTO if a
737 // program is defined in multiple CUs we could end up calling it out of
738 // beginModule as we walk the CUs.
740 DwarfCompileUnit *&CURef = SPMap[N];
746 if (!SP.isDefinition())
747 // This is a method declaration which will be handled while constructing
751 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
753 // Expose as a global name.
754 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
757 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
759 DIImportedEntity Module(N);
760 assert(Module.Verify());
761 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
762 constructImportedEntityDIE(TheCU, Module, D);
765 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
766 const MDNode *N, DIE *Context) {
767 DIImportedEntity Module(N);
768 assert(Module.Verify());
769 return constructImportedEntityDIE(TheCU, Module, Context);
772 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
773 const DIImportedEntity &Module,
775 assert(Module.Verify() &&
776 "Use one of the MDNode * overloads to handle invalid metadata");
777 assert(Context && "Should always have a context for an imported_module");
778 DIE *IMDie = new DIE(Module.getTag());
779 TheCU->insertDIE(Module, IMDie);
781 DIDescriptor Entity = Module.getEntity();
782 if (Entity.isNameSpace())
783 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
784 else if (Entity.isSubprogram())
785 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
786 else if (Entity.isType())
787 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
789 EntityDie = TheCU->getDIE(Entity);
790 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
791 Module.getContext().getFilename(),
792 Module.getContext().getDirectory());
793 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
794 StringRef Name = Module.getName();
796 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
797 Context->addChild(IMDie);
800 // Emit all Dwarf sections that should come prior to the content. Create
801 // global DIEs and emit initial debug info sections. This is invoked by
802 // the target AsmPrinter.
803 void DwarfDebug::beginModule() {
804 if (DisableDebugInfoPrinting)
807 const Module *M = MMI->getModule();
809 // If module has named metadata anchors then use them, otherwise scan the
810 // module using debug info finder to collect debug info.
811 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
814 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
816 // Emit initial sections so we can reference labels later.
819 auto Operands = CU_Nodes->operands();
821 bool SingleCU = std::next(Operands.begin()) == Operands.end();
823 for (MDNode *N : Operands) {
824 DICompileUnit CUNode(N);
825 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode, SingleCU);
826 DIArray ImportedEntities = CUNode.getImportedEntities();
827 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
828 ScopesWithImportedEntities.push_back(std::make_pair(
829 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
830 ImportedEntities.getElement(i)));
831 std::sort(ScopesWithImportedEntities.begin(),
832 ScopesWithImportedEntities.end(), less_first());
833 DIArray GVs = CUNode.getGlobalVariables();
834 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
835 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
836 DIArray SPs = CUNode.getSubprograms();
837 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
838 constructSubprogramDIE(CU, SPs.getElement(i));
839 DIArray EnumTypes = CUNode.getEnumTypes();
840 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
841 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
842 DIArray RetainedTypes = CUNode.getRetainedTypes();
843 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
844 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
845 // Emit imported_modules last so that the relevant context is already
847 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
848 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
851 // Tell MMI that we have debug info.
852 MMI->setDebugInfoAvailability(true);
854 // Prime section data.
855 SectionMap[Asm->getObjFileLowering().getTextSection()];
858 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
859 void DwarfDebug::computeInlinedDIEs() {
860 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
861 for (DIE *ISP : InlinedSubprogramDIEs)
862 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
864 for (const auto &AI : AbstractSPDies) {
865 DIE *ISP = AI.second;
866 if (InlinedSubprogramDIEs.count(ISP))
868 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
872 // Collect info for variables that were optimized out.
873 void DwarfDebug::collectDeadVariables() {
874 const Module *M = MMI->getModule();
876 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
877 for (MDNode *N : CU_Nodes->operands()) {
878 DICompileUnit TheCU(N);
879 DIArray Subprograms = TheCU.getSubprograms();
880 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
881 DISubprogram SP(Subprograms.getElement(i));
882 if (ProcessedSPNodes.count(SP) != 0)
884 if (!SP.isSubprogram())
886 if (!SP.isDefinition())
888 DIArray Variables = SP.getVariables();
889 if (Variables.getNumElements() == 0)
892 // Construct subprogram DIE and add variables DIEs.
893 DwarfCompileUnit *SPCU =
894 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
895 assert(SPCU && "Unable to find Compile Unit!");
896 // FIXME: See the comment in constructSubprogramDIE about duplicate
898 constructSubprogramDIE(SPCU, SP);
899 DIE *SPDIE = SPCU->getDIE(SP);
900 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
901 DIVariable DV(Variables.getElement(vi));
902 if (!DV.isVariable())
904 DbgVariable NewVar(DV, NULL, this);
905 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
906 SPDIE->addChild(VariableDIE);
913 void DwarfDebug::finalizeModuleInfo() {
914 // Collect info for variables that were optimized out.
915 collectDeadVariables();
917 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
918 computeInlinedDIEs();
920 // Handle anything that needs to be done on a per-unit basis after
921 // all other generation.
922 for (DwarfUnit *TheU : getUnits()) {
923 // Emit DW_AT_containing_type attribute to connect types with their
924 // vtable holding type.
925 TheU->constructContainingTypeDIEs();
927 // Add CU specific attributes if we need to add any.
928 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
929 // If we're splitting the dwarf out now that we've got the entire
930 // CU then add the dwo id to it.
931 DwarfCompileUnit *SkCU =
932 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
933 if (useSplitDwarf()) {
934 // Emit a unique identifier for this CU.
935 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
936 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
937 dwarf::DW_FORM_data8, ID);
938 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
939 dwarf::DW_FORM_data8, ID);
942 // If we have code split among multiple sections or we've requested
943 // it then emit a DW_AT_ranges attribute on the unit that will remain
944 // in the .o file, otherwise add a DW_AT_low_pc.
945 // FIXME: Also add a high pc if we can.
946 // FIXME: We should use ranges if we have multiple compile units or
947 // allow reordering of code ala .subsections_via_symbols in mach-o.
948 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
949 if (useCURanges() && TheU->getRanges().size()) {
950 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
951 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
952 DwarfDebugRangeSectionSym);
954 // A DW_AT_low_pc attribute may also be specified in combination with
955 // DW_AT_ranges to specify the default base address for use in location
956 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
957 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
960 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
965 // Compute DIE offsets and sizes.
966 InfoHolder.computeSizeAndOffsets();
968 SkeletonHolder.computeSizeAndOffsets();
971 void DwarfDebug::endSections() {
972 // Filter labels by section.
973 for (const SymbolCU &SCU : ArangeLabels) {
974 if (SCU.Sym->isInSection()) {
975 // Make a note of this symbol and it's section.
976 const MCSection *Section = &SCU.Sym->getSection();
977 if (!Section->getKind().isMetadata())
978 SectionMap[Section].push_back(SCU);
980 // Some symbols (e.g. common/bss on mach-o) can have no section but still
981 // appear in the output. This sucks as we rely on sections to build
982 // arange spans. We can do it without, but it's icky.
983 SectionMap[NULL].push_back(SCU);
987 // Build a list of sections used.
988 std::vector<const MCSection *> Sections;
989 for (const auto &it : SectionMap) {
990 const MCSection *Section = it.first;
991 Sections.push_back(Section);
994 // Sort the sections into order.
995 // This is only done to ensure consistent output order across different runs.
996 std::sort(Sections.begin(), Sections.end(), SectionSort);
998 // Add terminating symbols for each section.
999 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1000 const MCSection *Section = Sections[ID];
1001 MCSymbol *Sym = NULL;
1004 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1005 // if we know the section name up-front. For user-created sections, the
1006 // resulting label may not be valid to use as a label. (section names can
1007 // use a greater set of characters on some systems)
1008 Sym = Asm->GetTempSymbol("debug_end", ID);
1009 Asm->OutStreamer.SwitchSection(Section);
1010 Asm->OutStreamer.EmitLabel(Sym);
1013 // Insert a final terminator.
1014 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1017 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1018 // we've emitted a function into a unique section, or we're using LTO. If
1019 // we're using LTO then we can't know that any particular function in the
1020 // module is correlated to a particular CU and so we need to be conservative.
1021 // At this point all sections should be finalized except for dwarf sections.
1022 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1023 TargetMachine::getFunctionSections();
1026 // Emit all Dwarf sections that should come after the content.
1027 void DwarfDebug::endModule() {
1034 // End any existing sections.
1035 // TODO: Does this need to happen?
1038 // Finalize the debug info for the module.
1039 finalizeModuleInfo();
1043 // Emit all the DIEs into a debug info section.
1046 // Corresponding abbreviations into a abbrev section.
1047 emitAbbreviations();
1049 // Emit info into a debug loc section.
1052 // Emit info into a debug aranges section.
1053 if (GenerateARangeSection)
1056 // Emit info into a debug ranges section.
1059 if (useSplitDwarf()) {
1062 emitDebugAbbrevDWO();
1064 // Emit DWO addresses.
1065 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1068 // Emit info into the dwarf accelerator table sections.
1069 if (useDwarfAccelTables()) {
1072 emitAccelNamespaces();
1076 // Emit the pubnames and pubtypes sections if requested.
1077 if (HasDwarfPubSections) {
1078 emitDebugPubNames(GenerateGnuPubSections);
1079 emitDebugPubTypes(GenerateGnuPubSections);
1085 // Reset these for the next Module if we have one.
1089 // Find abstract variable, if any, associated with Var.
1090 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1091 DebugLoc ScopeLoc) {
1092 LLVMContext &Ctx = DV->getContext();
1093 // More then one inlined variable corresponds to one abstract variable.
1094 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1095 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1097 return AbsDbgVariable;
1099 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1103 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1104 addScopeVariable(Scope, AbsDbgVariable);
1105 AbstractVariables[Var] = AbsDbgVariable;
1106 return AbsDbgVariable;
1109 // If Var is a current function argument then add it to CurrentFnArguments list.
1110 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1111 if (!LScopes.isCurrentFunctionScope(Scope))
1113 DIVariable DV = Var->getVariable();
1114 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1116 unsigned ArgNo = DV.getArgNumber();
1120 size_t Size = CurrentFnArguments.size();
1122 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1123 // llvm::Function argument size is not good indicator of how many
1124 // arguments does the function have at source level.
1126 CurrentFnArguments.resize(ArgNo * 2);
1127 CurrentFnArguments[ArgNo - 1] = Var;
1131 // Collect variable information from side table maintained by MMI.
1132 void DwarfDebug::collectVariableInfoFromMMITable(
1133 SmallPtrSet<const MDNode *, 16> &Processed) {
1134 for (const auto &VI : MMI->getVariableDbgInfo()) {
1137 Processed.insert(VI.Var);
1138 DIVariable DV(VI.Var);
1139 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1141 // If variable scope is not found then skip this variable.
1145 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1146 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1147 RegVar->setFrameIndex(VI.Slot);
1148 if (!addCurrentFnArgument(RegVar, Scope))
1149 addScopeVariable(Scope, RegVar);
1151 AbsDbgVariable->setFrameIndex(VI.Slot);
1155 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1157 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1158 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1159 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1160 MI->getOperand(0).getReg() &&
1161 (MI->getOperand(1).isImm() ||
1162 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1165 // Get .debug_loc entry for the instruction range starting at MI.
1166 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1167 const MCSymbol *FLabel,
1168 const MCSymbol *SLabel,
1169 const MachineInstr *MI) {
1170 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1172 assert(MI->getNumOperands() == 3);
1173 if (MI->getOperand(0).isReg()) {
1174 MachineLocation MLoc;
1175 // If the second operand is an immediate, this is a
1176 // register-indirect address.
1177 if (!MI->getOperand(1).isImm())
1178 MLoc.set(MI->getOperand(0).getReg());
1180 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1181 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1183 if (MI->getOperand(0).isImm())
1184 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1185 if (MI->getOperand(0).isFPImm())
1186 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1187 if (MI->getOperand(0).isCImm())
1188 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1190 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1193 // Find variables for each lexical scope.
1195 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1197 // Grab the variable info that was squirreled away in the MMI side-table.
1198 collectVariableInfoFromMMITable(Processed);
1200 for (const MDNode *Var : UserVariables) {
1201 if (Processed.count(Var))
1204 // History contains relevant DBG_VALUE instructions for Var and instructions
1206 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1207 if (History.empty())
1209 const MachineInstr *MInsn = History.front();
1212 LexicalScope *Scope = NULL;
1213 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1214 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1215 Scope = LScopes.getCurrentFunctionScope();
1216 else if (MDNode *IA = DV.getInlinedAt())
1217 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1219 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1220 // If variable scope is not found then skip this variable.
1224 Processed.insert(DV);
1225 assert(MInsn->isDebugValue() && "History must begin with debug value");
1226 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1227 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1228 if (!addCurrentFnArgument(RegVar, Scope))
1229 addScopeVariable(Scope, RegVar);
1231 AbsVar->setMInsn(MInsn);
1233 // Simplify ranges that are fully coalesced.
1234 if (History.size() <= 1 ||
1235 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1236 RegVar->setMInsn(MInsn);
1240 // Handle multiple DBG_VALUE instructions describing one variable.
1241 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1243 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1244 HI = History.begin(),
1247 const MachineInstr *Begin = *HI;
1248 assert(Begin->isDebugValue() && "Invalid History entry");
1250 // Check if DBG_VALUE is truncating a range.
1251 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1252 !Begin->getOperand(0).getReg())
1255 // Compute the range for a register location.
1256 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1257 const MCSymbol *SLabel = 0;
1260 // If Begin is the last instruction in History then its value is valid
1261 // until the end of the function.
1262 SLabel = FunctionEndSym;
1264 const MachineInstr *End = HI[1];
1265 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1266 << "\t" << *Begin << "\t" << *End << "\n");
1267 if (End->isDebugValue())
1268 SLabel = getLabelBeforeInsn(End);
1270 // End is a normal instruction clobbering the range.
1271 SLabel = getLabelAfterInsn(End);
1272 assert(SLabel && "Forgot label after clobber instruction");
1277 // The value is valid until the next DBG_VALUE or clobber.
1278 DotDebugLocEntries.push_back(
1279 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1281 DotDebugLocEntries.push_back(DotDebugLocEntry());
1284 // Collect info for variables that were optimized out.
1285 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1286 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1287 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1288 DIVariable DV(Variables.getElement(i));
1289 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1291 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1292 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1296 // Return Label preceding the instruction.
1297 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1298 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1299 assert(Label && "Didn't insert label before instruction");
1303 // Return Label immediately following the instruction.
1304 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1305 return LabelsAfterInsn.lookup(MI);
1308 // Process beginning of an instruction.
1309 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1312 // Check if source location changes, but ignore DBG_VALUE locations.
1313 if (!MI->isDebugValue()) {
1314 DebugLoc DL = MI->getDebugLoc();
1315 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1318 if (DL == PrologEndLoc) {
1319 Flags |= DWARF2_FLAG_PROLOGUE_END;
1320 PrologEndLoc = DebugLoc();
1322 if (PrologEndLoc.isUnknown())
1323 Flags |= DWARF2_FLAG_IS_STMT;
1325 if (!DL.isUnknown()) {
1326 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1327 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1329 recordSourceLine(0, 0, 0, 0);
1333 // Insert labels where requested.
1334 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1335 LabelsBeforeInsn.find(MI);
1338 if (I == LabelsBeforeInsn.end())
1341 // Label already assigned.
1346 PrevLabel = MMI->getContext().CreateTempSymbol();
1347 Asm->OutStreamer.EmitLabel(PrevLabel);
1349 I->second = PrevLabel;
1352 // Process end of an instruction.
1353 void DwarfDebug::endInstruction() {
1355 // Don't create a new label after DBG_VALUE instructions.
1356 // They don't generate code.
1357 if (!CurMI->isDebugValue())
1360 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1361 LabelsAfterInsn.find(CurMI);
1365 if (I == LabelsAfterInsn.end())
1368 // Label already assigned.
1372 // We need a label after this instruction.
1374 PrevLabel = MMI->getContext().CreateTempSymbol();
1375 Asm->OutStreamer.EmitLabel(PrevLabel);
1377 I->second = PrevLabel;
1380 // Each LexicalScope has first instruction and last instruction to mark
1381 // beginning and end of a scope respectively. Create an inverse map that list
1382 // scopes starts (and ends) with an instruction. One instruction may start (or
1383 // end) multiple scopes. Ignore scopes that are not reachable.
1384 void DwarfDebug::identifyScopeMarkers() {
1385 SmallVector<LexicalScope *, 4> WorkList;
1386 WorkList.push_back(LScopes.getCurrentFunctionScope());
1387 while (!WorkList.empty()) {
1388 LexicalScope *S = WorkList.pop_back_val();
1390 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1391 if (!Children.empty())
1392 WorkList.append(Children.begin(), Children.end());
1394 if (S->isAbstractScope())
1397 for (const InsnRange &R : S->getRanges()) {
1398 assert(R.first && "InsnRange does not have first instruction!");
1399 assert(R.second && "InsnRange does not have second instruction!");
1400 requestLabelBeforeInsn(R.first);
1401 requestLabelAfterInsn(R.second);
1406 // Gather pre-function debug information. Assumes being called immediately
1407 // after the function entry point has been emitted.
1408 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1411 // If there's no debug info for the function we're not going to do anything.
1412 if (!MMI->hasDebugInfo())
1415 // Grab the lexical scopes for the function, if we don't have any of those
1416 // then we're not going to be able to do anything.
1417 LScopes.initialize(*MF);
1418 if (LScopes.empty()) {
1419 UsedNonDefaultText = true;
1423 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1425 // Make sure that each lexical scope will have a begin/end label.
1426 identifyScopeMarkers();
1428 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1429 // belongs to so that we add to the correct per-cu line table in the
1431 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1432 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1433 assert(TheCU && "Unable to find compile unit!");
1434 if (Asm->OutStreamer.hasRawTextSupport())
1435 // Use a single line table if we are generating assembly.
1436 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1438 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1440 // Check the current section against the standard text section. If different
1441 // keep track so that we will know when we're emitting functions into multiple
1443 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1444 UsedNonDefaultText = true;
1446 // Emit a label for the function so that we have a beginning address.
1447 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1448 // Assumes in correct section after the entry point.
1449 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1451 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1452 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1453 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1455 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1457 bool AtBlockEntry = true;
1458 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1460 const MachineInstr *MI = II;
1462 if (MI->isDebugValue()) {
1463 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1465 // Keep track of user variables.
1467 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1469 // Variable is in a register, we need to check for clobbers.
1470 if (isDbgValueInDefinedReg(MI))
1471 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1473 // Check the history of this variable.
1474 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1475 if (History.empty()) {
1476 UserVariables.push_back(Var);
1477 // The first mention of a function argument gets the FunctionBeginSym
1478 // label, so arguments are visible when breaking at function entry.
1480 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1481 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1482 LabelsBeforeInsn[MI] = FunctionBeginSym;
1484 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1485 const MachineInstr *Prev = History.back();
1486 if (Prev->isDebugValue()) {
1487 // Coalesce identical entries at the end of History.
1488 if (History.size() >= 2 &&
1489 Prev->isIdenticalTo(History[History.size() - 2])) {
1490 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1491 << "\t" << *Prev << "\t"
1492 << *History[History.size() - 2] << "\n");
1496 // Terminate old register assignments that don't reach MI;
1497 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1498 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1499 isDbgValueInDefinedReg(Prev)) {
1500 // Previous register assignment needs to terminate at the end of
1502 MachineBasicBlock::const_iterator LastMI =
1503 PrevMBB->getLastNonDebugInstr();
1504 if (LastMI == PrevMBB->end()) {
1505 // Drop DBG_VALUE for empty range.
1506 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1507 << "\t" << *Prev << "\n");
1509 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1510 // Terminate after LastMI.
1511 History.push_back(LastMI);
1515 History.push_back(MI);
1517 // Not a DBG_VALUE instruction.
1518 if (!MI->isPosition())
1519 AtBlockEntry = false;
1521 // First known non-DBG_VALUE and non-frame setup location marks
1522 // the beginning of the function body.
1523 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1524 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1525 PrologEndLoc = MI->getDebugLoc();
1527 // Check if the instruction clobbers any registers with debug vars.
1528 for (const MachineOperand &MO : MI->operands()) {
1529 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1531 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1534 const MDNode *Var = LiveUserVar[Reg];
1537 // Reg is now clobbered.
1538 LiveUserVar[Reg] = 0;
1540 // Was MD last defined by a DBG_VALUE referring to Reg?
1541 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1542 if (HistI == DbgValues.end())
1544 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1545 if (History.empty())
1547 const MachineInstr *Prev = History.back();
1548 // Sanity-check: Register assignments are terminated at the end of
1550 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1552 // Is the variable still in Reg?
1553 if (!isDbgValueInDefinedReg(Prev) ||
1554 Prev->getOperand(0).getReg() != Reg)
1556 // Var is clobbered. Make sure the next instruction gets a label.
1557 History.push_back(MI);
1564 for (auto &I : DbgValues) {
1565 SmallVectorImpl<const MachineInstr *> &History = I.second;
1566 if (History.empty())
1569 // Make sure the final register assignments are terminated.
1570 const MachineInstr *Prev = History.back();
1571 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1572 const MachineBasicBlock *PrevMBB = Prev->getParent();
1573 MachineBasicBlock::const_iterator LastMI =
1574 PrevMBB->getLastNonDebugInstr();
1575 if (LastMI == PrevMBB->end())
1576 // Drop DBG_VALUE for empty range.
1578 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1579 // Terminate after LastMI.
1580 History.push_back(LastMI);
1583 // Request labels for the full history.
1584 for (const MachineInstr *MI : History) {
1585 if (MI->isDebugValue())
1586 requestLabelBeforeInsn(MI);
1588 requestLabelAfterInsn(MI);
1592 PrevInstLoc = DebugLoc();
1593 PrevLabel = FunctionBeginSym;
1595 // Record beginning of function.
1596 if (!PrologEndLoc.isUnknown()) {
1597 DebugLoc FnStartDL =
1598 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1600 FnStartDL.getLine(), FnStartDL.getCol(),
1601 FnStartDL.getScope(MF->getFunction()->getContext()),
1602 // We'd like to list the prologue as "not statements" but GDB behaves
1603 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1604 DWARF2_FLAG_IS_STMT);
1608 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1609 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1610 DIVariable DV = Var->getVariable();
1611 // Variables with positive arg numbers are parameters.
1612 if (unsigned ArgNum = DV.getArgNumber()) {
1613 // Keep all parameters in order at the start of the variable list to ensure
1614 // function types are correct (no out-of-order parameters)
1616 // This could be improved by only doing it for optimized builds (unoptimized
1617 // builds have the right order to begin with), searching from the back (this
1618 // would catch the unoptimized case quickly), or doing a binary search
1619 // rather than linear search.
1620 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1621 while (I != Vars.end()) {
1622 unsigned CurNum = (*I)->getVariable().getArgNumber();
1623 // A local (non-parameter) variable has been found, insert immediately
1627 // A later indexed parameter has been found, insert immediately before it.
1628 if (CurNum > ArgNum)
1632 Vars.insert(I, Var);
1636 Vars.push_back(Var);
1639 // Gather and emit post-function debug information.
1640 void DwarfDebug::endFunction(const MachineFunction *MF) {
1641 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1642 // though the beginFunction may not be called at all.
1643 // We should handle both cases.
1647 assert(CurFn == MF);
1650 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1655 // Define end label for subprogram.
1656 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1657 // Assumes in correct section after the entry point.
1658 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1660 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1661 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1663 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1664 collectVariableInfo(ProcessedVars);
1666 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1667 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1668 assert(TheCU && "Unable to find compile unit!");
1670 // Construct abstract scopes.
1671 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1672 DISubprogram SP(AScope->getScopeNode());
1673 if (SP.isSubprogram()) {
1674 // Collect info for variables that were optimized out.
1675 DIArray Variables = SP.getVariables();
1676 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1677 DIVariable DV(Variables.getElement(i));
1678 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1680 // Check that DbgVariable for DV wasn't created earlier, when
1681 // findAbstractVariable() was called for inlined instance of DV.
1682 LLVMContext &Ctx = DV->getContext();
1683 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1684 if (AbstractVariables.lookup(CleanDV))
1686 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1687 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1690 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1691 constructScopeDIE(TheCU, AScope);
1694 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1695 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1696 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1698 // Add the range of this function to the list of ranges for the CU.
1699 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1700 TheCU->addRange(std::move(Span));
1703 for (auto &I : ScopeVariables)
1704 DeleteContainerPointers(I.second);
1705 ScopeVariables.clear();
1706 DeleteContainerPointers(CurrentFnArguments);
1707 UserVariables.clear();
1709 AbstractVariables.clear();
1710 LabelsBeforeInsn.clear();
1711 LabelsAfterInsn.clear();
1716 // Register a source line with debug info. Returns the unique label that was
1717 // emitted and which provides correspondence to the source line list.
1718 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1723 unsigned Discriminator = 0;
1725 DIDescriptor Scope(S);
1727 if (Scope.isCompileUnit()) {
1728 DICompileUnit CU(S);
1729 Fn = CU.getFilename();
1730 Dir = CU.getDirectory();
1731 } else if (Scope.isFile()) {
1733 Fn = F.getFilename();
1734 Dir = F.getDirectory();
1735 } else if (Scope.isSubprogram()) {
1737 Fn = SP.getFilename();
1738 Dir = SP.getDirectory();
1739 } else if (Scope.isLexicalBlockFile()) {
1740 DILexicalBlockFile DBF(S);
1741 Fn = DBF.getFilename();
1742 Dir = DBF.getDirectory();
1743 } else if (Scope.isLexicalBlock()) {
1744 DILexicalBlock DB(S);
1745 Fn = DB.getFilename();
1746 Dir = DB.getDirectory();
1747 Discriminator = DB.getDiscriminator();
1749 llvm_unreachable("Unexpected scope info");
1751 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1752 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1753 ->getOrCreateSourceID(Fn, Dir);
1755 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1759 //===----------------------------------------------------------------------===//
1761 //===----------------------------------------------------------------------===//
1763 // Compute the size and offset of a DIE. The offset is relative to start of the
1764 // CU. It returns the offset after laying out the DIE.
1765 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1766 // Record the abbreviation.
1767 assignAbbrevNumber(Die->getAbbrev());
1769 // Get the abbreviation for this DIE.
1770 const DIEAbbrev &Abbrev = Die->getAbbrev();
1773 Die->setOffset(Offset);
1775 // Start the size with the size of abbreviation code.
1776 Offset += getULEB128Size(Die->getAbbrevNumber());
1778 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1779 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1781 // Size the DIE attribute values.
1782 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1783 // Size attribute value.
1784 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1786 // Get the children.
1787 const std::vector<DIE *> &Children = Die->getChildren();
1789 // Size the DIE children if any.
1790 if (!Children.empty()) {
1791 assert(Abbrev.hasChildren() && "Children flag not set");
1793 for (DIE *Child : Children)
1794 Offset = computeSizeAndOffset(Child, Offset);
1796 // End of children marker.
1797 Offset += sizeof(int8_t);
1800 Die->setSize(Offset - Die->getOffset());
1804 // Compute the size and offset for each DIE.
1805 void DwarfFile::computeSizeAndOffsets() {
1806 // Offset from the first CU in the debug info section is 0 initially.
1807 unsigned SecOffset = 0;
1809 // Iterate over each compile unit and set the size and offsets for each
1810 // DIE within each compile unit. All offsets are CU relative.
1811 for (DwarfUnit *TheU : CUs) {
1812 TheU->setDebugInfoOffset(SecOffset);
1814 // CU-relative offset is reset to 0 here.
1815 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1816 TheU->getHeaderSize(); // Unit-specific headers
1818 // EndOffset here is CU-relative, after laying out
1819 // all of the CU DIE.
1820 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1821 SecOffset += EndOffset;
1825 // Emit initial Dwarf sections with a label at the start of each one.
1826 void DwarfDebug::emitSectionLabels() {
1827 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1829 // Dwarf sections base addresses.
1830 DwarfInfoSectionSym =
1831 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1832 if (useSplitDwarf())
1833 DwarfInfoDWOSectionSym =
1834 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1835 DwarfAbbrevSectionSym =
1836 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1837 if (useSplitDwarf())
1838 DwarfAbbrevDWOSectionSym = emitSectionSym(
1839 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1840 if (GenerateARangeSection)
1841 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1843 DwarfLineSectionSym =
1844 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1845 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1846 if (GenerateGnuPubSections) {
1847 DwarfGnuPubNamesSectionSym =
1848 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1849 DwarfGnuPubTypesSectionSym =
1850 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1851 } else if (HasDwarfPubSections) {
1852 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1853 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1856 DwarfStrSectionSym =
1857 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1858 if (useSplitDwarf()) {
1859 DwarfStrDWOSectionSym =
1860 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1861 DwarfAddrSectionSym =
1862 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1864 DwarfDebugRangeSectionSym =
1865 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1867 DwarfDebugLocSectionSym =
1868 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1871 // Recursively emits a debug information entry.
1872 void DwarfDebug::emitDIE(DIE *Die) {
1873 // Get the abbreviation for this DIE.
1874 const DIEAbbrev &Abbrev = Die->getAbbrev();
1876 // Emit the code (index) for the abbreviation.
1877 if (Asm->isVerbose())
1878 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1879 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1880 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1881 dwarf::TagString(Abbrev.getTag()));
1882 Asm->EmitULEB128(Abbrev.getNumber());
1884 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1885 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1887 // Emit the DIE attribute values.
1888 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1889 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1890 dwarf::Form Form = AbbrevData[i].getForm();
1891 assert(Form && "Too many attributes for DIE (check abbreviation)");
1893 if (Asm->isVerbose()) {
1894 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1895 if (Attr == dwarf::DW_AT_accessibility)
1896 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1897 cast<DIEInteger>(Values[i])->getValue()));
1900 // Emit an attribute using the defined form.
1901 Values[i]->EmitValue(Asm, Form);
1904 // Emit the DIE children if any.
1905 if (Abbrev.hasChildren()) {
1906 const std::vector<DIE *> &Children = Die->getChildren();
1908 for (DIE *Child : Children)
1911 Asm->OutStreamer.AddComment("End Of Children Mark");
1916 // Emit the various dwarf units to the unit section USection with
1917 // the abbreviations going into ASection.
1918 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1919 const MCSymbol *ASectionSym) {
1920 for (DwarfUnit *TheU : CUs) {
1921 DIE *Die = TheU->getUnitDie();
1922 const MCSection *USection = TheU->getSection();
1923 Asm->OutStreamer.SwitchSection(USection);
1925 // Emit the compile units header.
1926 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1928 // Emit size of content not including length itself
1929 Asm->OutStreamer.AddComment("Length of Unit");
1930 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1932 TheU->emitHeader(ASection, ASectionSym);
1935 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1939 // Emit the debug info section.
1940 void DwarfDebug::emitDebugInfo() {
1941 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1943 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1944 DwarfAbbrevSectionSym);
1947 // Emit the abbreviation section.
1948 void DwarfDebug::emitAbbreviations() {
1949 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1951 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1954 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1955 // Check to see if it is worth the effort.
1956 if (!Abbreviations.empty()) {
1957 // Start the debug abbrev section.
1958 Asm->OutStreamer.SwitchSection(Section);
1960 // For each abbrevation.
1961 for (const DIEAbbrev *Abbrev : Abbreviations) {
1962 // Emit the abbrevations code (base 1 index.)
1963 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1965 // Emit the abbreviations data.
1969 // Mark end of abbreviations.
1970 Asm->EmitULEB128(0, "EOM(3)");
1974 // Emit the last address of the section and the end of the line matrix.
1975 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1976 // Define last address of section.
1977 Asm->OutStreamer.AddComment("Extended Op");
1980 Asm->OutStreamer.AddComment("Op size");
1981 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1982 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1983 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1985 Asm->OutStreamer.AddComment("Section end label");
1987 Asm->OutStreamer.EmitSymbolValue(
1988 Asm->GetTempSymbol("section_end", SectionEnd),
1989 Asm->getDataLayout().getPointerSize());
1991 // Mark end of matrix.
1992 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1998 // Emit visible names into a hashed accelerator table section.
1999 void DwarfDebug::emitAccelNames() {
2001 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2002 for (DwarfUnit *TheU : getUnits()) {
2003 for (const auto &GI : TheU->getAccelNames()) {
2004 StringRef Name = GI.getKey();
2005 for (const DIE *D : GI.second)
2006 AT.AddName(Name, D);
2010 AT.FinalizeTable(Asm, "Names");
2011 Asm->OutStreamer.SwitchSection(
2012 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2013 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2014 Asm->OutStreamer.EmitLabel(SectionBegin);
2016 // Emit the full data.
2017 AT.Emit(Asm, SectionBegin, &InfoHolder);
2020 // Emit objective C classes and categories into a hashed accelerator table
2022 void DwarfDebug::emitAccelObjC() {
2024 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2025 for (DwarfUnit *TheU : getUnits()) {
2026 for (const auto &GI : TheU->getAccelObjC()) {
2027 StringRef Name = GI.getKey();
2028 for (const DIE *D : GI.second)
2029 AT.AddName(Name, D);
2033 AT.FinalizeTable(Asm, "ObjC");
2034 Asm->OutStreamer.SwitchSection(
2035 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2036 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2037 Asm->OutStreamer.EmitLabel(SectionBegin);
2039 // Emit the full data.
2040 AT.Emit(Asm, SectionBegin, &InfoHolder);
2043 // Emit namespace dies into a hashed accelerator table.
2044 void DwarfDebug::emitAccelNamespaces() {
2046 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2047 for (DwarfUnit *TheU : getUnits()) {
2048 for (const auto &GI : TheU->getAccelNamespace()) {
2049 StringRef Name = GI.getKey();
2050 for (const DIE *D : GI.second)
2051 AT.AddName(Name, D);
2055 AT.FinalizeTable(Asm, "namespac");
2056 Asm->OutStreamer.SwitchSection(
2057 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2058 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2059 Asm->OutStreamer.EmitLabel(SectionBegin);
2061 // Emit the full data.
2062 AT.Emit(Asm, SectionBegin, &InfoHolder);
2065 // Emit type dies into a hashed accelerator table.
2066 void DwarfDebug::emitAccelTypes() {
2067 std::vector<DwarfAccelTable::Atom> Atoms;
2069 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2071 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2073 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2074 DwarfAccelTable AT(Atoms);
2075 for (DwarfUnit *TheU : getUnits()) {
2076 for (const auto &GI : TheU->getAccelTypes()) {
2077 StringRef Name = GI.getKey();
2078 for (const auto &DI : GI.second)
2079 AT.AddName(Name, DI.first, DI.second);
2083 AT.FinalizeTable(Asm, "types");
2084 Asm->OutStreamer.SwitchSection(
2085 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2086 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2087 Asm->OutStreamer.EmitLabel(SectionBegin);
2089 // Emit the full data.
2090 AT.Emit(Asm, SectionBegin, &InfoHolder);
2093 // Public name handling.
2094 // The format for the various pubnames:
2096 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2097 // for the DIE that is named.
2099 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2100 // into the CU and the index value is computed according to the type of value
2101 // for the DIE that is named.
2103 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2104 // it's the offset within the debug_info/debug_types dwo section, however, the
2105 // reference in the pubname header doesn't change.
2107 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2108 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2110 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2112 // We could have a specification DIE that has our most of our knowledge,
2113 // look for that now.
2114 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2116 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2117 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2118 Linkage = dwarf::GIEL_EXTERNAL;
2119 } else if (Die->findAttribute(dwarf::DW_AT_external))
2120 Linkage = dwarf::GIEL_EXTERNAL;
2122 switch (Die->getTag()) {
2123 case dwarf::DW_TAG_class_type:
2124 case dwarf::DW_TAG_structure_type:
2125 case dwarf::DW_TAG_union_type:
2126 case dwarf::DW_TAG_enumeration_type:
2127 return dwarf::PubIndexEntryDescriptor(
2128 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2129 ? dwarf::GIEL_STATIC
2130 : dwarf::GIEL_EXTERNAL);
2131 case dwarf::DW_TAG_typedef:
2132 case dwarf::DW_TAG_base_type:
2133 case dwarf::DW_TAG_subrange_type:
2134 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2135 case dwarf::DW_TAG_namespace:
2136 return dwarf::GIEK_TYPE;
2137 case dwarf::DW_TAG_subprogram:
2138 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2139 case dwarf::DW_TAG_constant:
2140 case dwarf::DW_TAG_variable:
2141 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2142 case dwarf::DW_TAG_enumerator:
2143 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2144 dwarf::GIEL_STATIC);
2146 return dwarf::GIEK_NONE;
2150 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2152 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2153 const MCSection *PSec =
2154 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2155 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2157 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2160 void DwarfDebug::emitDebugPubSection(
2161 bool GnuStyle, const MCSection *PSec, StringRef Name,
2162 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2163 for (const auto &NU : CUMap) {
2164 DwarfCompileUnit *TheU = NU.second;
2166 const auto &Globals = (TheU->*Accessor)();
2168 if (Globals.empty())
2171 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2173 unsigned ID = TheU->getUniqueID();
2175 // Start the dwarf pubnames section.
2176 Asm->OutStreamer.SwitchSection(PSec);
2179 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2180 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2181 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2182 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2184 Asm->OutStreamer.EmitLabel(BeginLabel);
2186 Asm->OutStreamer.AddComment("DWARF Version");
2187 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2189 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2190 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2192 Asm->OutStreamer.AddComment("Compilation Unit Length");
2193 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2195 // Emit the pubnames for this compilation unit.
2196 for (const auto &GI : Globals) {
2197 const char *Name = GI.getKeyData();
2198 const DIE *Entity = GI.second;
2200 Asm->OutStreamer.AddComment("DIE offset");
2201 Asm->EmitInt32(Entity->getOffset());
2204 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2205 Asm->OutStreamer.AddComment(
2206 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2207 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2208 Asm->EmitInt8(Desc.toBits());
2211 Asm->OutStreamer.AddComment("External Name");
2212 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2215 Asm->OutStreamer.AddComment("End Mark");
2217 Asm->OutStreamer.EmitLabel(EndLabel);
2221 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2222 const MCSection *PSec =
2223 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2224 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2226 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2229 // Emit strings into a string section.
2230 void DwarfFile::emitStrings(const MCSection *StrSection,
2231 const MCSection *OffsetSection = NULL,
2232 const MCSymbol *StrSecSym = NULL) {
2234 if (StringPool.empty())
2237 // Start the dwarf str section.
2238 Asm->OutStreamer.SwitchSection(StrSection);
2240 // Get all of the string pool entries and put them in an array by their ID so
2241 // we can sort them.
2242 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2244 for (const auto &I : StringPool)
2245 Entries.push_back(std::make_pair(I.second.second, &I));
2247 array_pod_sort(Entries.begin(), Entries.end());
2249 for (const auto &Entry : Entries) {
2250 // Emit a label for reference from debug information entries.
2251 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2253 // Emit the string itself with a terminating null byte.
2254 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2255 Entry.second->getKeyLength() + 1));
2258 // If we've got an offset section go ahead and emit that now as well.
2259 if (OffsetSection) {
2260 Asm->OutStreamer.SwitchSection(OffsetSection);
2261 unsigned offset = 0;
2262 unsigned size = 4; // FIXME: DWARF64 is 8.
2263 for (const auto &Entry : Entries) {
2264 Asm->OutStreamer.EmitIntValue(offset, size);
2265 offset += Entry.second->getKeyLength() + 1;
2270 // Emit addresses into the section given.
2271 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2273 if (AddressPool.empty())
2276 // Start the dwarf addr section.
2277 Asm->OutStreamer.SwitchSection(AddrSection);
2279 // Order the address pool entries by ID
2280 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2282 for (const auto &I : AddressPool)
2283 Entries[I.second.Number] =
2285 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2286 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2288 for (const MCExpr *Entry : Entries)
2289 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2292 // Emit visible names into a debug str section.
2293 void DwarfDebug::emitDebugStr() {
2294 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2295 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2298 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2299 const DotDebugLocEntry &Entry) {
2300 DIVariable DV(Entry.getVariable());
2301 if (Entry.isInt()) {
2302 DIBasicType BTy(DV.getType());
2303 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2304 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2305 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2306 Streamer.EmitSLEB128(Entry.getInt());
2308 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2309 Streamer.EmitULEB128(Entry.getInt());
2311 } else if (Entry.isLocation()) {
2312 MachineLocation Loc = Entry.getLoc();
2313 if (!DV.hasComplexAddress())
2315 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2317 // Complex address entry.
2318 unsigned N = DV.getNumAddrElements();
2320 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2321 if (Loc.getOffset()) {
2323 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2324 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2325 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2326 Streamer.EmitSLEB128(DV.getAddrElement(1));
2328 // If first address element is OpPlus then emit
2329 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2330 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2331 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2335 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2338 // Emit remaining complex address elements.
2339 for (; i < N; ++i) {
2340 uint64_t Element = DV.getAddrElement(i);
2341 if (Element == DIBuilder::OpPlus) {
2342 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2343 Streamer.EmitULEB128(DV.getAddrElement(++i));
2344 } else if (Element == DIBuilder::OpDeref) {
2346 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2348 llvm_unreachable("unknown Opcode found in complex address");
2352 // else ... ignore constant fp. There is not any good way to
2353 // to represent them here in dwarf.
2357 // Emit locations into the debug loc section.
2358 void DwarfDebug::emitDebugLoc() {
2359 if (DotDebugLocEntries.empty())
2362 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2363 I = DotDebugLocEntries.begin(),
2364 E = DotDebugLocEntries.end();
2366 DotDebugLocEntry &Entry = *I;
2367 if (I + 1 != DotDebugLocEntries.end())
2371 // Start the dwarf loc section.
2372 Asm->OutStreamer.SwitchSection(
2373 Asm->getObjFileLowering().getDwarfLocSection());
2374 unsigned char Size = Asm->getDataLayout().getPointerSize();
2375 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2377 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2378 I = DotDebugLocEntries.begin(),
2379 E = DotDebugLocEntries.end();
2380 I != E; ++I, ++index) {
2381 const DotDebugLocEntry &Entry = *I;
2382 if (Entry.isMerged())
2385 if (Entry.isEmpty()) {
2386 Asm->OutStreamer.EmitIntValue(0, Size);
2387 Asm->OutStreamer.EmitIntValue(0, Size);
2388 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2390 // Set up the range.
2391 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2392 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2393 Asm->OutStreamer.AddComment("Loc expr size");
2394 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2395 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2396 Asm->EmitLabelDifference(end, begin, 2);
2397 Asm->OutStreamer.EmitLabel(begin);
2399 APByteStreamer Streamer(*Asm);
2400 emitDebugLocEntry(Streamer, Entry);
2402 Asm->OutStreamer.EmitLabel(end);
2408 const MCSymbol *Start, *End;
2411 // Emit a debug aranges section, containing a CU lookup for any
2412 // address we can tie back to a CU.
2413 void DwarfDebug::emitDebugARanges() {
2414 // Start the dwarf aranges section.
2415 Asm->OutStreamer.SwitchSection(
2416 Asm->getObjFileLowering().getDwarfARangesSection());
2418 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2422 // Build a list of sections used.
2423 std::vector<const MCSection *> Sections;
2424 for (const auto &it : SectionMap) {
2425 const MCSection *Section = it.first;
2426 Sections.push_back(Section);
2429 // Sort the sections into order.
2430 // This is only done to ensure consistent output order across different runs.
2431 std::sort(Sections.begin(), Sections.end(), SectionSort);
2433 // Build a set of address spans, sorted by CU.
2434 for (const MCSection *Section : Sections) {
2435 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2436 if (List.size() < 2)
2439 // Sort the symbols by offset within the section.
2440 std::sort(List.begin(), List.end(),
2441 [&](const SymbolCU &A, const SymbolCU &B) {
2442 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2443 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2445 // Symbols with no order assigned should be placed at the end.
2446 // (e.g. section end labels)
2454 // If we have no section (e.g. common), just write out
2455 // individual spans for each symbol.
2456 if (Section == NULL) {
2457 for (const SymbolCU &Cur : List) {
2459 Span.Start = Cur.Sym;
2462 Spans[Cur.CU].push_back(Span);
2465 // Build spans between each label.
2466 const MCSymbol *StartSym = List[0].Sym;
2467 for (size_t n = 1, e = List.size(); n < e; n++) {
2468 const SymbolCU &Prev = List[n - 1];
2469 const SymbolCU &Cur = List[n];
2471 // Try and build the longest span we can within the same CU.
2472 if (Cur.CU != Prev.CU) {
2474 Span.Start = StartSym;
2476 Spans[Prev.CU].push_back(Span);
2483 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2485 // Build a list of CUs used.
2486 std::vector<DwarfCompileUnit *> CUs;
2487 for (const auto &it : Spans) {
2488 DwarfCompileUnit *CU = it.first;
2492 // Sort the CU list (again, to ensure consistent output order).
2493 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2494 return A->getUniqueID() < B->getUniqueID();
2497 // Emit an arange table for each CU we used.
2498 for (DwarfCompileUnit *CU : CUs) {
2499 std::vector<ArangeSpan> &List = Spans[CU];
2501 // Emit size of content not including length itself.
2502 unsigned ContentSize =
2503 sizeof(int16_t) + // DWARF ARange version number
2504 sizeof(int32_t) + // Offset of CU in the .debug_info section
2505 sizeof(int8_t) + // Pointer Size (in bytes)
2506 sizeof(int8_t); // Segment Size (in bytes)
2508 unsigned TupleSize = PtrSize * 2;
2510 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2512 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2514 ContentSize += Padding;
2515 ContentSize += (List.size() + 1) * TupleSize;
2517 // For each compile unit, write the list of spans it covers.
2518 Asm->OutStreamer.AddComment("Length of ARange Set");
2519 Asm->EmitInt32(ContentSize);
2520 Asm->OutStreamer.AddComment("DWARF Arange version number");
2521 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2522 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2523 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2524 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2525 Asm->EmitInt8(PtrSize);
2526 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2529 Asm->OutStreamer.EmitFill(Padding, 0xff);
2531 for (const ArangeSpan &Span : List) {
2532 Asm->EmitLabelReference(Span.Start, PtrSize);
2534 // Calculate the size as being from the span start to it's end.
2536 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2538 // For symbols without an end marker (e.g. common), we
2539 // write a single arange entry containing just that one symbol.
2540 uint64_t Size = SymSize[Span.Start];
2544 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2548 Asm->OutStreamer.AddComment("ARange terminator");
2549 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2550 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2554 // Emit visible names into a debug ranges section.
2555 void DwarfDebug::emitDebugRanges() {
2556 // Start the dwarf ranges section.
2557 Asm->OutStreamer.SwitchSection(
2558 Asm->getObjFileLowering().getDwarfRangesSection());
2560 // Size for our labels.
2561 unsigned char Size = Asm->getDataLayout().getPointerSize();
2563 // Grab the specific ranges for the compile units in the module.
2564 for (const auto &I : CUMap) {
2565 DwarfCompileUnit *TheCU = I.second;
2567 // Emit a symbol so we can find the beginning of our ranges.
2568 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2570 // Iterate over the misc ranges for the compile units in the module.
2571 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2572 // Emit our symbol so we can find the beginning of the range.
2573 Asm->OutStreamer.EmitLabel(List.getSym());
2575 for (const RangeSpan &Range : List.getRanges()) {
2576 const MCSymbol *Begin = Range.getStart();
2577 const MCSymbol *End = Range.getEnd();
2578 assert(Begin && "Range without a begin symbol?");
2579 assert(End && "Range without an end symbol?");
2580 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2581 Asm->OutStreamer.EmitSymbolValue(End, Size);
2584 // And terminate the list with two 0 values.
2585 Asm->OutStreamer.EmitIntValue(0, Size);
2586 Asm->OutStreamer.EmitIntValue(0, Size);
2589 // Now emit a range for the CU itself.
2590 if (useCURanges() && TheCU->getRanges().size()) {
2591 Asm->OutStreamer.EmitLabel(
2592 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2593 for (const RangeSpan &Range : TheCU->getRanges()) {
2594 const MCSymbol *Begin = Range.getStart();
2595 const MCSymbol *End = Range.getEnd();
2596 assert(Begin && "Range without a begin symbol?");
2597 assert(End && "Range without an end symbol?");
2598 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2599 Asm->OutStreamer.EmitSymbolValue(End, Size);
2601 // And terminate the list with two 0 values.
2602 Asm->OutStreamer.EmitIntValue(0, Size);
2603 Asm->OutStreamer.EmitIntValue(0, Size);
2608 // DWARF5 Experimental Separate Dwarf emitters.
2610 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2612 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2613 U->getCUNode().getSplitDebugFilename());
2615 // Relocate to the beginning of the addr_base section, else 0 for the
2616 // beginning of the one for this compile unit.
2617 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2618 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2620 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2622 if (!CompilationDir.empty())
2623 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2625 addGnuPubAttributes(NewU, Die);
2627 SkeletonHolder.addUnit(NewU);
2630 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2631 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2632 // DW_AT_ranges_base, DW_AT_addr_base.
2633 // TODO: Implement DW_AT_ranges_base.
2634 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2636 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2637 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2638 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2639 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2640 DwarfInfoSectionSym);
2642 NewCU->initStmtList(DwarfLineSectionSym);
2644 initSkeletonUnit(CU, Die, NewCU);
2649 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2651 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2652 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2653 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2655 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2656 DwarfTypeUnit *NewTU =
2657 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2658 NewTU->setTypeSignature(TU->getTypeSignature());
2659 NewTU->setType(NULL);
2661 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2663 initSkeletonUnit(TU, Die, NewTU);
2667 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2668 // compile units that would normally be in debug_info.
2669 void DwarfDebug::emitDebugInfoDWO() {
2670 assert(useSplitDwarf() && "No split dwarf debug info?");
2671 InfoHolder.emitUnits(this,
2672 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2673 DwarfAbbrevDWOSectionSym);
2676 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2677 // abbreviations for the .debug_info.dwo section.
2678 void DwarfDebug::emitDebugAbbrevDWO() {
2679 assert(useSplitDwarf() && "No split dwarf?");
2680 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2683 void DwarfDebug::emitDebugLineDWO() {
2684 assert(useSplitDwarf() && "No split dwarf?");
2685 Asm->OutStreamer.SwitchSection(
2686 Asm->getObjFileLowering().getDwarfLineDWOSection());
2687 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2690 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2691 // string section and is identical in format to traditional .debug_str
2693 void DwarfDebug::emitDebugStrDWO() {
2694 assert(useSplitDwarf() && "No split dwarf?");
2695 const MCSection *OffSec =
2696 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2697 const MCSymbol *StrSym = DwarfStrSectionSym;
2698 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2702 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2703 StringRef Identifier, DIE *RefDie,
2704 DICompositeType CTy) {
2705 // Flag the type unit reference as a declaration so that if it contains
2706 // members (implicit special members, static data member definitions, member
2707 // declarations for definitions in this CU, etc) consumers don't get confused
2708 // and think this is a full definition.
2709 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2711 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2713 CU.addDIETypeSignature(RefDie, *TU);
2717 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2718 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2719 InfoHolder.getUnits().size(), UnitDie, CU, Asm, this, &InfoHolder,
2720 useSplitDwarf() ? &SplitTypeUnitFileTable : nullptr);
2722 InfoHolder.addUnit(NewTU);
2724 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2728 Hash.update(Identifier);
2729 // ... take the least significant 8 bytes and return those. Our MD5
2730 // implementation always returns its results in little endian, swap bytes
2732 MD5::MD5Result Result;
2734 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2735 NewTU->setTypeSignature(Signature);
2736 if (useSplitDwarf())
2737 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2739 CU.applyStmtList(*UnitDie);
2741 NewTU->setType(NewTU->createTypeDIE(CTy));
2745 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2746 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2748 CU.addDIETypeSignature(RefDie, *NewTU);
2751 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2752 MCSymbol *Begin, MCSymbol *End) {
2753 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2754 if (DwarfVersion < 4)
2755 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2757 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);