1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
53 #define DEBUG_TYPE "dwarfdebug"
56 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
57 cl::desc("Disable debug info printing"));
59 static cl::opt<bool> UnknownLocations(
60 "use-unknown-locations", cl::Hidden,
61 cl::desc("Make an absence of debug location information explicit."),
65 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
66 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
71 cl::desc("Generate dwarf aranges"),
75 enum DefaultOnOff { Default, Enable, Disable };
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 //===----------------------------------------------------------------------===//
113 /// resolve - Look in the DwarfDebug map for the MDNode that
114 /// corresponds to the reference.
115 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
116 return DD->resolve(Ref);
119 bool DbgVariable::isBlockByrefVariable() const {
120 assert(Var.isVariable() && "Invalid complex DbgVariable!");
121 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
125 DIType DbgVariable::getType() const {
126 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
127 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
128 // addresses instead.
129 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
130 /* Byref variables, in Blocks, are declared by the programmer as
131 "SomeType VarName;", but the compiler creates a
132 __Block_byref_x_VarName struct, and gives the variable VarName
133 either the struct, or a pointer to the struct, as its type. This
134 is necessary for various behind-the-scenes things the compiler
135 needs to do with by-reference variables in blocks.
137 However, as far as the original *programmer* is concerned, the
138 variable should still have type 'SomeType', as originally declared.
140 The following function dives into the __Block_byref_x_VarName
141 struct to find the original type of the variable. This will be
142 passed back to the code generating the type for the Debug
143 Information Entry for the variable 'VarName'. 'VarName' will then
144 have the original type 'SomeType' in its debug information.
146 The original type 'SomeType' will be the type of the field named
147 'VarName' inside the __Block_byref_x_VarName struct.
149 NOTE: In order for this to not completely fail on the debugger
150 side, the Debug Information Entry for the variable VarName needs to
151 have a DW_AT_location that tells the debugger how to unwind through
152 the pointers and __Block_byref_x_VarName struct to find the actual
153 value of the variable. The function addBlockByrefType does this. */
155 uint16_t tag = Ty.getTag();
157 if (tag == dwarf::DW_TAG_pointer_type)
158 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
160 DIArray Elements = DICompositeType(subType).getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDerivedType DT(Elements.getElement(i));
163 if (getName() == DT.getName())
164 return (resolve(DT.getTypeDerivedFrom()));
170 } // end llvm namespace
172 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
173 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
174 InfoHolder(A, "info_string", DIEValueAllocator),
175 UsedNonDefaultText(false),
176 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
178 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
179 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
180 DwarfAddrSectionSym = 0;
181 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
182 FunctionBeginSym = FunctionEndSym = 0;
186 // Turn on accelerator tables for Darwin by default, pubnames by
187 // default for non-Darwin, and handle split dwarf.
188 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
190 if (DwarfAccelTables == Default)
191 HasDwarfAccelTables = IsDarwin;
193 HasDwarfAccelTables = DwarfAccelTables == Enable;
195 if (SplitDwarf == Default)
196 HasSplitDwarf = false;
198 HasSplitDwarf = SplitDwarf == Enable;
200 if (DwarfPubSections == Default)
201 HasDwarfPubSections = !IsDarwin;
203 HasDwarfPubSections = DwarfPubSections == Enable;
205 DwarfVersion = DwarfVersionNumber
207 : MMI->getModule()->getDwarfVersion();
210 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
223 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
224 Asm->OutStreamer.EmitLabel(TmpSym);
228 DwarfFile::DwarfFile(AsmPrinter *AP, const char *Pref, BumpPtrAllocator &DA)
229 : Asm(AP), StringPool(DA), NextStringPoolNumber(0), StringPref(Pref) {}
230 DwarfFile::~DwarfFile() {
233 MCSymbol *DwarfFile::getStringPoolSym() {
234 return Asm->GetTempSymbol(StringPref);
237 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
238 std::pair<MCSymbol *, unsigned> &Entry =
239 StringPool.GetOrCreateValue(Str).getValue();
243 Entry.second = NextStringPoolNumber++;
244 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
247 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
259 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
260 std::make_pair(Sym, AddressPoolEntry(AddressPool.size(), TLS)));
261 return P.first->second.Number;
264 // Define a unique number for the abbreviation.
266 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
267 // Check the set for priors.
268 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
270 // If it's newly added.
271 if (InSet == &Abbrev) {
272 // Add to abbreviation list.
273 Abbreviations.push_back(&Abbrev);
275 // Assign the vector position + 1 as its number.
276 Abbrev.setNumber(Abbreviations.size());
278 // Assign existing abbreviation number.
279 Abbrev.setNumber(InSet->getNumber());
283 void DwarfFile::addUnit(DwarfUnit *CU) {
284 CUs.push_back(std::unique_ptr<DwarfUnit>(CU));
287 static bool isObjCClass(StringRef Name) {
288 return Name.startswith("+") || Name.startswith("-");
291 static bool hasObjCCategory(StringRef Name) {
292 if (!isObjCClass(Name))
295 return Name.find(") ") != StringRef::npos;
298 static void getObjCClassCategory(StringRef In, StringRef &Class,
299 StringRef &Category) {
300 if (!hasObjCCategory(In)) {
301 Class = In.slice(In.find('[') + 1, In.find(' '));
306 Class = In.slice(In.find('[') + 1, In.find('('));
307 Category = In.slice(In.find('[') + 1, In.find(' '));
311 static StringRef getObjCMethodName(StringRef In) {
312 return In.slice(In.find(' ') + 1, In.find(']'));
315 // Helper for sorting sections into a stable output order.
316 static bool SectionSort(const MCSection *A, const MCSection *B) {
317 std::string LA = (A ? A->getLabelBeginName() : "");
318 std::string LB = (B ? B->getLabelBeginName() : "");
322 // Add the various names to the Dwarf accelerator table names.
323 // TODO: Determine whether or not we should add names for programs
324 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
325 // is only slightly different than the lookup of non-standard ObjC names.
326 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
327 if (!SP.isDefinition())
329 TheU->addAccelName(SP.getName(), Die);
331 // If the linkage name is different than the name, go ahead and output
332 // that as well into the name table.
333 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
334 TheU->addAccelName(SP.getLinkageName(), Die);
336 // If this is an Objective-C selector name add it to the ObjC accelerator
338 if (isObjCClass(SP.getName())) {
339 StringRef Class, Category;
340 getObjCClassCategory(SP.getName(), Class, Category);
341 TheU->addAccelObjC(Class, Die);
343 TheU->addAccelObjC(Category, Die);
344 // Also add the base method name to the name table.
345 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
349 /// isSubprogramContext - Return true if Context is either a subprogram
350 /// or another context nested inside a subprogram.
351 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
354 DIDescriptor D(Context);
355 if (D.isSubprogram())
358 return isSubprogramContext(resolve(DIType(Context).getContext()));
362 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
363 // and DW_AT_high_pc attributes. If there are global variables in this
364 // scope then create and insert DIEs for these variables.
365 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
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++);
455 // Under fission, ranges are specified by constant offsets relative to the
456 // CU's DW_AT_GNU_ranges_base.
458 TheCU->addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
459 DwarfDebugRangeSectionSym);
461 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
462 DwarfDebugRangeSectionSym);
464 RangeSpanList List(RangeSym);
465 for (const InsnRange &R : Range) {
466 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
467 List.addRange(std::move(Span));
470 // Add the range list to the set of ranges to be emitted.
471 TheCU->addRangeList(std::move(List));
474 // Construct new DW_TAG_lexical_block for this scope and attach
475 // DW_AT_low_pc/DW_AT_high_pc labels.
476 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
477 LexicalScope *Scope) {
478 if (isLexicalScopeDIENull(Scope))
481 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
482 if (Scope->isAbstractScope())
485 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
487 // If we have multiple ranges, emit them into the range section.
488 if (ScopeRanges.size() > 1) {
489 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
493 // Construct the address range for this DIE.
494 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
495 MCSymbol *Start = getLabelBeforeInsn(RI->first);
496 MCSymbol *End = getLabelAfterInsn(RI->second);
497 assert(End && "End label should not be null!");
499 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
500 assert(End->isDefined() && "Invalid end label for an inlined scope!");
502 attachLowHighPC(TheCU, ScopeDIE, Start, End);
507 // This scope represents inlined body of a function. Construct DIE to
508 // represent this concrete inlined copy of the function.
509 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
510 LexicalScope *Scope) {
511 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
512 assert(!ScopeRanges.empty() &&
513 "LexicalScope does not have instruction markers!");
515 if (!Scope->getScopeNode())
517 DIScope DS(Scope->getScopeNode());
518 DISubprogram InlinedSP = getDISubprogram(DS);
519 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
521 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
525 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
526 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
528 // If we have multiple ranges, emit them into the range section.
529 if (ScopeRanges.size() > 1)
530 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
532 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
533 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
534 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
536 if (StartLabel == 0 || EndLabel == 0)
537 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
539 assert(StartLabel->isDefined() &&
540 "Invalid starting label for an inlined scope!");
541 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
543 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
546 InlinedSubprogramDIEs.insert(OriginDIE);
548 // Add the call site information to the DIE.
549 DILocation DL(Scope->getInlinedAt());
551 ScopeDIE, dwarf::DW_AT_call_file, None,
552 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
553 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
555 // Add name to the name table, we do this here because we're guaranteed
556 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
557 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
562 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
564 SmallVectorImpl<DIE *> &Children) {
565 DIE *ObjectPointer = NULL;
567 // Collect arguments for current function.
568 if (LScopes.isCurrentFunctionScope(Scope)) {
569 for (DbgVariable *ArgDV : CurrentFnArguments)
572 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
573 Children.push_back(Arg);
574 if (ArgDV->isObjectPointer())
578 // If this is a variadic function, add an unspecified parameter.
579 DISubprogram SP(Scope->getScopeNode());
580 DIArray FnArgs = SP.getType().getTypeArray();
581 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
582 .isUnspecifiedParameter()) {
583 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
584 Children.push_back(Ellipsis);
588 // Collect lexical scope children first.
589 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
590 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
591 Scope->isAbstractScope())) {
592 Children.push_back(Variable);
593 if (DV->isObjectPointer())
594 ObjectPointer = Variable;
596 for (LexicalScope *LS : Scope->getChildren())
597 if (DIE *Nested = constructScopeDIE(TheCU, LS))
598 Children.push_back(Nested);
599 return ObjectPointer;
602 // Construct a DIE for this scope.
603 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
604 LexicalScope *Scope) {
605 if (!Scope || !Scope->getScopeNode())
608 DIScope DS(Scope->getScopeNode());
610 SmallVector<DIE *, 8> Children;
611 DIE *ObjectPointer = NULL;
612 bool ChildrenCreated = false;
614 // We try to create the scope DIE first, then the children DIEs. This will
615 // avoid creating un-used children then removing them later when we find out
616 // the scope DIE is null.
617 DIE *ScopeDIE = NULL;
618 if (Scope->getInlinedAt())
619 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
620 else if (DS.isSubprogram()) {
621 ProcessedSPNodes.insert(DS);
622 if (Scope->isAbstractScope()) {
623 ScopeDIE = TheCU->getDIE(DS);
624 // Note down abstract DIE.
626 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
628 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
630 // Early exit when we know the scope DIE is going to be null.
631 if (isLexicalScopeDIENull(Scope))
634 // We create children here when we know the scope DIE is not going to be
635 // null and the children will be added to the scope DIE.
636 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
637 ChildrenCreated = true;
639 // There is no need to emit empty lexical block DIE.
640 std::pair<ImportedEntityMap::const_iterator,
641 ImportedEntityMap::const_iterator> Range =
643 ScopesWithImportedEntities.begin(),
644 ScopesWithImportedEntities.end(),
645 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
647 if (Children.empty() && Range.first == Range.second)
649 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
650 assert(ScopeDIE && "Scope DIE should not be null.");
651 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
653 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
657 assert(Children.empty() &&
658 "We create children only when the scope DIE is not null.");
661 if (!ChildrenCreated)
662 // We create children when the scope DIE is not null.
663 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
666 for (DIE *I : Children)
667 ScopeDIE->addChild(I);
669 if (DS.isSubprogram() && ObjectPointer != NULL)
670 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
675 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
676 if (!GenerateGnuPubSections)
679 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
682 // Create new DwarfCompileUnit for the given metadata node with tag
683 // DW_TAG_compile_unit.
684 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
685 StringRef FN = DIUnit.getFilename();
686 CompilationDir = DIUnit.getDirectory();
688 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
689 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
690 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
691 InfoHolder.addUnit(NewCU);
693 // LTO with assembly output shares a single line table amongst multiple CUs.
694 // To avoid the compilation directory being ambiguous, let the line table
695 // explicitly describe the directory of all files, never relying on the
696 // compilation directory.
697 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
698 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
699 NewCU->getUniqueID(), CompilationDir);
701 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
702 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
703 DIUnit.getLanguage());
704 NewCU->addString(Die, dwarf::DW_AT_name, FN);
706 if (!useSplitDwarf()) {
707 NewCU->initStmtList(DwarfLineSectionSym);
709 // If we're using split dwarf the compilation dir is going to be in the
710 // skeleton CU and so we don't need to duplicate it here.
711 if (!CompilationDir.empty())
712 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
714 addGnuPubAttributes(NewCU, Die);
717 if (DIUnit.isOptimized())
718 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
720 StringRef Flags = DIUnit.getFlags();
722 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
724 if (unsigned RVer = DIUnit.getRunTimeVersion())
725 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
726 dwarf::DW_FORM_data1, RVer);
731 if (useSplitDwarf()) {
732 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
733 DwarfInfoDWOSectionSym);
734 NewCU->setSkeleton(constructSkeletonCU(NewCU));
736 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
737 DwarfInfoSectionSym);
739 CUMap.insert(std::make_pair(DIUnit, NewCU));
740 CUDieMap.insert(std::make_pair(Die, NewCU));
744 // Construct subprogram DIE.
745 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
747 // FIXME: We should only call this routine once, however, during LTO if a
748 // program is defined in multiple CUs we could end up calling it out of
749 // beginModule as we walk the CUs.
751 DwarfCompileUnit *&CURef = SPMap[N];
757 if (!SP.isDefinition())
758 // This is a method declaration which will be handled while constructing
762 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
764 // Expose as a global name.
765 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
768 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
770 DIImportedEntity Module(N);
771 assert(Module.Verify());
772 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
773 constructImportedEntityDIE(TheCU, Module, D);
776 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
777 const MDNode *N, DIE *Context) {
778 DIImportedEntity Module(N);
779 assert(Module.Verify());
780 return constructImportedEntityDIE(TheCU, Module, Context);
783 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
784 const DIImportedEntity &Module,
786 assert(Module.Verify() &&
787 "Use one of the MDNode * overloads to handle invalid metadata");
788 assert(Context && "Should always have a context for an imported_module");
789 DIE *IMDie = TheCU->createAndAddDIE(Module.getTag(), *Context, Module);
791 DIDescriptor Entity = resolve(Module.getEntity());
792 if (Entity.isNameSpace())
793 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
794 else if (Entity.isSubprogram())
795 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
796 else if (Entity.isType())
797 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
799 EntityDie = TheCU->getDIE(Entity);
800 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
801 Module.getContext().getFilename(),
802 Module.getContext().getDirectory());
803 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
804 StringRef Name = Module.getName();
806 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
809 // Emit all Dwarf sections that should come prior to the content. Create
810 // global DIEs and emit initial debug info sections. This is invoked by
811 // the target AsmPrinter.
812 void DwarfDebug::beginModule() {
813 if (DisableDebugInfoPrinting)
816 const Module *M = MMI->getModule();
818 // If module has named metadata anchors then use them, otherwise scan the
819 // module using debug info finder to collect debug info.
820 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
823 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
825 // Emit initial sections so we can reference labels later.
828 SingleCU = CU_Nodes->getNumOperands() == 1;
830 for (MDNode *N : CU_Nodes->operands()) {
831 DICompileUnit CUNode(N);
832 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
833 DIArray ImportedEntities = CUNode.getImportedEntities();
834 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
835 ScopesWithImportedEntities.push_back(std::make_pair(
836 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
837 ImportedEntities.getElement(i)));
838 std::sort(ScopesWithImportedEntities.begin(),
839 ScopesWithImportedEntities.end(), less_first());
840 DIArray GVs = CUNode.getGlobalVariables();
841 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
842 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
843 DIArray SPs = CUNode.getSubprograms();
844 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
845 constructSubprogramDIE(CU, SPs.getElement(i));
846 DIArray EnumTypes = CUNode.getEnumTypes();
847 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
848 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
849 DIArray RetainedTypes = CUNode.getRetainedTypes();
850 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
851 DIType Ty(RetainedTypes.getElement(i));
852 // The retained types array by design contains pointers to
853 // MDNodes rather than DIRefs. Unique them here.
854 DIType UniqueTy(resolve(Ty.getRef()));
855 CU->getOrCreateTypeDIE(UniqueTy);
857 // Emit imported_modules last so that the relevant context is already
859 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
860 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
863 // Tell MMI that we have debug info.
864 MMI->setDebugInfoAvailability(true);
866 // Prime section data.
867 SectionMap[Asm->getObjFileLowering().getTextSection()];
870 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
871 void DwarfDebug::computeInlinedDIEs() {
872 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
873 for (DIE *ISP : InlinedSubprogramDIEs)
874 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
876 for (const auto &AI : AbstractSPDies) {
877 DIE *ISP = AI.second;
878 if (InlinedSubprogramDIEs.count(ISP))
880 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
884 // Collect info for variables that were optimized out.
885 void DwarfDebug::collectDeadVariables() {
886 const Module *M = MMI->getModule();
888 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
889 for (MDNode *N : CU_Nodes->operands()) {
890 DICompileUnit TheCU(N);
891 DIArray Subprograms = TheCU.getSubprograms();
892 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
893 DISubprogram SP(Subprograms.getElement(i));
894 if (ProcessedSPNodes.count(SP) != 0)
896 if (!SP.isSubprogram())
898 if (!SP.isDefinition())
900 DIArray Variables = SP.getVariables();
901 if (Variables.getNumElements() == 0)
904 // Construct subprogram DIE and add variables DIEs.
905 DwarfCompileUnit *SPCU =
906 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
907 assert(SPCU && "Unable to find Compile Unit!");
908 // FIXME: See the comment in constructSubprogramDIE about duplicate
910 constructSubprogramDIE(SPCU, SP);
911 DIE *SPDIE = SPCU->getDIE(SP);
912 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
913 DIVariable DV(Variables.getElement(vi));
914 if (!DV.isVariable())
916 DbgVariable NewVar(DV, NULL, this);
917 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
918 SPDIE->addChild(VariableDIE);
925 void DwarfDebug::finalizeModuleInfo() {
926 // Collect info for variables that were optimized out.
927 collectDeadVariables();
929 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
930 computeInlinedDIEs();
932 // Handle anything that needs to be done on a per-unit basis after
933 // all other generation.
934 for (const auto &TheU : getUnits()) {
935 // Emit DW_AT_containing_type attribute to connect types with their
936 // vtable holding type.
937 TheU->constructContainingTypeDIEs();
939 // Add CU specific attributes if we need to add any.
940 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
941 // If we're splitting the dwarf out now that we've got the entire
942 // CU then add the dwo id to it.
943 DwarfCompileUnit *SkCU =
944 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
945 if (useSplitDwarf()) {
946 // Emit a unique identifier for this CU.
947 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
948 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
949 dwarf::DW_FORM_data8, ID);
950 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
951 dwarf::DW_FORM_data8, ID);
953 // We don't keep track of which addresses are used in which CU so this
954 // is a bit pessimistic under LTO.
955 if (!InfoHolder.getAddrPool()->empty())
956 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
957 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
958 DwarfAddrSectionSym);
959 if (!TheU->getRangeLists().empty())
960 addSectionLabel(Asm, SkCU, SkCU->getUnitDie(),
961 dwarf::DW_AT_GNU_ranges_base,
962 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
965 // If we have code split among multiple sections or non-contiguous
966 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
967 // remain in the .o file, otherwise add a DW_AT_low_pc.
968 // FIXME: We should use ranges allow reordering of code ala
969 // .subsections_via_symbols in mach-o. This would mean turning on
970 // ranges for all subprogram DIEs for mach-o.
971 DwarfCompileUnit &U =
972 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
973 unsigned NumRanges = TheU->getRanges().size();
976 addSectionLabel(Asm, &U, U.getUnitDie(), dwarf::DW_AT_ranges,
977 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
978 DwarfDebugRangeSectionSym);
980 // A DW_AT_low_pc attribute may also be specified in combination with
981 // DW_AT_ranges to specify the default base address for use in
982 // location lists (see Section 2.6.2) and range lists (see Section
984 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
987 RangeSpan &Range = TheU->getRanges().back();
988 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
990 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
997 // Compute DIE offsets and sizes.
998 InfoHolder.computeSizeAndOffsets();
1000 SkeletonHolder.computeSizeAndOffsets();
1003 void DwarfDebug::endSections() {
1004 // Filter labels by section.
1005 for (const SymbolCU &SCU : ArangeLabels) {
1006 if (SCU.Sym->isInSection()) {
1007 // Make a note of this symbol and it's section.
1008 const MCSection *Section = &SCU.Sym->getSection();
1009 if (!Section->getKind().isMetadata())
1010 SectionMap[Section].push_back(SCU);
1012 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1013 // appear in the output. This sucks as we rely on sections to build
1014 // arange spans. We can do it without, but it's icky.
1015 SectionMap[NULL].push_back(SCU);
1019 // Build a list of sections used.
1020 std::vector<const MCSection *> Sections;
1021 for (const auto &it : SectionMap) {
1022 const MCSection *Section = it.first;
1023 Sections.push_back(Section);
1026 // Sort the sections into order.
1027 // This is only done to ensure consistent output order across different runs.
1028 std::sort(Sections.begin(), Sections.end(), SectionSort);
1030 // Add terminating symbols for each section.
1031 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1032 const MCSection *Section = Sections[ID];
1033 MCSymbol *Sym = NULL;
1036 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1037 // if we know the section name up-front. For user-created sections, the
1038 // resulting label may not be valid to use as a label. (section names can
1039 // use a greater set of characters on some systems)
1040 Sym = Asm->GetTempSymbol("debug_end", ID);
1041 Asm->OutStreamer.SwitchSection(Section);
1042 Asm->OutStreamer.EmitLabel(Sym);
1045 // Insert a final terminator.
1046 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1050 // Emit all Dwarf sections that should come after the content.
1051 void DwarfDebug::endModule() {
1058 // End any existing sections.
1059 // TODO: Does this need to happen?
1062 // Finalize the debug info for the module.
1063 finalizeModuleInfo();
1067 // Emit all the DIEs into a debug info section.
1070 // Corresponding abbreviations into a abbrev section.
1071 emitAbbreviations();
1073 // Emit info into a debug aranges section.
1074 if (GenerateARangeSection)
1077 // Emit info into a debug ranges section.
1080 if (useSplitDwarf()) {
1083 emitDebugAbbrevDWO();
1085 // Emit DWO addresses.
1086 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1089 // Emit info into a debug loc section.
1092 // Emit info into the dwarf accelerator table sections.
1093 if (useDwarfAccelTables()) {
1096 emitAccelNamespaces();
1100 // Emit the pubnames and pubtypes sections if requested.
1101 if (HasDwarfPubSections) {
1102 emitDebugPubNames(GenerateGnuPubSections);
1103 emitDebugPubTypes(GenerateGnuPubSections);
1109 // Reset these for the next Module if we have one.
1113 // Find abstract variable, if any, associated with Var.
1114 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1115 DebugLoc ScopeLoc) {
1116 LLVMContext &Ctx = DV->getContext();
1117 // More then one inlined variable corresponds to one abstract variable.
1118 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1119 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1121 return AbsDbgVariable;
1123 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1127 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1128 addScopeVariable(Scope, AbsDbgVariable);
1129 AbstractVariables[Var] = AbsDbgVariable;
1130 return AbsDbgVariable;
1133 // If Var is a current function argument then add it to CurrentFnArguments list.
1134 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1135 if (!LScopes.isCurrentFunctionScope(Scope))
1137 DIVariable DV = Var->getVariable();
1138 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1140 unsigned ArgNo = DV.getArgNumber();
1144 size_t Size = CurrentFnArguments.size();
1146 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1147 // llvm::Function argument size is not good indicator of how many
1148 // arguments does the function have at source level.
1150 CurrentFnArguments.resize(ArgNo * 2);
1151 CurrentFnArguments[ArgNo - 1] = Var;
1155 // Collect variable information from side table maintained by MMI.
1156 void DwarfDebug::collectVariableInfoFromMMITable(
1157 SmallPtrSet<const MDNode *, 16> &Processed) {
1158 for (const auto &VI : MMI->getVariableDbgInfo()) {
1161 Processed.insert(VI.Var);
1162 DIVariable DV(VI.Var);
1163 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1165 // If variable scope is not found then skip this variable.
1169 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1170 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1171 RegVar->setFrameIndex(VI.Slot);
1172 if (!addCurrentFnArgument(RegVar, Scope))
1173 addScopeVariable(Scope, RegVar);
1175 AbsDbgVariable->setFrameIndex(VI.Slot);
1179 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1181 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1182 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1183 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1184 MI->getOperand(0).getReg() &&
1185 (MI->getOperand(1).isImm() ||
1186 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1189 // Get .debug_loc entry for the instruction range starting at MI.
1190 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1191 const MCSymbol *FLabel,
1192 const MCSymbol *SLabel,
1193 const MachineInstr *MI,
1194 DwarfCompileUnit *Unit) {
1195 const MDNode *Var = MI->getDebugVariable();
1197 assert(MI->getNumOperands() == 3);
1198 if (MI->getOperand(0).isReg()) {
1199 MachineLocation MLoc;
1200 // If the second operand is an immediate, this is a
1201 // register-indirect address.
1202 if (!MI->getOperand(1).isImm())
1203 MLoc.set(MI->getOperand(0).getReg());
1205 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1206 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1208 if (MI->getOperand(0).isImm())
1209 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1210 if (MI->getOperand(0).isFPImm())
1211 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1213 if (MI->getOperand(0).isCImm())
1214 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1217 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1220 // Find variables for each lexical scope.
1222 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1224 // Grab the variable info that was squirreled away in the MMI side-table.
1225 collectVariableInfoFromMMITable(Processed);
1227 for (const MDNode *Var : UserVariables) {
1228 if (Processed.count(Var))
1231 // History contains relevant DBG_VALUE instructions for Var and instructions
1233 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1234 if (History.empty())
1236 const MachineInstr *MInsn = History.front();
1239 LexicalScope *Scope = NULL;
1240 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1241 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1242 Scope = LScopes.getCurrentFunctionScope();
1243 else if (MDNode *IA = DV.getInlinedAt())
1244 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1246 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1247 // If variable scope is not found then skip this variable.
1251 Processed.insert(DV);
1252 assert(MInsn->isDebugValue() && "History must begin with debug value");
1253 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1254 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1255 if (!addCurrentFnArgument(RegVar, Scope))
1256 addScopeVariable(Scope, RegVar);
1258 AbsVar->setMInsn(MInsn);
1260 // Simplify ranges that are fully coalesced.
1261 if (History.size() <= 1 ||
1262 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1263 RegVar->setMInsn(MInsn);
1267 // Handle multiple DBG_VALUE instructions describing one variable.
1268 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1270 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1271 DebugLocList &LocList = DotDebugLocEntries.back();
1273 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1274 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1275 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1276 HI = History.begin(),
1279 const MachineInstr *Begin = *HI;
1280 assert(Begin->isDebugValue() && "Invalid History entry");
1282 // Check if DBG_VALUE is truncating a range.
1283 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1284 !Begin->getOperand(0).getReg())
1287 // Compute the range for a register location.
1288 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1289 const MCSymbol *SLabel = 0;
1292 // If Begin is the last instruction in History then its value is valid
1293 // until the end of the function.
1294 SLabel = FunctionEndSym;
1296 const MachineInstr *End = HI[1];
1297 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1298 << "\t" << *Begin << "\t" << *End << "\n");
1299 if (End->isDebugValue())
1300 SLabel = getLabelBeforeInsn(End);
1302 // End is a normal instruction clobbering the range.
1303 SLabel = getLabelAfterInsn(End);
1304 assert(SLabel && "Forgot label after clobber instruction");
1309 // The value is valid until the next DBG_VALUE or clobber.
1310 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1311 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1312 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1313 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1314 DebugLoc.push_back(std::move(Loc));
1318 // Collect info for variables that were optimized out.
1319 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1320 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1321 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1322 DIVariable DV(Variables.getElement(i));
1323 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1325 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1326 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1330 // Return Label preceding the instruction.
1331 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1332 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1333 assert(Label && "Didn't insert label before instruction");
1337 // Return Label immediately following the instruction.
1338 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1339 return LabelsAfterInsn.lookup(MI);
1342 // Process beginning of an instruction.
1343 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1346 // Check if source location changes, but ignore DBG_VALUE locations.
1347 if (!MI->isDebugValue()) {
1348 DebugLoc DL = MI->getDebugLoc();
1349 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1352 if (DL == PrologEndLoc) {
1353 Flags |= DWARF2_FLAG_PROLOGUE_END;
1354 PrologEndLoc = DebugLoc();
1356 if (PrologEndLoc.isUnknown())
1357 Flags |= DWARF2_FLAG_IS_STMT;
1359 if (!DL.isUnknown()) {
1360 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1361 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1363 recordSourceLine(0, 0, 0, 0);
1367 // Insert labels where requested.
1368 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1369 LabelsBeforeInsn.find(MI);
1372 if (I == LabelsBeforeInsn.end())
1375 // Label already assigned.
1380 PrevLabel = MMI->getContext().CreateTempSymbol();
1381 Asm->OutStreamer.EmitLabel(PrevLabel);
1383 I->second = PrevLabel;
1386 // Process end of an instruction.
1387 void DwarfDebug::endInstruction() {
1389 // Don't create a new label after DBG_VALUE instructions.
1390 // They don't generate code.
1391 if (!CurMI->isDebugValue())
1394 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1395 LabelsAfterInsn.find(CurMI);
1399 if (I == LabelsAfterInsn.end())
1402 // Label already assigned.
1406 // We need a label after this instruction.
1408 PrevLabel = MMI->getContext().CreateTempSymbol();
1409 Asm->OutStreamer.EmitLabel(PrevLabel);
1411 I->second = PrevLabel;
1414 // Each LexicalScope has first instruction and last instruction to mark
1415 // beginning and end of a scope respectively. Create an inverse map that list
1416 // scopes starts (and ends) with an instruction. One instruction may start (or
1417 // end) multiple scopes. Ignore scopes that are not reachable.
1418 void DwarfDebug::identifyScopeMarkers() {
1419 SmallVector<LexicalScope *, 4> WorkList;
1420 WorkList.push_back(LScopes.getCurrentFunctionScope());
1421 while (!WorkList.empty()) {
1422 LexicalScope *S = WorkList.pop_back_val();
1424 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1425 if (!Children.empty())
1426 WorkList.append(Children.begin(), Children.end());
1428 if (S->isAbstractScope())
1431 for (const InsnRange &R : S->getRanges()) {
1432 assert(R.first && "InsnRange does not have first instruction!");
1433 assert(R.second && "InsnRange does not have second instruction!");
1434 requestLabelBeforeInsn(R.first);
1435 requestLabelAfterInsn(R.second);
1440 // Gather pre-function debug information. Assumes being called immediately
1441 // after the function entry point has been emitted.
1442 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1445 // If there's no debug info for the function we're not going to do anything.
1446 if (!MMI->hasDebugInfo())
1449 // Grab the lexical scopes for the function, if we don't have any of those
1450 // then we're not going to be able to do anything.
1451 LScopes.initialize(*MF);
1452 if (LScopes.empty())
1455 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1457 // Make sure that each lexical scope will have a begin/end label.
1458 identifyScopeMarkers();
1460 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1461 // belongs to so that we add to the correct per-cu line table in the
1463 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1464 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1465 assert(TheCU && "Unable to find compile unit!");
1466 if (Asm->OutStreamer.hasRawTextSupport())
1467 // Use a single line table if we are generating assembly.
1468 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1470 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1472 // Emit a label for the function so that we have a beginning address.
1473 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1474 // Assumes in correct section after the entry point.
1475 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1477 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1478 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1479 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1481 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1483 bool AtBlockEntry = true;
1484 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1486 const MachineInstr *MI = II;
1488 if (MI->isDebugValue()) {
1489 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1491 // Keep track of user variables.
1492 const MDNode *Var = MI->getDebugVariable();
1494 // Variable is in a register, we need to check for clobbers.
1495 if (isDbgValueInDefinedReg(MI))
1496 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1498 // Check the history of this variable.
1499 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1500 if (History.empty()) {
1501 UserVariables.push_back(Var);
1502 // The first mention of a function argument gets the FunctionBeginSym
1503 // label, so arguments are visible when breaking at function entry.
1505 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1506 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1507 LabelsBeforeInsn[MI] = FunctionBeginSym;
1509 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1510 const MachineInstr *Prev = History.back();
1511 if (Prev->isDebugValue()) {
1512 // Coalesce identical entries at the end of History.
1513 if (History.size() >= 2 &&
1514 Prev->isIdenticalTo(History[History.size() - 2])) {
1515 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1516 << "\t" << *Prev << "\t"
1517 << *History[History.size() - 2] << "\n");
1521 // Terminate old register assignments that don't reach MI;
1522 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1523 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1524 isDbgValueInDefinedReg(Prev)) {
1525 // Previous register assignment needs to terminate at the end of
1527 MachineBasicBlock::const_iterator LastMI =
1528 PrevMBB->getLastNonDebugInstr();
1529 if (LastMI == PrevMBB->end()) {
1530 // Drop DBG_VALUE for empty range.
1531 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1532 << "\t" << *Prev << "\n");
1534 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1535 // Terminate after LastMI.
1536 History.push_back(LastMI);
1540 History.push_back(MI);
1542 // Not a DBG_VALUE instruction.
1543 if (!MI->isPosition())
1544 AtBlockEntry = false;
1546 // First known non-DBG_VALUE and non-frame setup location marks
1547 // the beginning of the function body.
1548 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1549 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1550 PrologEndLoc = MI->getDebugLoc();
1552 // Check if the instruction clobbers any registers with debug vars.
1553 for (const MachineOperand &MO : MI->operands()) {
1554 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1556 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1559 const MDNode *Var = LiveUserVar[Reg];
1562 // Reg is now clobbered.
1563 LiveUserVar[Reg] = 0;
1565 // Was MD last defined by a DBG_VALUE referring to Reg?
1566 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1567 if (HistI == DbgValues.end())
1569 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1570 if (History.empty())
1572 const MachineInstr *Prev = History.back();
1573 // Sanity-check: Register assignments are terminated at the end of
1575 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1577 // Is the variable still in Reg?
1578 if (!isDbgValueInDefinedReg(Prev) ||
1579 Prev->getOperand(0).getReg() != Reg)
1581 // Var is clobbered. Make sure the next instruction gets a label.
1582 History.push_back(MI);
1589 for (auto &I : DbgValues) {
1590 SmallVectorImpl<const MachineInstr *> &History = I.second;
1591 if (History.empty())
1594 // Make sure the final register assignments are terminated.
1595 const MachineInstr *Prev = History.back();
1596 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1597 const MachineBasicBlock *PrevMBB = Prev->getParent();
1598 MachineBasicBlock::const_iterator LastMI =
1599 PrevMBB->getLastNonDebugInstr();
1600 if (LastMI == PrevMBB->end())
1601 // Drop DBG_VALUE for empty range.
1603 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1604 // Terminate after LastMI.
1605 History.push_back(LastMI);
1608 // Request labels for the full history.
1609 for (const MachineInstr *MI : History) {
1610 if (MI->isDebugValue())
1611 requestLabelBeforeInsn(MI);
1613 requestLabelAfterInsn(MI);
1617 PrevInstLoc = DebugLoc();
1618 PrevLabel = FunctionBeginSym;
1620 // Record beginning of function.
1621 if (!PrologEndLoc.isUnknown()) {
1622 DebugLoc FnStartDL =
1623 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1625 FnStartDL.getLine(), FnStartDL.getCol(),
1626 FnStartDL.getScope(MF->getFunction()->getContext()),
1627 // We'd like to list the prologue as "not statements" but GDB behaves
1628 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1629 DWARF2_FLAG_IS_STMT);
1633 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1634 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1635 DIVariable DV = Var->getVariable();
1636 // Variables with positive arg numbers are parameters.
1637 if (unsigned ArgNum = DV.getArgNumber()) {
1638 // Keep all parameters in order at the start of the variable list to ensure
1639 // function types are correct (no out-of-order parameters)
1641 // This could be improved by only doing it for optimized builds (unoptimized
1642 // builds have the right order to begin with), searching from the back (this
1643 // would catch the unoptimized case quickly), or doing a binary search
1644 // rather than linear search.
1645 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1646 while (I != Vars.end()) {
1647 unsigned CurNum = (*I)->getVariable().getArgNumber();
1648 // A local (non-parameter) variable has been found, insert immediately
1652 // A later indexed parameter has been found, insert immediately before it.
1653 if (CurNum > ArgNum)
1657 Vars.insert(I, Var);
1661 Vars.push_back(Var);
1664 // Gather and emit post-function debug information.
1665 void DwarfDebug::endFunction(const MachineFunction *MF) {
1666 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1667 // though the beginFunction may not be called at all.
1668 // We should handle both cases.
1672 assert(CurFn == MF);
1675 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1676 // If we don't have a lexical scope for this function then there will
1677 // be a hole in the range information. Keep note of this by setting the
1678 // previously used section to nullptr.
1679 PrevSection = nullptr;
1685 // Define end label for subprogram.
1686 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1687 // Assumes in correct section after the entry point.
1688 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1690 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1691 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1693 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1694 collectVariableInfo(ProcessedVars);
1696 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1697 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1698 assert(TheCU && "Unable to find compile unit!");
1700 // Construct abstract scopes.
1701 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1702 DISubprogram SP(AScope->getScopeNode());
1703 if (SP.isSubprogram()) {
1704 // Collect info for variables that were optimized out.
1705 DIArray Variables = SP.getVariables();
1706 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1707 DIVariable DV(Variables.getElement(i));
1708 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1710 // Check that DbgVariable for DV wasn't created earlier, when
1711 // findAbstractVariable() was called for inlined instance of DV.
1712 LLVMContext &Ctx = DV->getContext();
1713 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1714 if (AbstractVariables.lookup(CleanDV))
1716 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1717 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1720 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1721 constructScopeDIE(TheCU, AScope);
1724 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1725 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1726 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1728 // Add the range of this function to the list of ranges for the CU.
1729 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1730 TheCU->addRange(std::move(Span));
1731 PrevSection = Asm->getCurrentSection();
1735 for (auto &I : ScopeVariables)
1736 DeleteContainerPointers(I.second);
1737 ScopeVariables.clear();
1738 DeleteContainerPointers(CurrentFnArguments);
1739 UserVariables.clear();
1741 AbstractVariables.clear();
1742 LabelsBeforeInsn.clear();
1743 LabelsAfterInsn.clear();
1748 // Register a source line with debug info. Returns the unique label that was
1749 // emitted and which provides correspondence to the source line list.
1750 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1755 unsigned Discriminator = 0;
1757 DIDescriptor Scope(S);
1759 if (Scope.isCompileUnit()) {
1760 DICompileUnit CU(S);
1761 Fn = CU.getFilename();
1762 Dir = CU.getDirectory();
1763 } else if (Scope.isFile()) {
1765 Fn = F.getFilename();
1766 Dir = F.getDirectory();
1767 } else if (Scope.isSubprogram()) {
1769 Fn = SP.getFilename();
1770 Dir = SP.getDirectory();
1771 } else if (Scope.isLexicalBlockFile()) {
1772 DILexicalBlockFile DBF(S);
1773 Fn = DBF.getFilename();
1774 Dir = DBF.getDirectory();
1775 } else if (Scope.isLexicalBlock()) {
1776 DILexicalBlock DB(S);
1777 Fn = DB.getFilename();
1778 Dir = DB.getDirectory();
1779 Discriminator = DB.getDiscriminator();
1781 llvm_unreachable("Unexpected scope info");
1783 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1784 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1785 .getOrCreateSourceID(Fn, Dir);
1787 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1791 //===----------------------------------------------------------------------===//
1793 //===----------------------------------------------------------------------===//
1795 // Compute the size and offset of a DIE. The offset is relative to start of the
1796 // CU. It returns the offset after laying out the DIE.
1797 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) {
1798 // Record the abbreviation.
1799 assignAbbrevNumber(Die.getAbbrev());
1801 // Get the abbreviation for this DIE.
1802 const DIEAbbrev &Abbrev = Die.getAbbrev();
1805 Die.setOffset(Offset);
1807 // Start the size with the size of abbreviation code.
1808 Offset += getULEB128Size(Die.getAbbrevNumber());
1810 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1811 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1813 // Size the DIE attribute values.
1814 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1815 // Size attribute value.
1816 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1818 // Get the children.
1819 const auto &Children = Die.getChildren();
1821 // Size the DIE children if any.
1822 if (!Children.empty()) {
1823 assert(Abbrev.hasChildren() && "Children flag not set");
1825 for (auto &Child : Children)
1826 Offset = computeSizeAndOffset(*Child, Offset);
1828 // End of children marker.
1829 Offset += sizeof(int8_t);
1832 Die.setSize(Offset - Die.getOffset());
1836 // Compute the size and offset for each DIE.
1837 void DwarfFile::computeSizeAndOffsets() {
1838 // Offset from the first CU in the debug info section is 0 initially.
1839 unsigned SecOffset = 0;
1841 // Iterate over each compile unit and set the size and offsets for each
1842 // DIE within each compile unit. All offsets are CU relative.
1843 for (const auto &TheU : CUs) {
1844 TheU->setDebugInfoOffset(SecOffset);
1846 // CU-relative offset is reset to 0 here.
1847 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1848 TheU->getHeaderSize(); // Unit-specific headers
1850 // EndOffset here is CU-relative, after laying out
1851 // all of the CU DIE.
1852 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset);
1853 SecOffset += EndOffset;
1857 // Emit initial Dwarf sections with a label at the start of each one.
1858 void DwarfDebug::emitSectionLabels() {
1859 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1861 // Dwarf sections base addresses.
1862 DwarfInfoSectionSym =
1863 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1864 if (useSplitDwarf())
1865 DwarfInfoDWOSectionSym =
1866 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1867 DwarfAbbrevSectionSym =
1868 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1869 if (useSplitDwarf())
1870 DwarfAbbrevDWOSectionSym = emitSectionSym(
1871 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1872 if (GenerateARangeSection)
1873 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1875 DwarfLineSectionSym =
1876 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1877 if (GenerateGnuPubSections) {
1878 DwarfGnuPubNamesSectionSym =
1879 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1880 DwarfGnuPubTypesSectionSym =
1881 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1882 } else if (HasDwarfPubSections) {
1883 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1884 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1887 DwarfStrSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1889 if (useSplitDwarf()) {
1890 DwarfStrDWOSectionSym =
1891 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1892 DwarfAddrSectionSym =
1893 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1894 DwarfDebugLocSectionSym =
1895 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1897 DwarfDebugLocSectionSym =
1898 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1899 DwarfDebugRangeSectionSym =
1900 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1903 // Recursively emits a debug information entry.
1904 void DwarfDebug::emitDIE(DIE &Die) {
1905 // Get the abbreviation for this DIE.
1906 const DIEAbbrev &Abbrev = Die.getAbbrev();
1908 // Emit the code (index) for the abbreviation.
1909 if (Asm->isVerbose())
1910 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1911 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1912 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1913 dwarf::TagString(Abbrev.getTag()));
1914 Asm->EmitULEB128(Abbrev.getNumber());
1916 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1917 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1919 // Emit the DIE attribute values.
1920 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1921 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1922 dwarf::Form Form = AbbrevData[i].getForm();
1923 assert(Form && "Too many attributes for DIE (check abbreviation)");
1925 if (Asm->isVerbose()) {
1926 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1927 if (Attr == dwarf::DW_AT_accessibility)
1928 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1929 cast<DIEInteger>(Values[i])->getValue()));
1932 // Emit an attribute using the defined form.
1933 Values[i]->EmitValue(Asm, Form);
1936 // Emit the DIE children if any.
1937 if (Abbrev.hasChildren()) {
1938 for (auto &Child : Die.getChildren())
1941 Asm->OutStreamer.AddComment("End Of Children Mark");
1946 // Emit the various dwarf units to the unit section USection with
1947 // the abbreviations going into ASection.
1948 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) {
1949 for (const auto &TheU : CUs) {
1950 DIE *Die = TheU->getUnitDie();
1951 const MCSection *USection = TheU->getSection();
1952 Asm->OutStreamer.SwitchSection(USection);
1954 // Emit the compile units header.
1955 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1957 // Emit size of content not including length itself
1958 Asm->OutStreamer.AddComment("Length of Unit");
1959 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1961 TheU->emitHeader(ASectionSym);
1964 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1968 // Emit the debug info section.
1969 void DwarfDebug::emitDebugInfo() {
1970 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1972 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1975 // Emit the abbreviation section.
1976 void DwarfDebug::emitAbbreviations() {
1977 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1979 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1982 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1983 // Check to see if it is worth the effort.
1984 if (!Abbreviations.empty()) {
1985 // Start the debug abbrev section.
1986 Asm->OutStreamer.SwitchSection(Section);
1988 // For each abbrevation.
1989 for (const DIEAbbrev *Abbrev : Abbreviations) {
1990 // Emit the abbrevations code (base 1 index.)
1991 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1993 // Emit the abbreviations data.
1997 // Mark end of abbreviations.
1998 Asm->EmitULEB128(0, "EOM(3)");
2002 // Emit the last address of the section and the end of the line matrix.
2003 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2004 // Define last address of section.
2005 Asm->OutStreamer.AddComment("Extended Op");
2008 Asm->OutStreamer.AddComment("Op size");
2009 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2010 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2011 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2013 Asm->OutStreamer.AddComment("Section end label");
2015 Asm->OutStreamer.EmitSymbolValue(
2016 Asm->GetTempSymbol("section_end", SectionEnd),
2017 Asm->getDataLayout().getPointerSize());
2019 // Mark end of matrix.
2020 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2026 // Emit visible names into a hashed accelerator table section.
2027 void DwarfDebug::emitAccelNames() {
2029 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2030 for (const auto &TheU : getUnits()) {
2031 for (const auto &GI : TheU->getAccelNames()) {
2032 StringRef Name = GI.getKey();
2033 for (const DIE *D : GI.second)
2034 AT.AddName(Name, D);
2038 AT.FinalizeTable(Asm, "Names");
2039 Asm->OutStreamer.SwitchSection(
2040 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2041 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2042 Asm->OutStreamer.EmitLabel(SectionBegin);
2044 // Emit the full data.
2045 AT.Emit(Asm, SectionBegin, &InfoHolder);
2048 // Emit objective C classes and categories into a hashed accelerator table
2050 void DwarfDebug::emitAccelObjC() {
2052 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2053 for (const auto &TheU : getUnits()) {
2054 for (const auto &GI : TheU->getAccelObjC()) {
2055 StringRef Name = GI.getKey();
2056 for (const DIE *D : GI.second)
2057 AT.AddName(Name, D);
2061 AT.FinalizeTable(Asm, "ObjC");
2062 Asm->OutStreamer.SwitchSection(
2063 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2064 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2065 Asm->OutStreamer.EmitLabel(SectionBegin);
2067 // Emit the full data.
2068 AT.Emit(Asm, SectionBegin, &InfoHolder);
2071 // Emit namespace dies into a hashed accelerator table.
2072 void DwarfDebug::emitAccelNamespaces() {
2074 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2075 for (const auto &TheU : getUnits()) {
2076 for (const auto &GI : TheU->getAccelNamespace()) {
2077 StringRef Name = GI.getKey();
2078 for (const DIE *D : GI.second)
2079 AT.AddName(Name, D);
2083 AT.FinalizeTable(Asm, "namespac");
2084 Asm->OutStreamer.SwitchSection(
2085 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2086 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2087 Asm->OutStreamer.EmitLabel(SectionBegin);
2089 // Emit the full data.
2090 AT.Emit(Asm, SectionBegin, &InfoHolder);
2093 // Emit type dies into a hashed accelerator table.
2094 void DwarfDebug::emitAccelTypes() {
2095 std::vector<DwarfAccelTable::Atom> Atoms;
2097 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2099 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2101 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2102 DwarfAccelTable AT(Atoms);
2103 for (const auto &TheU : getUnits()) {
2104 for (const auto &GI : TheU->getAccelTypes()) {
2105 StringRef Name = GI.getKey();
2106 for (const auto &DI : GI.second)
2107 AT.AddName(Name, DI.first, DI.second);
2111 AT.FinalizeTable(Asm, "types");
2112 Asm->OutStreamer.SwitchSection(
2113 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2114 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2115 Asm->OutStreamer.EmitLabel(SectionBegin);
2117 // Emit the full data.
2118 AT.Emit(Asm, SectionBegin, &InfoHolder);
2121 // Public name handling.
2122 // The format for the various pubnames:
2124 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2125 // for the DIE that is named.
2127 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2128 // into the CU and the index value is computed according to the type of value
2129 // for the DIE that is named.
2131 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2132 // it's the offset within the debug_info/debug_types dwo section, however, the
2133 // reference in the pubname header doesn't change.
2135 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2136 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2138 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2140 // We could have a specification DIE that has our most of our knowledge,
2141 // look for that now.
2142 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2144 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2145 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2146 Linkage = dwarf::GIEL_EXTERNAL;
2147 } else if (Die->findAttribute(dwarf::DW_AT_external))
2148 Linkage = dwarf::GIEL_EXTERNAL;
2150 switch (Die->getTag()) {
2151 case dwarf::DW_TAG_class_type:
2152 case dwarf::DW_TAG_structure_type:
2153 case dwarf::DW_TAG_union_type:
2154 case dwarf::DW_TAG_enumeration_type:
2155 return dwarf::PubIndexEntryDescriptor(
2156 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2157 ? dwarf::GIEL_STATIC
2158 : dwarf::GIEL_EXTERNAL);
2159 case dwarf::DW_TAG_typedef:
2160 case dwarf::DW_TAG_base_type:
2161 case dwarf::DW_TAG_subrange_type:
2162 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2163 case dwarf::DW_TAG_namespace:
2164 return dwarf::GIEK_TYPE;
2165 case dwarf::DW_TAG_subprogram:
2166 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2167 case dwarf::DW_TAG_constant:
2168 case dwarf::DW_TAG_variable:
2169 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2170 case dwarf::DW_TAG_enumerator:
2171 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2172 dwarf::GIEL_STATIC);
2174 return dwarf::GIEK_NONE;
2178 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2180 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2181 const MCSection *PSec =
2182 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2183 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2185 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2188 void DwarfDebug::emitDebugPubSection(
2189 bool GnuStyle, const MCSection *PSec, StringRef Name,
2190 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2191 for (const auto &NU : CUMap) {
2192 DwarfCompileUnit *TheU = NU.second;
2194 const auto &Globals = (TheU->*Accessor)();
2196 if (Globals.empty())
2199 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2201 unsigned ID = TheU->getUniqueID();
2203 // Start the dwarf pubnames section.
2204 Asm->OutStreamer.SwitchSection(PSec);
2207 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2208 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2209 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2210 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2212 Asm->OutStreamer.EmitLabel(BeginLabel);
2214 Asm->OutStreamer.AddComment("DWARF Version");
2215 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2217 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2218 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2220 Asm->OutStreamer.AddComment("Compilation Unit Length");
2221 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2223 // Emit the pubnames for this compilation unit.
2224 for (const auto &GI : Globals) {
2225 const char *Name = GI.getKeyData();
2226 const DIE *Entity = GI.second;
2228 Asm->OutStreamer.AddComment("DIE offset");
2229 Asm->EmitInt32(Entity->getOffset());
2232 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2233 Asm->OutStreamer.AddComment(
2234 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2235 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2236 Asm->EmitInt8(Desc.toBits());
2239 Asm->OutStreamer.AddComment("External Name");
2240 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2243 Asm->OutStreamer.AddComment("End Mark");
2245 Asm->OutStreamer.EmitLabel(EndLabel);
2249 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2250 const MCSection *PSec =
2251 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2252 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2254 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2257 // Emit strings into a string section.
2258 void DwarfFile::emitStrings(const MCSection *StrSection,
2259 const MCSection *OffsetSection = NULL,
2260 const MCSymbol *StrSecSym = NULL) {
2262 if (StringPool.empty())
2265 // Start the dwarf str section.
2266 Asm->OutStreamer.SwitchSection(StrSection);
2268 // Get all of the string pool entries and put them in an array by their ID so
2269 // we can sort them.
2270 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2272 for (const auto &I : StringPool)
2273 Entries.push_back(std::make_pair(I.second.second, &I));
2275 array_pod_sort(Entries.begin(), Entries.end());
2277 for (const auto &Entry : Entries) {
2278 // Emit a label for reference from debug information entries.
2279 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2281 // Emit the string itself with a terminating null byte.
2282 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2283 Entry.second->getKeyLength() + 1));
2286 // If we've got an offset section go ahead and emit that now as well.
2287 if (OffsetSection) {
2288 Asm->OutStreamer.SwitchSection(OffsetSection);
2289 unsigned offset = 0;
2290 unsigned size = 4; // FIXME: DWARF64 is 8.
2291 for (const auto &Entry : Entries) {
2292 Asm->OutStreamer.EmitIntValue(offset, size);
2293 offset += Entry.second->getKeyLength() + 1;
2298 // Emit addresses into the section given.
2299 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2301 if (AddressPool.empty())
2304 // Start the dwarf addr section.
2305 Asm->OutStreamer.SwitchSection(AddrSection);
2307 // Order the address pool entries by ID
2308 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2310 for (const auto &I : AddressPool)
2311 Entries[I.second.Number] =
2313 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2314 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2316 for (const MCExpr *Entry : Entries)
2317 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2320 // Emit visible names into a debug str section.
2321 void DwarfDebug::emitDebugStr() {
2322 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2323 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2326 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2327 const DebugLocEntry &Entry) {
2328 DIVariable DV(Entry.getVariable());
2329 if (Entry.isInt()) {
2330 DIBasicType BTy(resolve(DV.getType()));
2331 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2332 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2333 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2334 Streamer.EmitSLEB128(Entry.getInt());
2336 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2337 Streamer.EmitULEB128(Entry.getInt());
2339 } else if (Entry.isLocation()) {
2340 MachineLocation Loc = Entry.getLoc();
2341 if (!DV.hasComplexAddress())
2343 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2345 // Complex address entry.
2346 unsigned N = DV.getNumAddrElements();
2348 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2349 if (Loc.getOffset()) {
2351 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2352 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2353 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2354 Streamer.EmitSLEB128(DV.getAddrElement(1));
2356 // If first address element is OpPlus then emit
2357 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2358 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2359 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2363 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2366 // Emit remaining complex address elements.
2367 for (; i < N; ++i) {
2368 uint64_t Element = DV.getAddrElement(i);
2369 if (Element == DIBuilder::OpPlus) {
2370 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2371 Streamer.EmitULEB128(DV.getAddrElement(++i));
2372 } else if (Element == DIBuilder::OpDeref) {
2374 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2376 llvm_unreachable("unknown Opcode found in complex address");
2380 // else ... ignore constant fp. There is not any good way to
2381 // to represent them here in dwarf.
2385 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2386 Asm->OutStreamer.AddComment("Loc expr size");
2387 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2388 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2389 Asm->EmitLabelDifference(end, begin, 2);
2390 Asm->OutStreamer.EmitLabel(begin);
2392 APByteStreamer Streamer(*Asm);
2393 emitDebugLocEntry(Streamer, Entry);
2395 Asm->OutStreamer.EmitLabel(end);
2398 // Emit locations into the debug loc section.
2399 void DwarfDebug::emitDebugLoc() {
2400 // Start the dwarf loc section.
2401 Asm->OutStreamer.SwitchSection(
2402 Asm->getObjFileLowering().getDwarfLocSection());
2403 unsigned char Size = Asm->getDataLayout().getPointerSize();
2404 for (const auto &DebugLoc : DotDebugLocEntries) {
2405 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2406 for (const auto &Entry : DebugLoc.List) {
2407 // Set up the range. This range is relative to the entry point of the
2408 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2409 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2410 const DwarfCompileUnit *CU = Entry.getCU();
2411 if (CU->getRanges().size() == 1) {
2412 // Grab the begin symbol from the first range as our base.
2413 const MCSymbol *Base = CU->getRanges()[0].getStart();
2414 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2415 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2417 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2418 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2421 emitDebugLocEntryLocation(Entry);
2423 Asm->OutStreamer.EmitIntValue(0, Size);
2424 Asm->OutStreamer.EmitIntValue(0, Size);
2428 void DwarfDebug::emitDebugLocDWO() {
2429 Asm->OutStreamer.SwitchSection(
2430 Asm->getObjFileLowering().getDwarfLocDWOSection());
2431 for (const auto &DebugLoc : DotDebugLocEntries) {
2432 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2433 for (const auto &Entry : DebugLoc.List) {
2434 // Just always use start_length for now - at least that's one address
2435 // rather than two. We could get fancier and try to, say, reuse an
2436 // address we know we've emitted elsewhere (the start of the function?
2437 // The start of the CU or CU subrange that encloses this range?)
2438 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2439 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2440 Asm->EmitULEB128(idx);
2441 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2443 emitDebugLocEntryLocation(Entry);
2445 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2450 const MCSymbol *Start, *End;
2453 // Emit a debug aranges section, containing a CU lookup for any
2454 // address we can tie back to a CU.
2455 void DwarfDebug::emitDebugARanges() {
2456 // Start the dwarf aranges section.
2457 Asm->OutStreamer.SwitchSection(
2458 Asm->getObjFileLowering().getDwarfARangesSection());
2460 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2464 // Build a list of sections used.
2465 std::vector<const MCSection *> Sections;
2466 for (const auto &it : SectionMap) {
2467 const MCSection *Section = it.first;
2468 Sections.push_back(Section);
2471 // Sort the sections into order.
2472 // This is only done to ensure consistent output order across different runs.
2473 std::sort(Sections.begin(), Sections.end(), SectionSort);
2475 // Build a set of address spans, sorted by CU.
2476 for (const MCSection *Section : Sections) {
2477 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2478 if (List.size() < 2)
2481 // Sort the symbols by offset within the section.
2482 std::sort(List.begin(), List.end(),
2483 [&](const SymbolCU &A, const SymbolCU &B) {
2484 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2485 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2487 // Symbols with no order assigned should be placed at the end.
2488 // (e.g. section end labels)
2496 // If we have no section (e.g. common), just write out
2497 // individual spans for each symbol.
2498 if (Section == NULL) {
2499 for (const SymbolCU &Cur : List) {
2501 Span.Start = Cur.Sym;
2504 Spans[Cur.CU].push_back(Span);
2507 // Build spans between each label.
2508 const MCSymbol *StartSym = List[0].Sym;
2509 for (size_t n = 1, e = List.size(); n < e; n++) {
2510 const SymbolCU &Prev = List[n - 1];
2511 const SymbolCU &Cur = List[n];
2513 // Try and build the longest span we can within the same CU.
2514 if (Cur.CU != Prev.CU) {
2516 Span.Start = StartSym;
2518 Spans[Prev.CU].push_back(Span);
2525 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2527 // Build a list of CUs used.
2528 std::vector<DwarfCompileUnit *> CUs;
2529 for (const auto &it : Spans) {
2530 DwarfCompileUnit *CU = it.first;
2534 // Sort the CU list (again, to ensure consistent output order).
2535 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2536 return A->getUniqueID() < B->getUniqueID();
2539 // Emit an arange table for each CU we used.
2540 for (DwarfCompileUnit *CU : CUs) {
2541 std::vector<ArangeSpan> &List = Spans[CU];
2543 // Emit size of content not including length itself.
2544 unsigned ContentSize =
2545 sizeof(int16_t) + // DWARF ARange version number
2546 sizeof(int32_t) + // Offset of CU in the .debug_info section
2547 sizeof(int8_t) + // Pointer Size (in bytes)
2548 sizeof(int8_t); // Segment Size (in bytes)
2550 unsigned TupleSize = PtrSize * 2;
2552 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2554 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2556 ContentSize += Padding;
2557 ContentSize += (List.size() + 1) * TupleSize;
2559 // For each compile unit, write the list of spans it covers.
2560 Asm->OutStreamer.AddComment("Length of ARange Set");
2561 Asm->EmitInt32(ContentSize);
2562 Asm->OutStreamer.AddComment("DWARF Arange version number");
2563 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2564 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2565 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2566 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2567 Asm->EmitInt8(PtrSize);
2568 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2571 Asm->OutStreamer.EmitFill(Padding, 0xff);
2573 for (const ArangeSpan &Span : List) {
2574 Asm->EmitLabelReference(Span.Start, PtrSize);
2576 // Calculate the size as being from the span start to it's end.
2578 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2580 // For symbols without an end marker (e.g. common), we
2581 // write a single arange entry containing just that one symbol.
2582 uint64_t Size = SymSize[Span.Start];
2586 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2590 Asm->OutStreamer.AddComment("ARange terminator");
2591 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2592 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2596 // Emit visible names into a debug ranges section.
2597 void DwarfDebug::emitDebugRanges() {
2598 // Start the dwarf ranges section.
2599 Asm->OutStreamer.SwitchSection(
2600 Asm->getObjFileLowering().getDwarfRangesSection());
2602 // Size for our labels.
2603 unsigned char Size = Asm->getDataLayout().getPointerSize();
2605 // Grab the specific ranges for the compile units in the module.
2606 for (const auto &I : CUMap) {
2607 DwarfCompileUnit *TheCU = I.second;
2609 // Emit a symbol so we can find the beginning of our ranges.
2610 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2612 // Iterate over the misc ranges for the compile units in the module.
2613 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2614 // Emit our symbol so we can find the beginning of the range.
2615 Asm->OutStreamer.EmitLabel(List.getSym());
2617 for (const RangeSpan &Range : List.getRanges()) {
2618 const MCSymbol *Begin = Range.getStart();
2619 const MCSymbol *End = Range.getEnd();
2620 assert(Begin && "Range without a begin symbol?");
2621 assert(End && "Range without an end symbol?");
2622 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2623 Asm->OutStreamer.EmitSymbolValue(End, Size);
2626 // And terminate the list with two 0 values.
2627 Asm->OutStreamer.EmitIntValue(0, Size);
2628 Asm->OutStreamer.EmitIntValue(0, Size);
2631 // Now emit a range for the CU itself.
2632 if (TheCU->getRanges().size() > 1) {
2633 Asm->OutStreamer.EmitLabel(
2634 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2635 for (const RangeSpan &Range : TheCU->getRanges()) {
2636 const MCSymbol *Begin = Range.getStart();
2637 const MCSymbol *End = Range.getEnd();
2638 assert(Begin && "Range without a begin symbol?");
2639 assert(End && "Range without an end symbol?");
2640 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2641 Asm->OutStreamer.EmitSymbolValue(End, Size);
2643 // And terminate the list with two 0 values.
2644 Asm->OutStreamer.EmitIntValue(0, Size);
2645 Asm->OutStreamer.EmitIntValue(0, Size);
2650 // DWARF5 Experimental Separate Dwarf emitters.
2652 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2654 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2655 U->getCUNode().getSplitDebugFilename());
2657 if (!CompilationDir.empty())
2658 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2660 addGnuPubAttributes(NewU, Die);
2662 SkeletonHolder.addUnit(NewU);
2665 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2666 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2667 // DW_AT_addr_base, DW_AT_ranges_base.
2668 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2670 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2671 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2672 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2673 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2674 DwarfInfoSectionSym);
2676 NewCU->initStmtList(DwarfLineSectionSym);
2678 initSkeletonUnit(CU, Die, NewCU);
2683 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2685 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2686 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2687 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2689 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2690 DwarfTypeUnit *NewTU =
2691 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2692 NewTU->setTypeSignature(TU->getTypeSignature());
2693 NewTU->setType(NULL);
2695 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2697 initSkeletonUnit(TU, Die, NewTU);
2701 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2702 // compile units that would normally be in debug_info.
2703 void DwarfDebug::emitDebugInfoDWO() {
2704 assert(useSplitDwarf() && "No split dwarf debug info?");
2705 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2706 // emit relocations into the dwo file.
2707 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2710 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2711 // abbreviations for the .debug_info.dwo section.
2712 void DwarfDebug::emitDebugAbbrevDWO() {
2713 assert(useSplitDwarf() && "No split dwarf?");
2714 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2717 void DwarfDebug::emitDebugLineDWO() {
2718 assert(useSplitDwarf() && "No split dwarf?");
2719 Asm->OutStreamer.SwitchSection(
2720 Asm->getObjFileLowering().getDwarfLineDWOSection());
2721 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2724 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2725 // string section and is identical in format to traditional .debug_str
2727 void DwarfDebug::emitDebugStrDWO() {
2728 assert(useSplitDwarf() && "No split dwarf?");
2729 const MCSection *OffSec =
2730 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2731 const MCSymbol *StrSym = DwarfStrSectionSym;
2732 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2736 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2737 if (!useSplitDwarf())
2740 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2741 return &SplitTypeUnitFileTable;
2744 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2745 StringRef Identifier, DIE *RefDie,
2746 DICompositeType CTy) {
2747 // Flag the type unit reference as a declaration so that if it contains
2748 // members (implicit special members, static data member definitions, member
2749 // declarations for definitions in this CU, etc) consumers don't get confused
2750 // and think this is a full definition.
2751 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2753 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2755 CU.addDIETypeSignature(RefDie, *TU);
2759 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2760 DwarfTypeUnit *NewTU =
2761 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, CU, Asm, this,
2762 &InfoHolder, getDwoLineTable(CU));
2764 InfoHolder.addUnit(NewTU);
2766 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2770 Hash.update(Identifier);
2771 // ... take the least significant 8 bytes and return those. Our MD5
2772 // implementation always returns its results in little endian, swap bytes
2774 MD5::MD5Result Result;
2776 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2777 NewTU->setTypeSignature(Signature);
2778 if (useSplitDwarf())
2779 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2781 CU.applyStmtList(*UnitDie);
2783 NewTU->setType(NewTU->createTypeDIE(CTy));
2787 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2788 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2790 CU.addDIETypeSignature(RefDie, *NewTU);
2793 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2794 MCSymbol *Begin, MCSymbol *End) {
2795 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2796 if (DwarfVersion < 4)
2797 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2799 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);