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(std::unique_ptr<DwarfUnit> U) {
284 CUs.push_back(std::move(U));
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.
376 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
377 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
379 DISubprogram SPDecl = SP.getFunctionDeclaration();
380 if (!SPDecl.isSubprogram()) {
381 // There is not any need to generate specification DIE for a function
382 // defined at compile unit level. If a function is defined inside another
383 // function then gdb prefers the definition at top level and but does not
384 // expect specification DIE in parent function. So avoid creating
385 // specification DIE for a function defined inside a function.
386 DIScope SPContext = resolve(SP.getContext());
387 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
388 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
389 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
392 DICompositeType SPTy = SP.getType();
393 DIArray Args = SPTy.getTypeArray();
394 uint16_t SPTag = SPTy.getTag();
395 if (SPTag == dwarf::DW_TAG_subroutine_type)
396 SPCU.constructSubprogramArguments(*SPDie, Args);
397 DIE *SPDeclDie = SPDie;
399 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
400 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
405 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
407 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
408 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
409 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
411 // Add name to the name table, we do this here because we're guaranteed
412 // to have concrete versions of our DW_TAG_subprogram nodes.
413 addSubprogramNames(SPCU, SP, SPDie);
418 /// Check whether we should create a DIE for the given Scope, return true
419 /// if we don't create a DIE (the corresponding DIE is null).
420 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
421 if (Scope->isAbstractScope())
424 // We don't create a DIE if there is no Range.
425 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
429 if (Ranges.size() > 1)
432 // We don't create a DIE if we have a single Range and the end label
434 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
435 MCSymbol *End = getLabelAfterInsn(RI->second);
439 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
440 dwarf::Attribute A, const MCSymbol *L,
441 const MCSymbol *Sec) {
442 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
443 U.addSectionLabel(D, A, L);
445 U.addSectionDelta(D, A, L, Sec);
448 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
449 const SmallVectorImpl<InsnRange> &Range) {
450 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
451 // emitting it appropriately.
452 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
454 // Under fission, ranges are specified by constant offsets relative to the
455 // CU's DW_AT_GNU_ranges_base.
457 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
458 DwarfDebugRangeSectionSym);
460 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
461 DwarfDebugRangeSectionSym);
463 RangeSpanList List(RangeSym);
464 for (const InsnRange &R : Range) {
465 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
466 List.addRange(std::move(Span));
469 // Add the range list to the set of ranges to be emitted.
470 TheCU.addRangeList(std::move(List));
473 // Construct new DW_TAG_lexical_block for this scope and attach
474 // DW_AT_low_pc/DW_AT_high_pc labels.
475 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
476 LexicalScope *Scope) {
477 if (isLexicalScopeDIENull(Scope))
480 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
481 if (Scope->isAbstractScope())
484 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
486 // If we have multiple ranges, emit them into the range section.
487 if (ScopeRanges.size() > 1) {
488 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
492 // Construct the address range for this DIE.
493 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
494 MCSymbol *Start = getLabelBeforeInsn(RI->first);
495 MCSymbol *End = getLabelAfterInsn(RI->second);
496 assert(End && "End label should not be null!");
498 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
499 assert(End->isDefined() && "Invalid end label for an inlined scope!");
501 attachLowHighPC(TheCU, ScopeDIE, Start, End);
506 // This scope represents inlined body of a function. Construct DIE to
507 // represent this concrete inlined copy of the function.
508 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
509 LexicalScope *Scope) {
510 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
511 assert(!ScopeRanges.empty() &&
512 "LexicalScope does not have instruction markers!");
514 if (!Scope->getScopeNode())
516 DIScope DS(Scope->getScopeNode());
517 DISubprogram InlinedSP = getDISubprogram(DS);
518 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
520 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
524 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
525 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
527 // If we have multiple ranges, emit them into the range section.
528 if (ScopeRanges.size() > 1)
529 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
531 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
532 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
533 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
535 if (StartLabel == 0 || EndLabel == 0)
536 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
538 assert(StartLabel->isDefined() &&
539 "Invalid starting label for an inlined scope!");
540 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
542 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
545 InlinedSubprogramDIEs.insert(OriginDIE);
547 // Add the call site information to the DIE.
548 DILocation DL(Scope->getInlinedAt());
549 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
550 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
551 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
553 // Add name to the name table, we do this here because we're guaranteed
554 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
555 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
560 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
562 SmallVectorImpl<DIE *> &Children) {
563 DIE *ObjectPointer = NULL;
565 // Collect arguments for current function.
566 if (LScopes.isCurrentFunctionScope(Scope)) {
567 for (DbgVariable *ArgDV : CurrentFnArguments)
570 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
571 Children.push_back(Arg);
572 if (ArgDV->isObjectPointer())
576 // If this is a variadic function, add an unspecified parameter.
577 DISubprogram SP(Scope->getScopeNode());
578 DIArray FnArgs = SP.getType().getTypeArray();
579 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
580 .isUnspecifiedParameter()) {
581 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
582 Children.push_back(Ellipsis);
586 // Collect lexical scope children first.
587 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
589 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope())) {
590 Children.push_back(Variable);
591 if (DV->isObjectPointer())
592 ObjectPointer = Variable;
594 for (LexicalScope *LS : Scope->getChildren())
595 if (DIE *Nested = constructScopeDIE(TheCU, LS))
596 Children.push_back(Nested);
597 return ObjectPointer;
600 // Construct a DIE for this scope.
601 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
602 LexicalScope *Scope) {
603 if (!Scope || !Scope->getScopeNode())
606 DIScope DS(Scope->getScopeNode());
608 SmallVector<DIE *, 8> Children;
609 DIE *ObjectPointer = NULL;
610 bool ChildrenCreated = false;
612 // We try to create the scope DIE first, then the children DIEs. This will
613 // avoid creating un-used children then removing them later when we find out
614 // the scope DIE is null.
615 DIE *ScopeDIE = NULL;
616 if (Scope->getInlinedAt())
617 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
618 else if (DS.isSubprogram()) {
619 ProcessedSPNodes.insert(DS);
620 if (Scope->isAbstractScope()) {
621 ScopeDIE = TheCU.getDIE(DS);
622 // Note down abstract DIE.
624 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
626 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
628 // Early exit when we know the scope DIE is going to be null.
629 if (isLexicalScopeDIENull(Scope))
632 // We create children here when we know the scope DIE is not going to be
633 // null and the children will be added to the scope DIE.
634 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
635 ChildrenCreated = true;
637 // There is no need to emit empty lexical block DIE.
638 std::pair<ImportedEntityMap::const_iterator,
639 ImportedEntityMap::const_iterator> Range =
641 ScopesWithImportedEntities.begin(),
642 ScopesWithImportedEntities.end(),
643 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
645 if (Children.empty() && Range.first == Range.second)
647 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
648 assert(ScopeDIE && "Scope DIE should not be null.");
649 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
651 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
655 assert(Children.empty() &&
656 "We create children only when the scope DIE is not null.");
659 if (!ChildrenCreated)
660 // We create children when the scope DIE is not null.
661 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
664 for (DIE *I : Children)
665 ScopeDIE->addChild(I);
667 if (DS.isSubprogram() && ObjectPointer != NULL)
668 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
673 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
674 if (!GenerateGnuPubSections)
677 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
680 // Create new DwarfCompileUnit for the given metadata node with tag
681 // DW_TAG_compile_unit.
682 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
683 StringRef FN = DIUnit.getFilename();
684 CompilationDir = DIUnit.getDirectory();
686 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
687 auto OwnedUnit = make_unique<DwarfCompileUnit>(
688 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
689 DwarfCompileUnit &NewCU = *OwnedUnit;
690 InfoHolder.addUnit(std::move(OwnedUnit));
692 // LTO with assembly output shares a single line table amongst multiple CUs.
693 // To avoid the compilation directory being ambiguous, let the line table
694 // explicitly describe the directory of all files, never relying on the
695 // compilation directory.
696 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
697 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
698 NewCU.getUniqueID(), CompilationDir);
700 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
701 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
702 DIUnit.getLanguage());
703 NewCU.addString(Die, dwarf::DW_AT_name, FN);
705 if (!useSplitDwarf()) {
706 NewCU.initStmtList(DwarfLineSectionSym);
708 // If we're using split dwarf the compilation dir is going to be in the
709 // skeleton CU and so we don't need to duplicate it here.
710 if (!CompilationDir.empty())
711 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
713 addGnuPubAttributes(NewCU, Die);
716 if (DIUnit.isOptimized())
717 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
719 StringRef Flags = DIUnit.getFlags();
721 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
723 if (unsigned RVer = DIUnit.getRunTimeVersion())
724 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
725 dwarf::DW_FORM_data1, RVer);
730 if (useSplitDwarf()) {
731 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
732 DwarfInfoDWOSectionSym);
733 NewCU.setSkeleton(constructSkeletonCU(NewCU));
735 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
736 DwarfInfoSectionSym);
738 CUMap.insert(std::make_pair(DIUnit, &NewCU));
739 CUDieMap.insert(std::make_pair(Die, &NewCU));
743 // Construct subprogram DIE.
744 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
746 // FIXME: We should only call this routine once, however, during LTO if a
747 // program is defined in multiple CUs we could end up calling it out of
748 // beginModule as we walk the CUs.
750 DwarfCompileUnit *&CURef = SPMap[N];
756 if (!SP.isDefinition())
757 // This is a method declaration which will be handled while constructing
761 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
763 // Expose as a global name.
764 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
767 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
769 DIImportedEntity Module(N);
770 assert(Module.Verify());
771 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
772 constructImportedEntityDIE(TheCU, Module, D);
775 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
776 const MDNode *N, DIE *Context) {
777 DIImportedEntity Module(N);
778 assert(Module.Verify());
779 return constructImportedEntityDIE(TheCU, Module, Context);
782 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
783 const DIImportedEntity &Module,
785 assert(Module.Verify() &&
786 "Use one of the MDNode * overloads to handle invalid metadata");
787 assert(Context && "Should always have a context for an imported_module");
788 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
790 DIDescriptor Entity = resolve(Module.getEntity());
791 if (Entity.isNameSpace())
792 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
793 else if (Entity.isSubprogram())
794 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
795 else if (Entity.isType())
796 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
798 EntityDie = TheCU.getDIE(Entity);
799 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
800 Module.getContext().getFilename(),
801 Module.getContext().getDirectory());
802 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
803 StringRef Name = Module.getName();
805 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
808 // Emit all Dwarf sections that should come prior to the content. Create
809 // global DIEs and emit initial debug info sections. This is invoked by
810 // the target AsmPrinter.
811 void DwarfDebug::beginModule() {
812 if (DisableDebugInfoPrinting)
815 const Module *M = MMI->getModule();
817 // If module has named metadata anchors then use them, otherwise scan the
818 // module using debug info finder to collect debug info.
819 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
822 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
824 // Emit initial sections so we can reference labels later.
827 SingleCU = CU_Nodes->getNumOperands() == 1;
829 for (MDNode *N : CU_Nodes->operands()) {
830 DICompileUnit CUNode(N);
831 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
832 DIArray ImportedEntities = CUNode.getImportedEntities();
833 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
834 ScopesWithImportedEntities.push_back(std::make_pair(
835 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
836 ImportedEntities.getElement(i)));
837 std::sort(ScopesWithImportedEntities.begin(),
838 ScopesWithImportedEntities.end(), less_first());
839 DIArray GVs = CUNode.getGlobalVariables();
840 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
841 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
842 DIArray SPs = CUNode.getSubprograms();
843 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
844 constructSubprogramDIE(CU, SPs.getElement(i));
845 DIArray EnumTypes = CUNode.getEnumTypes();
846 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
847 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
848 DIArray RetainedTypes = CUNode.getRetainedTypes();
849 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
850 DIType Ty(RetainedTypes.getElement(i));
851 // The retained types array by design contains pointers to
852 // MDNodes rather than DIRefs. Unique them here.
853 DIType UniqueTy(resolve(Ty.getRef()));
854 CU.getOrCreateTypeDIE(UniqueTy);
856 // Emit imported_modules last so that the relevant context is already
858 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
859 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
862 // Tell MMI that we have debug info.
863 MMI->setDebugInfoAvailability(true);
865 // Prime section data.
866 SectionMap[Asm->getObjFileLowering().getTextSection()];
869 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
870 void DwarfDebug::computeInlinedDIEs() {
871 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
872 for (DIE *ISP : InlinedSubprogramDIEs)
873 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
875 for (const auto &AI : AbstractSPDies) {
876 DIE *ISP = AI.second;
877 if (InlinedSubprogramDIEs.count(ISP))
879 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
883 // Collect info for variables that were optimized out.
884 void DwarfDebug::collectDeadVariables() {
885 const Module *M = MMI->getModule();
887 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
888 for (MDNode *N : CU_Nodes->operands()) {
889 DICompileUnit TheCU(N);
890 DIArray Subprograms = TheCU.getSubprograms();
891 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
892 DISubprogram SP(Subprograms.getElement(i));
893 if (ProcessedSPNodes.count(SP) != 0)
895 if (!SP.isSubprogram())
897 if (!SP.isDefinition())
899 DIArray Variables = SP.getVariables();
900 if (Variables.getNumElements() == 0)
903 // Construct subprogram DIE and add variables DIEs.
904 DwarfCompileUnit *SPCU =
905 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
906 assert(SPCU && "Unable to find Compile Unit!");
907 // FIXME: See the comment in constructSubprogramDIE about duplicate
909 constructSubprogramDIE(*SPCU, SP);
910 DIE *SPDIE = SPCU->getDIE(SP);
911 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
912 DIVariable DV(Variables.getElement(vi));
913 if (!DV.isVariable())
915 DbgVariable NewVar(DV, NULL, this);
916 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
917 SPDIE->addChild(VariableDIE);
924 void DwarfDebug::finalizeModuleInfo() {
925 // Collect info for variables that were optimized out.
926 collectDeadVariables();
928 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
929 computeInlinedDIEs();
931 // Handle anything that needs to be done on a per-unit basis after
932 // all other generation.
933 for (const auto &TheU : getUnits()) {
934 // Emit DW_AT_containing_type attribute to connect types with their
935 // vtable holding type.
936 TheU->constructContainingTypeDIEs();
938 // Add CU specific attributes if we need to add any.
939 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
940 // If we're splitting the dwarf out now that we've got the entire
941 // CU then add the dwo id to it.
942 DwarfCompileUnit *SkCU =
943 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
944 if (useSplitDwarf()) {
945 // Emit a unique identifier for this CU.
946 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
947 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
948 dwarf::DW_FORM_data8, ID);
949 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
950 dwarf::DW_FORM_data8, ID);
952 // We don't keep track of which addresses are used in which CU so this
953 // is a bit pessimistic under LTO.
954 if (!InfoHolder.getAddrPool()->empty())
955 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
956 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
957 DwarfAddrSectionSym);
958 if (!TheU->getRangeLists().empty())
959 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
960 dwarf::DW_AT_GNU_ranges_base,
961 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
964 // If we have code split among multiple sections or non-contiguous
965 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
966 // remain in the .o file, otherwise add a DW_AT_low_pc.
967 // FIXME: We should use ranges allow reordering of code ala
968 // .subsections_via_symbols in mach-o. This would mean turning on
969 // ranges for all subprogram DIEs for mach-o.
970 DwarfCompileUnit &U =
971 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
972 unsigned NumRanges = TheU->getRanges().size();
975 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
976 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
977 DwarfDebugRangeSectionSym);
979 // A DW_AT_low_pc attribute may also be specified in combination with
980 // DW_AT_ranges to specify the default base address for use in
981 // location lists (see Section 2.6.2) and range lists (see Section
983 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
986 RangeSpan &Range = TheU->getRanges().back();
987 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
989 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
996 // Compute DIE offsets and sizes.
997 InfoHolder.computeSizeAndOffsets();
999 SkeletonHolder.computeSizeAndOffsets();
1002 void DwarfDebug::endSections() {
1003 // Filter labels by section.
1004 for (const SymbolCU &SCU : ArangeLabels) {
1005 if (SCU.Sym->isInSection()) {
1006 // Make a note of this symbol and it's section.
1007 const MCSection *Section = &SCU.Sym->getSection();
1008 if (!Section->getKind().isMetadata())
1009 SectionMap[Section].push_back(SCU);
1011 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1012 // appear in the output. This sucks as we rely on sections to build
1013 // arange spans. We can do it without, but it's icky.
1014 SectionMap[NULL].push_back(SCU);
1018 // Build a list of sections used.
1019 std::vector<const MCSection *> Sections;
1020 for (const auto &it : SectionMap) {
1021 const MCSection *Section = it.first;
1022 Sections.push_back(Section);
1025 // Sort the sections into order.
1026 // This is only done to ensure consistent output order across different runs.
1027 std::sort(Sections.begin(), Sections.end(), SectionSort);
1029 // Add terminating symbols for each section.
1030 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1031 const MCSection *Section = Sections[ID];
1032 MCSymbol *Sym = NULL;
1035 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1036 // if we know the section name up-front. For user-created sections, the
1037 // resulting label may not be valid to use as a label. (section names can
1038 // use a greater set of characters on some systems)
1039 Sym = Asm->GetTempSymbol("debug_end", ID);
1040 Asm->OutStreamer.SwitchSection(Section);
1041 Asm->OutStreamer.EmitLabel(Sym);
1044 // Insert a final terminator.
1045 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1049 // Emit all Dwarf sections that should come after the content.
1050 void DwarfDebug::endModule() {
1057 // End any existing sections.
1058 // TODO: Does this need to happen?
1061 // Finalize the debug info for the module.
1062 finalizeModuleInfo();
1066 // Emit all the DIEs into a debug info section.
1069 // Corresponding abbreviations into a abbrev section.
1070 emitAbbreviations();
1072 // Emit info into a debug aranges section.
1073 if (GenerateARangeSection)
1076 // Emit info into a debug ranges section.
1079 if (useSplitDwarf()) {
1082 emitDebugAbbrevDWO();
1084 // Emit DWO addresses.
1085 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1088 // Emit info into a debug loc section.
1091 // Emit info into the dwarf accelerator table sections.
1092 if (useDwarfAccelTables()) {
1095 emitAccelNamespaces();
1099 // Emit the pubnames and pubtypes sections if requested.
1100 if (HasDwarfPubSections) {
1101 emitDebugPubNames(GenerateGnuPubSections);
1102 emitDebugPubTypes(GenerateGnuPubSections);
1108 // Reset these for the next Module if we have one.
1112 // Find abstract variable, if any, associated with Var.
1113 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1114 DebugLoc ScopeLoc) {
1115 LLVMContext &Ctx = DV->getContext();
1116 // More then one inlined variable corresponds to one abstract variable.
1117 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1118 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1120 return AbsDbgVariable;
1122 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1126 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1127 addScopeVariable(Scope, AbsDbgVariable);
1128 AbstractVariables[Var] = AbsDbgVariable;
1129 return AbsDbgVariable;
1132 // If Var is a current function argument then add it to CurrentFnArguments list.
1133 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1134 if (!LScopes.isCurrentFunctionScope(Scope))
1136 DIVariable DV = Var->getVariable();
1137 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1139 unsigned ArgNo = DV.getArgNumber();
1143 size_t Size = CurrentFnArguments.size();
1145 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1146 // llvm::Function argument size is not good indicator of how many
1147 // arguments does the function have at source level.
1149 CurrentFnArguments.resize(ArgNo * 2);
1150 CurrentFnArguments[ArgNo - 1] = Var;
1154 // Collect variable information from side table maintained by MMI.
1155 void DwarfDebug::collectVariableInfoFromMMITable(
1156 SmallPtrSet<const MDNode *, 16> &Processed) {
1157 for (const auto &VI : MMI->getVariableDbgInfo()) {
1160 Processed.insert(VI.Var);
1161 DIVariable DV(VI.Var);
1162 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1164 // If variable scope is not found then skip this variable.
1168 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1169 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1170 RegVar->setFrameIndex(VI.Slot);
1171 if (!addCurrentFnArgument(RegVar, Scope))
1172 addScopeVariable(Scope, RegVar);
1174 AbsDbgVariable->setFrameIndex(VI.Slot);
1178 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1180 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1181 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1182 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1183 MI->getOperand(0).getReg() &&
1184 (MI->getOperand(1).isImm() ||
1185 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1188 // Get .debug_loc entry for the instruction range starting at MI.
1189 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1190 const MCSymbol *FLabel,
1191 const MCSymbol *SLabel,
1192 const MachineInstr *MI,
1193 DwarfCompileUnit *Unit) {
1194 const MDNode *Var = MI->getDebugVariable();
1196 assert(MI->getNumOperands() == 3);
1197 if (MI->getOperand(0).isReg()) {
1198 MachineLocation MLoc;
1199 // If the second operand is an immediate, this is a
1200 // register-indirect address.
1201 if (!MI->getOperand(1).isImm())
1202 MLoc.set(MI->getOperand(0).getReg());
1204 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1205 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1207 if (MI->getOperand(0).isImm())
1208 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1209 if (MI->getOperand(0).isFPImm())
1210 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1212 if (MI->getOperand(0).isCImm())
1213 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1216 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1219 // Find variables for each lexical scope.
1221 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1223 // Grab the variable info that was squirreled away in the MMI side-table.
1224 collectVariableInfoFromMMITable(Processed);
1226 for (const MDNode *Var : UserVariables) {
1227 if (Processed.count(Var))
1230 // History contains relevant DBG_VALUE instructions for Var and instructions
1232 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1233 if (History.empty())
1235 const MachineInstr *MInsn = History.front();
1238 LexicalScope *Scope = NULL;
1239 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1240 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1241 Scope = LScopes.getCurrentFunctionScope();
1242 else if (MDNode *IA = DV.getInlinedAt())
1243 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1245 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1246 // If variable scope is not found then skip this variable.
1250 Processed.insert(DV);
1251 assert(MInsn->isDebugValue() && "History must begin with debug value");
1252 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1253 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1254 if (!addCurrentFnArgument(RegVar, Scope))
1255 addScopeVariable(Scope, RegVar);
1257 AbsVar->setMInsn(MInsn);
1259 // Simplify ranges that are fully coalesced.
1260 if (History.size() <= 1 ||
1261 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1262 RegVar->setMInsn(MInsn);
1266 // Handle multiple DBG_VALUE instructions describing one variable.
1267 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1269 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1270 DebugLocList &LocList = DotDebugLocEntries.back();
1272 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1273 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1274 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1275 HI = History.begin(),
1278 const MachineInstr *Begin = *HI;
1279 assert(Begin->isDebugValue() && "Invalid History entry");
1281 // Check if DBG_VALUE is truncating a range.
1282 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1283 !Begin->getOperand(0).getReg())
1286 // Compute the range for a register location.
1287 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1288 const MCSymbol *SLabel = 0;
1291 // If Begin is the last instruction in History then its value is valid
1292 // until the end of the function.
1293 SLabel = FunctionEndSym;
1295 const MachineInstr *End = HI[1];
1296 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1297 << "\t" << *Begin << "\t" << *End << "\n");
1298 if (End->isDebugValue())
1299 SLabel = getLabelBeforeInsn(End);
1301 // End is a normal instruction clobbering the range.
1302 SLabel = getLabelAfterInsn(End);
1303 assert(SLabel && "Forgot label after clobber instruction");
1308 // The value is valid until the next DBG_VALUE or clobber.
1309 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1310 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1311 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1312 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1313 DebugLoc.push_back(std::move(Loc));
1317 // Collect info for variables that were optimized out.
1318 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1319 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1320 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1321 DIVariable DV(Variables.getElement(i));
1322 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1324 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1325 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1329 // Return Label preceding the instruction.
1330 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1331 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1332 assert(Label && "Didn't insert label before instruction");
1336 // Return Label immediately following the instruction.
1337 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1338 return LabelsAfterInsn.lookup(MI);
1341 // Process beginning of an instruction.
1342 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1345 // Check if source location changes, but ignore DBG_VALUE locations.
1346 if (!MI->isDebugValue()) {
1347 DebugLoc DL = MI->getDebugLoc();
1348 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1351 if (DL == PrologEndLoc) {
1352 Flags |= DWARF2_FLAG_PROLOGUE_END;
1353 PrologEndLoc = DebugLoc();
1355 if (PrologEndLoc.isUnknown())
1356 Flags |= DWARF2_FLAG_IS_STMT;
1358 if (!DL.isUnknown()) {
1359 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1360 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1362 recordSourceLine(0, 0, 0, 0);
1366 // Insert labels where requested.
1367 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1368 LabelsBeforeInsn.find(MI);
1371 if (I == LabelsBeforeInsn.end())
1374 // Label already assigned.
1379 PrevLabel = MMI->getContext().CreateTempSymbol();
1380 Asm->OutStreamer.EmitLabel(PrevLabel);
1382 I->second = PrevLabel;
1385 // Process end of an instruction.
1386 void DwarfDebug::endInstruction() {
1388 // Don't create a new label after DBG_VALUE instructions.
1389 // They don't generate code.
1390 if (!CurMI->isDebugValue())
1393 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1394 LabelsAfterInsn.find(CurMI);
1398 if (I == LabelsAfterInsn.end())
1401 // Label already assigned.
1405 // We need a label after this instruction.
1407 PrevLabel = MMI->getContext().CreateTempSymbol();
1408 Asm->OutStreamer.EmitLabel(PrevLabel);
1410 I->second = PrevLabel;
1413 // Each LexicalScope has first instruction and last instruction to mark
1414 // beginning and end of a scope respectively. Create an inverse map that list
1415 // scopes starts (and ends) with an instruction. One instruction may start (or
1416 // end) multiple scopes. Ignore scopes that are not reachable.
1417 void DwarfDebug::identifyScopeMarkers() {
1418 SmallVector<LexicalScope *, 4> WorkList;
1419 WorkList.push_back(LScopes.getCurrentFunctionScope());
1420 while (!WorkList.empty()) {
1421 LexicalScope *S = WorkList.pop_back_val();
1423 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1424 if (!Children.empty())
1425 WorkList.append(Children.begin(), Children.end());
1427 if (S->isAbstractScope())
1430 for (const InsnRange &R : S->getRanges()) {
1431 assert(R.first && "InsnRange does not have first instruction!");
1432 assert(R.second && "InsnRange does not have second instruction!");
1433 requestLabelBeforeInsn(R.first);
1434 requestLabelAfterInsn(R.second);
1439 // Gather pre-function debug information. Assumes being called immediately
1440 // after the function entry point has been emitted.
1441 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1444 // If there's no debug info for the function we're not going to do anything.
1445 if (!MMI->hasDebugInfo())
1448 // Grab the lexical scopes for the function, if we don't have any of those
1449 // then we're not going to be able to do anything.
1450 LScopes.initialize(*MF);
1451 if (LScopes.empty())
1454 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1456 // Make sure that each lexical scope will have a begin/end label.
1457 identifyScopeMarkers();
1459 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1460 // belongs to so that we add to the correct per-cu line table in the
1462 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1463 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1464 assert(TheCU && "Unable to find compile unit!");
1465 if (Asm->OutStreamer.hasRawTextSupport())
1466 // Use a single line table if we are generating assembly.
1467 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1469 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1471 // Emit a label for the function so that we have a beginning address.
1472 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1473 // Assumes in correct section after the entry point.
1474 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1476 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1477 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1478 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1480 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1482 bool AtBlockEntry = true;
1483 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1485 const MachineInstr *MI = II;
1487 if (MI->isDebugValue()) {
1488 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1490 // Keep track of user variables.
1491 const MDNode *Var = MI->getDebugVariable();
1493 // Variable is in a register, we need to check for clobbers.
1494 if (isDbgValueInDefinedReg(MI))
1495 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1497 // Check the history of this variable.
1498 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1499 if (History.empty()) {
1500 UserVariables.push_back(Var);
1501 // The first mention of a function argument gets the FunctionBeginSym
1502 // label, so arguments are visible when breaking at function entry.
1504 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1505 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1506 LabelsBeforeInsn[MI] = FunctionBeginSym;
1508 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1509 const MachineInstr *Prev = History.back();
1510 if (Prev->isDebugValue()) {
1511 // Coalesce identical entries at the end of History.
1512 if (History.size() >= 2 &&
1513 Prev->isIdenticalTo(History[History.size() - 2])) {
1514 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1515 << "\t" << *Prev << "\t"
1516 << *History[History.size() - 2] << "\n");
1520 // Terminate old register assignments that don't reach MI;
1521 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1522 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1523 isDbgValueInDefinedReg(Prev)) {
1524 // Previous register assignment needs to terminate at the end of
1526 MachineBasicBlock::const_iterator LastMI =
1527 PrevMBB->getLastNonDebugInstr();
1528 if (LastMI == PrevMBB->end()) {
1529 // Drop DBG_VALUE for empty range.
1530 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1531 << "\t" << *Prev << "\n");
1533 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1534 // Terminate after LastMI.
1535 History.push_back(LastMI);
1539 History.push_back(MI);
1541 // Not a DBG_VALUE instruction.
1542 if (!MI->isPosition())
1543 AtBlockEntry = false;
1545 // First known non-DBG_VALUE and non-frame setup location marks
1546 // the beginning of the function body.
1547 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1548 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1549 PrologEndLoc = MI->getDebugLoc();
1551 // Check if the instruction clobbers any registers with debug vars.
1552 for (const MachineOperand &MO : MI->operands()) {
1553 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1555 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1558 const MDNode *Var = LiveUserVar[Reg];
1561 // Reg is now clobbered.
1562 LiveUserVar[Reg] = 0;
1564 // Was MD last defined by a DBG_VALUE referring to Reg?
1565 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1566 if (HistI == DbgValues.end())
1568 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1569 if (History.empty())
1571 const MachineInstr *Prev = History.back();
1572 // Sanity-check: Register assignments are terminated at the end of
1574 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1576 // Is the variable still in Reg?
1577 if (!isDbgValueInDefinedReg(Prev) ||
1578 Prev->getOperand(0).getReg() != Reg)
1580 // Var is clobbered. Make sure the next instruction gets a label.
1581 History.push_back(MI);
1588 for (auto &I : DbgValues) {
1589 SmallVectorImpl<const MachineInstr *> &History = I.second;
1590 if (History.empty())
1593 // Make sure the final register assignments are terminated.
1594 const MachineInstr *Prev = History.back();
1595 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1596 const MachineBasicBlock *PrevMBB = Prev->getParent();
1597 MachineBasicBlock::const_iterator LastMI =
1598 PrevMBB->getLastNonDebugInstr();
1599 if (LastMI == PrevMBB->end())
1600 // Drop DBG_VALUE for empty range.
1602 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1603 // Terminate after LastMI.
1604 History.push_back(LastMI);
1607 // Request labels for the full history.
1608 for (const MachineInstr *MI : History) {
1609 if (MI->isDebugValue())
1610 requestLabelBeforeInsn(MI);
1612 requestLabelAfterInsn(MI);
1616 PrevInstLoc = DebugLoc();
1617 PrevLabel = FunctionBeginSym;
1619 // Record beginning of function.
1620 if (!PrologEndLoc.isUnknown()) {
1621 DebugLoc FnStartDL =
1622 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1624 FnStartDL.getLine(), FnStartDL.getCol(),
1625 FnStartDL.getScope(MF->getFunction()->getContext()),
1626 // We'd like to list the prologue as "not statements" but GDB behaves
1627 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1628 DWARF2_FLAG_IS_STMT);
1632 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1633 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1634 DIVariable DV = Var->getVariable();
1635 // Variables with positive arg numbers are parameters.
1636 if (unsigned ArgNum = DV.getArgNumber()) {
1637 // Keep all parameters in order at the start of the variable list to ensure
1638 // function types are correct (no out-of-order parameters)
1640 // This could be improved by only doing it for optimized builds (unoptimized
1641 // builds have the right order to begin with), searching from the back (this
1642 // would catch the unoptimized case quickly), or doing a binary search
1643 // rather than linear search.
1644 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1645 while (I != Vars.end()) {
1646 unsigned CurNum = (*I)->getVariable().getArgNumber();
1647 // A local (non-parameter) variable has been found, insert immediately
1651 // A later indexed parameter has been found, insert immediately before it.
1652 if (CurNum > ArgNum)
1656 Vars.insert(I, Var);
1660 Vars.push_back(Var);
1663 // Gather and emit post-function debug information.
1664 void DwarfDebug::endFunction(const MachineFunction *MF) {
1665 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1666 // though the beginFunction may not be called at all.
1667 // We should handle both cases.
1671 assert(CurFn == MF);
1674 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1675 // If we don't have a lexical scope for this function then there will
1676 // be a hole in the range information. Keep note of this by setting the
1677 // previously used section to nullptr.
1678 PrevSection = nullptr;
1684 // Define end label for subprogram.
1685 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1686 // Assumes in correct section after the entry point.
1687 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1689 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1690 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1692 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1693 collectVariableInfo(ProcessedVars);
1695 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1696 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1698 // Construct abstract scopes.
1699 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1700 DISubprogram SP(AScope->getScopeNode());
1701 if (SP.isSubprogram()) {
1702 // Collect info for variables that were optimized out.
1703 DIArray Variables = SP.getVariables();
1704 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1705 DIVariable DV(Variables.getElement(i));
1706 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1708 // Check that DbgVariable for DV wasn't created earlier, when
1709 // findAbstractVariable() was called for inlined instance of DV.
1710 LLVMContext &Ctx = DV->getContext();
1711 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1712 if (AbstractVariables.lookup(CleanDV))
1714 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1715 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1718 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1719 constructScopeDIE(TheCU, AScope);
1722 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1723 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1724 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1726 // Add the range of this function to the list of ranges for the CU.
1727 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1728 TheCU.addRange(std::move(Span));
1729 PrevSection = Asm->getCurrentSection();
1733 for (auto &I : ScopeVariables)
1734 DeleteContainerPointers(I.second);
1735 ScopeVariables.clear();
1736 DeleteContainerPointers(CurrentFnArguments);
1737 UserVariables.clear();
1739 AbstractVariables.clear();
1740 LabelsBeforeInsn.clear();
1741 LabelsAfterInsn.clear();
1746 // Register a source line with debug info. Returns the unique label that was
1747 // emitted and which provides correspondence to the source line list.
1748 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1753 unsigned Discriminator = 0;
1755 DIDescriptor Scope(S);
1757 if (Scope.isCompileUnit()) {
1758 DICompileUnit CU(S);
1759 Fn = CU.getFilename();
1760 Dir = CU.getDirectory();
1761 } else if (Scope.isFile()) {
1763 Fn = F.getFilename();
1764 Dir = F.getDirectory();
1765 } else if (Scope.isSubprogram()) {
1767 Fn = SP.getFilename();
1768 Dir = SP.getDirectory();
1769 } else if (Scope.isLexicalBlockFile()) {
1770 DILexicalBlockFile DBF(S);
1771 Fn = DBF.getFilename();
1772 Dir = DBF.getDirectory();
1773 } else if (Scope.isLexicalBlock()) {
1774 DILexicalBlock DB(S);
1775 Fn = DB.getFilename();
1776 Dir = DB.getDirectory();
1777 Discriminator = DB.getDiscriminator();
1779 llvm_unreachable("Unexpected scope info");
1781 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1782 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1783 .getOrCreateSourceID(Fn, Dir);
1785 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1789 //===----------------------------------------------------------------------===//
1791 //===----------------------------------------------------------------------===//
1793 // Compute the size and offset of a DIE. The offset is relative to start of the
1794 // CU. It returns the offset after laying out the DIE.
1795 unsigned DwarfFile::computeSizeAndOffset(DIE &Die, unsigned Offset) {
1796 // Record the abbreviation.
1797 assignAbbrevNumber(Die.getAbbrev());
1799 // Get the abbreviation for this DIE.
1800 const DIEAbbrev &Abbrev = Die.getAbbrev();
1803 Die.setOffset(Offset);
1805 // Start the size with the size of abbreviation code.
1806 Offset += getULEB128Size(Die.getAbbrevNumber());
1808 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1809 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1811 // Size the DIE attribute values.
1812 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1813 // Size attribute value.
1814 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1816 // Get the children.
1817 const auto &Children = Die.getChildren();
1819 // Size the DIE children if any.
1820 if (!Children.empty()) {
1821 assert(Abbrev.hasChildren() && "Children flag not set");
1823 for (auto &Child : Children)
1824 Offset = computeSizeAndOffset(*Child, Offset);
1826 // End of children marker.
1827 Offset += sizeof(int8_t);
1830 Die.setSize(Offset - Die.getOffset());
1834 // Compute the size and offset for each DIE.
1835 void DwarfFile::computeSizeAndOffsets() {
1836 // Offset from the first CU in the debug info section is 0 initially.
1837 unsigned SecOffset = 0;
1839 // Iterate over each compile unit and set the size and offsets for each
1840 // DIE within each compile unit. All offsets are CU relative.
1841 for (const auto &TheU : CUs) {
1842 TheU->setDebugInfoOffset(SecOffset);
1844 // CU-relative offset is reset to 0 here.
1845 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1846 TheU->getHeaderSize(); // Unit-specific headers
1848 // EndOffset here is CU-relative, after laying out
1849 // all of the CU DIE.
1850 unsigned EndOffset = computeSizeAndOffset(*TheU->getUnitDie(), Offset);
1851 SecOffset += EndOffset;
1855 // Emit initial Dwarf sections with a label at the start of each one.
1856 void DwarfDebug::emitSectionLabels() {
1857 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1859 // Dwarf sections base addresses.
1860 DwarfInfoSectionSym =
1861 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1862 if (useSplitDwarf())
1863 DwarfInfoDWOSectionSym =
1864 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1865 DwarfAbbrevSectionSym =
1866 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1867 if (useSplitDwarf())
1868 DwarfAbbrevDWOSectionSym = emitSectionSym(
1869 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1870 if (GenerateARangeSection)
1871 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1873 DwarfLineSectionSym =
1874 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1875 if (GenerateGnuPubSections) {
1876 DwarfGnuPubNamesSectionSym =
1877 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1878 DwarfGnuPubTypesSectionSym =
1879 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1880 } else if (HasDwarfPubSections) {
1881 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1882 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1885 DwarfStrSectionSym =
1886 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1887 if (useSplitDwarf()) {
1888 DwarfStrDWOSectionSym =
1889 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1890 DwarfAddrSectionSym =
1891 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1892 DwarfDebugLocSectionSym =
1893 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1895 DwarfDebugLocSectionSym =
1896 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1897 DwarfDebugRangeSectionSym =
1898 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1901 // Recursively emits a debug information entry.
1902 void DwarfDebug::emitDIE(DIE &Die) {
1903 // Get the abbreviation for this DIE.
1904 const DIEAbbrev &Abbrev = Die.getAbbrev();
1906 // Emit the code (index) for the abbreviation.
1907 if (Asm->isVerbose())
1908 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1909 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1910 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1911 dwarf::TagString(Abbrev.getTag()));
1912 Asm->EmitULEB128(Abbrev.getNumber());
1914 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1915 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1917 // Emit the DIE attribute values.
1918 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1919 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1920 dwarf::Form Form = AbbrevData[i].getForm();
1921 assert(Form && "Too many attributes for DIE (check abbreviation)");
1923 if (Asm->isVerbose()) {
1924 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1925 if (Attr == dwarf::DW_AT_accessibility)
1926 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1927 cast<DIEInteger>(Values[i])->getValue()));
1930 // Emit an attribute using the defined form.
1931 Values[i]->EmitValue(Asm, Form);
1934 // Emit the DIE children if any.
1935 if (Abbrev.hasChildren()) {
1936 for (auto &Child : Die.getChildren())
1939 Asm->OutStreamer.AddComment("End Of Children Mark");
1944 // Emit the various dwarf units to the unit section USection with
1945 // the abbreviations going into ASection.
1946 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSymbol *ASectionSym) {
1947 for (const auto &TheU : CUs) {
1948 DIE *Die = TheU->getUnitDie();
1949 const MCSection *USection = TheU->getSection();
1950 Asm->OutStreamer.SwitchSection(USection);
1952 // Emit the compile units header.
1953 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1955 // Emit size of content not including length itself
1956 Asm->OutStreamer.AddComment("Length of Unit");
1957 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1959 TheU->emitHeader(ASectionSym);
1962 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1966 // Emit the debug info section.
1967 void DwarfDebug::emitDebugInfo() {
1968 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1970 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1973 // Emit the abbreviation section.
1974 void DwarfDebug::emitAbbreviations() {
1975 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1977 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1980 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1981 // Check to see if it is worth the effort.
1982 if (!Abbreviations.empty()) {
1983 // Start the debug abbrev section.
1984 Asm->OutStreamer.SwitchSection(Section);
1986 // For each abbrevation.
1987 for (const DIEAbbrev *Abbrev : Abbreviations) {
1988 // Emit the abbrevations code (base 1 index.)
1989 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1991 // Emit the abbreviations data.
1995 // Mark end of abbreviations.
1996 Asm->EmitULEB128(0, "EOM(3)");
2000 // Emit the last address of the section and the end of the line matrix.
2001 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2002 // Define last address of section.
2003 Asm->OutStreamer.AddComment("Extended Op");
2006 Asm->OutStreamer.AddComment("Op size");
2007 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2008 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2009 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2011 Asm->OutStreamer.AddComment("Section end label");
2013 Asm->OutStreamer.EmitSymbolValue(
2014 Asm->GetTempSymbol("section_end", SectionEnd),
2015 Asm->getDataLayout().getPointerSize());
2017 // Mark end of matrix.
2018 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2024 // Emit visible names into a hashed accelerator table section.
2025 void DwarfDebug::emitAccelNames() {
2027 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2028 for (const auto &TheU : getUnits()) {
2029 for (const auto &GI : TheU->getAccelNames()) {
2030 StringRef Name = GI.getKey();
2031 for (const DIE *D : GI.second)
2032 AT.AddName(Name, D);
2036 AT.FinalizeTable(Asm, "Names");
2037 Asm->OutStreamer.SwitchSection(
2038 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2039 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2040 Asm->OutStreamer.EmitLabel(SectionBegin);
2042 // Emit the full data.
2043 AT.Emit(Asm, SectionBegin, &InfoHolder);
2046 // Emit objective C classes and categories into a hashed accelerator table
2048 void DwarfDebug::emitAccelObjC() {
2050 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2051 for (const auto &TheU : getUnits()) {
2052 for (const auto &GI : TheU->getAccelObjC()) {
2053 StringRef Name = GI.getKey();
2054 for (const DIE *D : GI.second)
2055 AT.AddName(Name, D);
2059 AT.FinalizeTable(Asm, "ObjC");
2060 Asm->OutStreamer.SwitchSection(
2061 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2062 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2063 Asm->OutStreamer.EmitLabel(SectionBegin);
2065 // Emit the full data.
2066 AT.Emit(Asm, SectionBegin, &InfoHolder);
2069 // Emit namespace dies into a hashed accelerator table.
2070 void DwarfDebug::emitAccelNamespaces() {
2072 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2073 for (const auto &TheU : getUnits()) {
2074 for (const auto &GI : TheU->getAccelNamespace()) {
2075 StringRef Name = GI.getKey();
2076 for (const DIE *D : GI.second)
2077 AT.AddName(Name, D);
2081 AT.FinalizeTable(Asm, "namespac");
2082 Asm->OutStreamer.SwitchSection(
2083 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2084 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2085 Asm->OutStreamer.EmitLabel(SectionBegin);
2087 // Emit the full data.
2088 AT.Emit(Asm, SectionBegin, &InfoHolder);
2091 // Emit type dies into a hashed accelerator table.
2092 void DwarfDebug::emitAccelTypes() {
2093 std::vector<DwarfAccelTable::Atom> Atoms;
2095 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2097 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2099 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2100 DwarfAccelTable AT(Atoms);
2101 for (const auto &TheU : getUnits()) {
2102 for (const auto &GI : TheU->getAccelTypes()) {
2103 StringRef Name = GI.getKey();
2104 for (const auto &DI : GI.second)
2105 AT.AddName(Name, DI.first, DI.second);
2109 AT.FinalizeTable(Asm, "types");
2110 Asm->OutStreamer.SwitchSection(
2111 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2112 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2113 Asm->OutStreamer.EmitLabel(SectionBegin);
2115 // Emit the full data.
2116 AT.Emit(Asm, SectionBegin, &InfoHolder);
2119 // Public name handling.
2120 // The format for the various pubnames:
2122 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2123 // for the DIE that is named.
2125 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2126 // into the CU and the index value is computed according to the type of value
2127 // for the DIE that is named.
2129 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2130 // it's the offset within the debug_info/debug_types dwo section, however, the
2131 // reference in the pubname header doesn't change.
2133 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2134 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2136 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2138 // We could have a specification DIE that has our most of our knowledge,
2139 // look for that now.
2140 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2142 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2143 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2144 Linkage = dwarf::GIEL_EXTERNAL;
2145 } else if (Die->findAttribute(dwarf::DW_AT_external))
2146 Linkage = dwarf::GIEL_EXTERNAL;
2148 switch (Die->getTag()) {
2149 case dwarf::DW_TAG_class_type:
2150 case dwarf::DW_TAG_structure_type:
2151 case dwarf::DW_TAG_union_type:
2152 case dwarf::DW_TAG_enumeration_type:
2153 return dwarf::PubIndexEntryDescriptor(
2154 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2155 ? dwarf::GIEL_STATIC
2156 : dwarf::GIEL_EXTERNAL);
2157 case dwarf::DW_TAG_typedef:
2158 case dwarf::DW_TAG_base_type:
2159 case dwarf::DW_TAG_subrange_type:
2160 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2161 case dwarf::DW_TAG_namespace:
2162 return dwarf::GIEK_TYPE;
2163 case dwarf::DW_TAG_subprogram:
2164 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2165 case dwarf::DW_TAG_constant:
2166 case dwarf::DW_TAG_variable:
2167 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2168 case dwarf::DW_TAG_enumerator:
2169 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2170 dwarf::GIEL_STATIC);
2172 return dwarf::GIEK_NONE;
2176 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2178 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2179 const MCSection *PSec =
2180 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2181 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2183 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2186 void DwarfDebug::emitDebugPubSection(
2187 bool GnuStyle, const MCSection *PSec, StringRef Name,
2188 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2189 for (const auto &NU : CUMap) {
2190 DwarfCompileUnit *TheU = NU.second;
2192 const auto &Globals = (TheU->*Accessor)();
2194 if (Globals.empty())
2197 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2199 unsigned ID = TheU->getUniqueID();
2201 // Start the dwarf pubnames section.
2202 Asm->OutStreamer.SwitchSection(PSec);
2205 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2206 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2207 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2208 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2210 Asm->OutStreamer.EmitLabel(BeginLabel);
2212 Asm->OutStreamer.AddComment("DWARF Version");
2213 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2215 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2216 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2218 Asm->OutStreamer.AddComment("Compilation Unit Length");
2219 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2221 // Emit the pubnames for this compilation unit.
2222 for (const auto &GI : Globals) {
2223 const char *Name = GI.getKeyData();
2224 const DIE *Entity = GI.second;
2226 Asm->OutStreamer.AddComment("DIE offset");
2227 Asm->EmitInt32(Entity->getOffset());
2230 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2231 Asm->OutStreamer.AddComment(
2232 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2233 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2234 Asm->EmitInt8(Desc.toBits());
2237 Asm->OutStreamer.AddComment("External Name");
2238 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2241 Asm->OutStreamer.AddComment("End Mark");
2243 Asm->OutStreamer.EmitLabel(EndLabel);
2247 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2248 const MCSection *PSec =
2249 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2250 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2252 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2255 // Emit strings into a string section.
2256 void DwarfFile::emitStrings(const MCSection *StrSection,
2257 const MCSection *OffsetSection = NULL,
2258 const MCSymbol *StrSecSym = NULL) {
2260 if (StringPool.empty())
2263 // Start the dwarf str section.
2264 Asm->OutStreamer.SwitchSection(StrSection);
2266 // Get all of the string pool entries and put them in an array by their ID so
2267 // we can sort them.
2268 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2270 for (const auto &I : StringPool)
2271 Entries.push_back(std::make_pair(I.second.second, &I));
2273 array_pod_sort(Entries.begin(), Entries.end());
2275 for (const auto &Entry : Entries) {
2276 // Emit a label for reference from debug information entries.
2277 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2279 // Emit the string itself with a terminating null byte.
2280 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2281 Entry.second->getKeyLength() + 1));
2284 // If we've got an offset section go ahead and emit that now as well.
2285 if (OffsetSection) {
2286 Asm->OutStreamer.SwitchSection(OffsetSection);
2287 unsigned offset = 0;
2288 unsigned size = 4; // FIXME: DWARF64 is 8.
2289 for (const auto &Entry : Entries) {
2290 Asm->OutStreamer.EmitIntValue(offset, size);
2291 offset += Entry.second->getKeyLength() + 1;
2296 // Emit addresses into the section given.
2297 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2299 if (AddressPool.empty())
2302 // Start the dwarf addr section.
2303 Asm->OutStreamer.SwitchSection(AddrSection);
2305 // Order the address pool entries by ID
2306 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2308 for (const auto &I : AddressPool)
2309 Entries[I.second.Number] =
2311 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2312 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2314 for (const MCExpr *Entry : Entries)
2315 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2318 // Emit visible names into a debug str section.
2319 void DwarfDebug::emitDebugStr() {
2320 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2321 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2324 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2325 const DebugLocEntry &Entry) {
2326 DIVariable DV(Entry.getVariable());
2327 if (Entry.isInt()) {
2328 DIBasicType BTy(resolve(DV.getType()));
2329 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2330 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2331 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2332 Streamer.EmitSLEB128(Entry.getInt());
2334 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2335 Streamer.EmitULEB128(Entry.getInt());
2337 } else if (Entry.isLocation()) {
2338 MachineLocation Loc = Entry.getLoc();
2339 if (!DV.hasComplexAddress())
2341 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2343 // Complex address entry.
2344 unsigned N = DV.getNumAddrElements();
2346 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2347 if (Loc.getOffset()) {
2349 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2350 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2351 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2352 Streamer.EmitSLEB128(DV.getAddrElement(1));
2354 // If first address element is OpPlus then emit
2355 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2356 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2357 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2361 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2364 // Emit remaining complex address elements.
2365 for (; i < N; ++i) {
2366 uint64_t Element = DV.getAddrElement(i);
2367 if (Element == DIBuilder::OpPlus) {
2368 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2369 Streamer.EmitULEB128(DV.getAddrElement(++i));
2370 } else if (Element == DIBuilder::OpDeref) {
2372 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2374 llvm_unreachable("unknown Opcode found in complex address");
2378 // else ... ignore constant fp. There is not any good way to
2379 // to represent them here in dwarf.
2383 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2384 Asm->OutStreamer.AddComment("Loc expr size");
2385 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2386 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2387 Asm->EmitLabelDifference(end, begin, 2);
2388 Asm->OutStreamer.EmitLabel(begin);
2390 APByteStreamer Streamer(*Asm);
2391 emitDebugLocEntry(Streamer, Entry);
2393 Asm->OutStreamer.EmitLabel(end);
2396 // Emit locations into the debug loc section.
2397 void DwarfDebug::emitDebugLoc() {
2398 // Start the dwarf loc section.
2399 Asm->OutStreamer.SwitchSection(
2400 Asm->getObjFileLowering().getDwarfLocSection());
2401 unsigned char Size = Asm->getDataLayout().getPointerSize();
2402 for (const auto &DebugLoc : DotDebugLocEntries) {
2403 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2404 for (const auto &Entry : DebugLoc.List) {
2405 // Set up the range. This range is relative to the entry point of the
2406 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2407 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2408 const DwarfCompileUnit *CU = Entry.getCU();
2409 if (CU->getRanges().size() == 1) {
2410 // Grab the begin symbol from the first range as our base.
2411 const MCSymbol *Base = CU->getRanges()[0].getStart();
2412 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2413 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2415 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2416 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2419 emitDebugLocEntryLocation(Entry);
2421 Asm->OutStreamer.EmitIntValue(0, Size);
2422 Asm->OutStreamer.EmitIntValue(0, Size);
2426 void DwarfDebug::emitDebugLocDWO() {
2427 Asm->OutStreamer.SwitchSection(
2428 Asm->getObjFileLowering().getDwarfLocDWOSection());
2429 for (const auto &DebugLoc : DotDebugLocEntries) {
2430 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2431 for (const auto &Entry : DebugLoc.List) {
2432 // Just always use start_length for now - at least that's one address
2433 // rather than two. We could get fancier and try to, say, reuse an
2434 // address we know we've emitted elsewhere (the start of the function?
2435 // The start of the CU or CU subrange that encloses this range?)
2436 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2437 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2438 Asm->EmitULEB128(idx);
2439 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2441 emitDebugLocEntryLocation(Entry);
2443 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2448 const MCSymbol *Start, *End;
2451 // Emit a debug aranges section, containing a CU lookup for any
2452 // address we can tie back to a CU.
2453 void DwarfDebug::emitDebugARanges() {
2454 // Start the dwarf aranges section.
2455 Asm->OutStreamer.SwitchSection(
2456 Asm->getObjFileLowering().getDwarfARangesSection());
2458 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2462 // Build a list of sections used.
2463 std::vector<const MCSection *> Sections;
2464 for (const auto &it : SectionMap) {
2465 const MCSection *Section = it.first;
2466 Sections.push_back(Section);
2469 // Sort the sections into order.
2470 // This is only done to ensure consistent output order across different runs.
2471 std::sort(Sections.begin(), Sections.end(), SectionSort);
2473 // Build a set of address spans, sorted by CU.
2474 for (const MCSection *Section : Sections) {
2475 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2476 if (List.size() < 2)
2479 // Sort the symbols by offset within the section.
2480 std::sort(List.begin(), List.end(),
2481 [&](const SymbolCU &A, const SymbolCU &B) {
2482 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2483 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2485 // Symbols with no order assigned should be placed at the end.
2486 // (e.g. section end labels)
2494 // If we have no section (e.g. common), just write out
2495 // individual spans for each symbol.
2496 if (Section == NULL) {
2497 for (const SymbolCU &Cur : List) {
2499 Span.Start = Cur.Sym;
2502 Spans[Cur.CU].push_back(Span);
2505 // Build spans between each label.
2506 const MCSymbol *StartSym = List[0].Sym;
2507 for (size_t n = 1, e = List.size(); n < e; n++) {
2508 const SymbolCU &Prev = List[n - 1];
2509 const SymbolCU &Cur = List[n];
2511 // Try and build the longest span we can within the same CU.
2512 if (Cur.CU != Prev.CU) {
2514 Span.Start = StartSym;
2516 Spans[Prev.CU].push_back(Span);
2523 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2525 // Build a list of CUs used.
2526 std::vector<DwarfCompileUnit *> CUs;
2527 for (const auto &it : Spans) {
2528 DwarfCompileUnit *CU = it.first;
2532 // Sort the CU list (again, to ensure consistent output order).
2533 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2534 return A->getUniqueID() < B->getUniqueID();
2537 // Emit an arange table for each CU we used.
2538 for (DwarfCompileUnit *CU : CUs) {
2539 std::vector<ArangeSpan> &List = Spans[CU];
2541 // Emit size of content not including length itself.
2542 unsigned ContentSize =
2543 sizeof(int16_t) + // DWARF ARange version number
2544 sizeof(int32_t) + // Offset of CU in the .debug_info section
2545 sizeof(int8_t) + // Pointer Size (in bytes)
2546 sizeof(int8_t); // Segment Size (in bytes)
2548 unsigned TupleSize = PtrSize * 2;
2550 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2552 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2554 ContentSize += Padding;
2555 ContentSize += (List.size() + 1) * TupleSize;
2557 // For each compile unit, write the list of spans it covers.
2558 Asm->OutStreamer.AddComment("Length of ARange Set");
2559 Asm->EmitInt32(ContentSize);
2560 Asm->OutStreamer.AddComment("DWARF Arange version number");
2561 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2562 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2563 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2564 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2565 Asm->EmitInt8(PtrSize);
2566 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2569 Asm->OutStreamer.EmitFill(Padding, 0xff);
2571 for (const ArangeSpan &Span : List) {
2572 Asm->EmitLabelReference(Span.Start, PtrSize);
2574 // Calculate the size as being from the span start to it's end.
2576 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2578 // For symbols without an end marker (e.g. common), we
2579 // write a single arange entry containing just that one symbol.
2580 uint64_t Size = SymSize[Span.Start];
2584 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2588 Asm->OutStreamer.AddComment("ARange terminator");
2589 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2590 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2594 // Emit visible names into a debug ranges section.
2595 void DwarfDebug::emitDebugRanges() {
2596 // Start the dwarf ranges section.
2597 Asm->OutStreamer.SwitchSection(
2598 Asm->getObjFileLowering().getDwarfRangesSection());
2600 // Size for our labels.
2601 unsigned char Size = Asm->getDataLayout().getPointerSize();
2603 // Grab the specific ranges for the compile units in the module.
2604 for (const auto &I : CUMap) {
2605 DwarfCompileUnit *TheCU = I.second;
2607 // Emit a symbol so we can find the beginning of our ranges.
2608 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2610 // Iterate over the misc ranges for the compile units in the module.
2611 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2612 // Emit our symbol so we can find the beginning of the range.
2613 Asm->OutStreamer.EmitLabel(List.getSym());
2615 for (const RangeSpan &Range : List.getRanges()) {
2616 const MCSymbol *Begin = Range.getStart();
2617 const MCSymbol *End = Range.getEnd();
2618 assert(Begin && "Range without a begin symbol?");
2619 assert(End && "Range without an end symbol?");
2620 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2621 Asm->OutStreamer.EmitSymbolValue(End, Size);
2624 // And terminate the list with two 0 values.
2625 Asm->OutStreamer.EmitIntValue(0, Size);
2626 Asm->OutStreamer.EmitIntValue(0, Size);
2629 // Now emit a range for the CU itself.
2630 if (TheCU->getRanges().size() > 1) {
2631 Asm->OutStreamer.EmitLabel(
2632 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2633 for (const RangeSpan &Range : TheCU->getRanges()) {
2634 const MCSymbol *Begin = Range.getStart();
2635 const MCSymbol *End = Range.getEnd();
2636 assert(Begin && "Range without a begin symbol?");
2637 assert(End && "Range without an end symbol?");
2638 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2639 Asm->OutStreamer.EmitSymbolValue(End, Size);
2641 // And terminate the list with two 0 values.
2642 Asm->OutStreamer.EmitIntValue(0, Size);
2643 Asm->OutStreamer.EmitIntValue(0, Size);
2648 // DWARF5 Experimental Separate Dwarf emitters.
2650 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2651 std::unique_ptr<DwarfUnit> NewU) {
2652 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2653 U.getCUNode().getSplitDebugFilename());
2655 if (!CompilationDir.empty())
2656 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2658 addGnuPubAttributes(*NewU, Die);
2660 SkeletonHolder.addUnit(std::move(NewU));
2663 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2664 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2665 // DW_AT_addr_base, DW_AT_ranges_base.
2666 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2668 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2669 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2670 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2671 DwarfCompileUnit &NewCU = *OwnedUnit;
2672 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2673 DwarfInfoSectionSym);
2675 NewCU.initStmtList(DwarfLineSectionSym);
2677 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2682 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2684 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2685 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2686 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2688 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2689 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2690 this, &SkeletonHolder);
2691 DwarfTypeUnit &NewTU = *OwnedUnit;
2692 NewTU.setTypeSignature(TU.getTypeSignature());
2693 NewTU.setType(NULL);
2695 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2697 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
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);
2761 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2762 this, &InfoHolder, getDwoLineTable(CU));
2763 DwarfTypeUnit &NewTU = *OwnedUnit;
2765 InfoHolder.addUnit(std::move(OwnedUnit));
2767 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2771 Hash.update(Identifier);
2772 // ... take the least significant 8 bytes and return those. Our MD5
2773 // implementation always returns its results in little endian, swap bytes
2775 MD5::MD5Result Result;
2777 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2778 NewTU.setTypeSignature(Signature);
2779 if (useSplitDwarf())
2780 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2782 CU.applyStmtList(*UnitDie);
2784 NewTU.setType(NewTU.createTypeDIE(CTy));
2788 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2789 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2791 CU.addDIETypeSignature(RefDie, NewTU);
2794 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2795 MCSymbol *Begin, MCSymbol *End) {
2796 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2797 if (DwarfVersion < 4)
2798 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2800 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);