1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
63 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
64 cl::desc("Add the CU hash as the dwo_id."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static cl::opt<unsigned>
106 DwarfVersionNumber("dwarf-version", cl::Hidden,
107 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
109 static const char *const DWARFGroupName = "DWARF Emission";
110 static const char *const DbgTimerName = "DWARF Debug Writer";
112 //===----------------------------------------------------------------------===//
116 /// resolve - Look in the DwarfDebug map for the MDNode that
117 /// corresponds to the reference.
118 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
119 return DD->resolve(Ref);
122 DIType DbgVariable::getType() const {
123 DIType Ty = Var.getType();
124 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125 // addresses instead.
126 if (Var.isBlockByrefVariable()) {
127 /* Byref variables, in Blocks, are declared by the programmer as
128 "SomeType VarName;", but the compiler creates a
129 __Block_byref_x_VarName struct, and gives the variable VarName
130 either the struct, or a pointer to the struct, as its type. This
131 is necessary for various behind-the-scenes things the compiler
132 needs to do with by-reference variables in blocks.
134 However, as far as the original *programmer* is concerned, the
135 variable should still have type 'SomeType', as originally declared.
137 The following function dives into the __Block_byref_x_VarName
138 struct to find the original type of the variable. This will be
139 passed back to the code generating the type for the Debug
140 Information Entry for the variable 'VarName'. 'VarName' will then
141 have the original type 'SomeType' in its debug information.
143 The original type 'SomeType' will be the type of the field named
144 'VarName' inside the __Block_byref_x_VarName struct.
146 NOTE: In order for this to not completely fail on the debugger
147 side, the Debug Information Entry for the variable VarName needs to
148 have a DW_AT_location that tells the debugger how to unwind through
149 the pointers and __Block_byref_x_VarName struct to find the actual
150 value of the variable. The function addBlockByrefType does this. */
152 uint16_t tag = Ty.getTag();
154 if (tag == dwarf::DW_TAG_pointer_type)
155 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
157 DIArray Elements = DICompositeType(subType).getTypeArray();
158 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
159 DIDerivedType DT(Elements.getElement(i));
160 if (getName() == DT.getName())
161 return (resolve(DT.getTypeDerivedFrom()));
167 } // end llvm namespace
169 /// Return Dwarf Version by checking module flags.
170 static unsigned getDwarfVersionFromModule(const Module *M) {
171 Value *Val = M->getModuleFlag("Dwarf Version");
173 return dwarf::DWARF_VERSION;
174 return cast<ConstantInt>(Val)->getZExtValue();
177 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
178 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
179 PrevLabel(NULL), GlobalRangeCount(0),
180 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
181 UsedNonDefaultText(false),
182 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
185 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
186 DwarfAddrSectionSym = 0;
187 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
188 FunctionBeginSym = FunctionEndSym = 0;
192 // Turn on accelerator tables for Darwin by default, pubnames by
193 // default for non-Darwin, and handle split dwarf.
194 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 DwarfVersion = DwarfVersionNumber
213 : getDwarfVersionFromModule(MMI->getModule());
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 // Switch to the specified MCSection and emit an assembler
222 // temporary label to it if SymbolStem is specified.
223 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
224 const char *SymbolStem = 0) {
225 Asm->OutStreamer.SwitchSection(Section);
229 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
230 Asm->OutStreamer.EmitLabel(TmpSym);
234 DwarfFile::~DwarfFile() {
235 for (DwarfUnit *DU : CUs)
239 MCSymbol *DwarfFile::getStringPoolSym() {
240 return Asm->GetTempSymbol(StringPref);
243 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
244 std::pair<MCSymbol *, unsigned> &Entry =
245 StringPool.GetOrCreateValue(Str).getValue();
249 Entry.second = NextStringPoolNumber++;
250 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
253 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
254 std::pair<MCSymbol *, unsigned> &Entry =
255 StringPool.GetOrCreateValue(Str).getValue();
259 Entry.second = NextStringPoolNumber++;
260 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
264 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
265 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
266 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
268 ++NextAddrPoolNumber;
269 return P.first->second.Number;
272 // Define a unique number for the abbreviation.
274 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
275 // Check the set for priors.
276 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
278 // If it's newly added.
279 if (InSet == &Abbrev) {
280 // Add to abbreviation list.
281 Abbreviations.push_back(&Abbrev);
283 // Assign the vector position + 1 as its number.
284 Abbrev.setNumber(Abbreviations.size());
286 // Assign existing abbreviation number.
287 Abbrev.setNumber(InSet->getNumber());
291 static bool isObjCClass(StringRef Name) {
292 return Name.startswith("+") || Name.startswith("-");
295 static bool hasObjCCategory(StringRef Name) {
296 if (!isObjCClass(Name))
299 return Name.find(") ") != StringRef::npos;
302 static void getObjCClassCategory(StringRef In, StringRef &Class,
303 StringRef &Category) {
304 if (!hasObjCCategory(In)) {
305 Class = In.slice(In.find('[') + 1, In.find(' '));
310 Class = In.slice(In.find('[') + 1, In.find('('));
311 Category = In.slice(In.find('[') + 1, In.find(' '));
315 static StringRef getObjCMethodName(StringRef In) {
316 return In.slice(In.find(' ') + 1, In.find(']'));
319 // Helper for sorting sections into a stable output order.
320 static bool SectionSort(const MCSection *A, const MCSection *B) {
321 std::string LA = (A ? A->getLabelBeginName() : "");
322 std::string LB = (B ? B->getLabelBeginName() : "");
326 // Add the various names to the Dwarf accelerator table names.
327 // TODO: Determine whether or not we should add names for programs
328 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
329 // is only slightly different than the lookup of non-standard ObjC names.
330 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
331 if (!SP.isDefinition())
333 TheU->addAccelName(SP.getName(), Die);
335 // If the linkage name is different than the name, go ahead and output
336 // that as well into the name table.
337 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
338 TheU->addAccelName(SP.getLinkageName(), Die);
340 // If this is an Objective-C selector name add it to the ObjC accelerator
342 if (isObjCClass(SP.getName())) {
343 StringRef Class, Category;
344 getObjCClassCategory(SP.getName(), Class, Category);
345 TheU->addAccelObjC(Class, Die);
347 TheU->addAccelObjC(Category, Die);
348 // Also add the base method name to the name table.
349 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
353 /// isSubprogramContext - Return true if Context is either a subprogram
354 /// or another context nested inside a subprogram.
355 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
358 DIDescriptor D(Context);
359 if (D.isSubprogram())
362 return isSubprogramContext(resolve(DIType(Context).getContext()));
366 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
367 // and DW_AT_high_pc attributes. If there are global variables in this
368 // scope then create and insert DIEs for these variables.
369 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
371 DIE *SPDie = SPCU->getDIE(SP);
373 assert(SPDie && "Unable to find subprogram DIE!");
375 // If we're updating an abstract DIE, then we will be adding the children and
376 // object pointer later on. But what we don't want to do is process the
377 // concrete DIE twice.
378 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
379 // Pick up abstract subprogram DIE.
381 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
382 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
384 DISubprogram SPDecl = SP.getFunctionDeclaration();
385 if (!SPDecl.isSubprogram()) {
386 // There is not any need to generate specification DIE for a function
387 // defined at compile unit level. If a function is defined inside another
388 // function then gdb prefers the definition at top level and but does not
389 // expect specification DIE in parent function. So avoid creating
390 // specification DIE for a function defined inside a function.
391 DIScope SPContext = resolve(SP.getContext());
392 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
393 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
394 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
397 DICompositeType SPTy = SP.getType();
398 DIArray Args = SPTy.getTypeArray();
399 uint16_t SPTag = SPTy.getTag();
400 if (SPTag == dwarf::DW_TAG_subroutine_type)
401 SPCU->constructSubprogramArguments(*SPDie, Args);
402 DIE *SPDeclDie = SPDie;
403 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
404 *SPCU->getUnitDie());
405 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
410 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
412 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
413 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
414 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
416 // Add name to the name table, we do this here because we're guaranteed
417 // to have concrete versions of our DW_TAG_subprogram nodes.
418 addSubprogramNames(SPCU, SP, SPDie);
423 /// Check whether we should create a DIE for the given Scope, return true
424 /// if we don't create a DIE (the corresponding DIE is null).
425 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
426 if (Scope->isAbstractScope())
429 // We don't create a DIE if there is no Range.
430 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
434 if (Ranges.size() > 1)
437 // We don't create a DIE if we have a single Range and the end label
439 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
440 MCSymbol *End = getLabelAfterInsn(RI->second);
444 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
445 dwarf::Attribute A, const MCSymbol *L,
446 const MCSymbol *Sec) {
447 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
448 U->addSectionLabel(D, A, L);
450 U->addSectionDelta(D, A, L, Sec);
453 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
454 const SmallVectorImpl<InsnRange> &Range) {
455 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
456 // emitting it appropriately.
457 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
458 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
459 DwarfDebugRangeSectionSym);
461 RangeSpanList List(RangeSym);
462 for (const InsnRange &R : Range) {
463 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
464 List.addRange(std::move(Span));
467 // Add the range list to the set of ranges to be emitted.
468 TheCU->addRangeList(std::move(List));
471 // Construct new DW_TAG_lexical_block for this scope and attach
472 // DW_AT_low_pc/DW_AT_high_pc labels.
473 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
474 LexicalScope *Scope) {
475 if (isLexicalScopeDIENull(Scope))
478 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
479 if (Scope->isAbstractScope())
482 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
484 // If we have multiple ranges, emit them into the range section.
485 if (ScopeRanges.size() > 1) {
486 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
490 // Construct the address range for this DIE.
491 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
492 MCSymbol *Start = getLabelBeforeInsn(RI->first);
493 MCSymbol *End = getLabelAfterInsn(RI->second);
494 assert(End && "End label should not be null!");
496 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
497 assert(End->isDefined() && "Invalid end label for an inlined scope!");
499 attachLowHighPC(TheCU, ScopeDIE, Start, End);
504 // This scope represents inlined body of a function. Construct DIE to
505 // represent this concrete inlined copy of the function.
506 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
507 LexicalScope *Scope) {
508 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
509 assert(!ScopeRanges.empty() &&
510 "LexicalScope does not have instruction markers!");
512 if (!Scope->getScopeNode())
514 DIScope DS(Scope->getScopeNode());
515 DISubprogram InlinedSP = getDISubprogram(DS);
516 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
518 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
522 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
523 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
525 // If we have multiple ranges, emit them into the range section.
526 if (ScopeRanges.size() > 1)
527 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
529 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
530 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
531 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
533 if (StartLabel == 0 || EndLabel == 0)
534 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
536 assert(StartLabel->isDefined() &&
537 "Invalid starting label for an inlined scope!");
538 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
540 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
543 InlinedSubprogramDIEs.insert(OriginDIE);
545 // Add the call site information to the DIE.
546 DILocation DL(Scope->getInlinedAt());
547 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
548 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
549 TheCU->getUniqueID()));
550 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
552 // Add name to the name table, we do this here because we're guaranteed
553 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
554 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
559 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
561 SmallVectorImpl<DIE *> &Children) {
562 DIE *ObjectPointer = NULL;
564 // Collect arguments for current function.
565 if (LScopes.isCurrentFunctionScope(Scope)) {
566 for (DbgVariable *ArgDV : CurrentFnArguments)
569 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
570 Children.push_back(Arg);
571 if (ArgDV->isObjectPointer())
575 // If this is a variadic function, add an unspecified parameter.
576 DISubprogram SP(Scope->getScopeNode());
577 DIArray FnArgs = SP.getType().getTypeArray();
578 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
579 .isUnspecifiedParameter()) {
580 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
581 Children.push_back(Ellipsis);
585 // Collect lexical scope children first.
586 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
587 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
588 Scope->isAbstractScope())) {
589 Children.push_back(Variable);
590 if (DV->isObjectPointer())
591 ObjectPointer = Variable;
593 for (LexicalScope *LS : Scope->getChildren())
594 if (DIE *Nested = constructScopeDIE(TheCU, LS))
595 Children.push_back(Nested);
596 return ObjectPointer;
599 // Construct a DIE for this scope.
600 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
601 LexicalScope *Scope) {
602 if (!Scope || !Scope->getScopeNode())
605 DIScope DS(Scope->getScopeNode());
607 SmallVector<DIE *, 8> Children;
608 DIE *ObjectPointer = NULL;
609 bool ChildrenCreated = false;
611 // We try to create the scope DIE first, then the children DIEs. This will
612 // avoid creating un-used children then removing them later when we find out
613 // the scope DIE is null.
614 DIE *ScopeDIE = NULL;
615 if (Scope->getInlinedAt())
616 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
617 else if (DS.isSubprogram()) {
618 ProcessedSPNodes.insert(DS);
619 if (Scope->isAbstractScope()) {
620 ScopeDIE = TheCU->getDIE(DS);
621 // Note down abstract DIE.
623 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
625 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
627 // Early exit when we know the scope DIE is going to be null.
628 if (isLexicalScopeDIENull(Scope))
631 // We create children here when we know the scope DIE is not going to be
632 // null and the children will be added to the scope DIE.
633 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
634 ChildrenCreated = true;
636 // There is no need to emit empty lexical block DIE.
637 std::pair<ImportedEntityMap::const_iterator,
638 ImportedEntityMap::const_iterator> Range =
640 ScopesWithImportedEntities.begin(),
641 ScopesWithImportedEntities.end(),
642 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
644 if (Children.empty() && Range.first == Range.second)
646 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
647 assert(ScopeDIE && "Scope DIE should not be null.");
648 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
650 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
654 assert(Children.empty() &&
655 "We create children only when the scope DIE is not null.");
658 if (!ChildrenCreated)
659 // We create children when the scope DIE is not null.
660 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
663 for (DIE *I : Children)
664 ScopeDIE->addChild(I);
666 if (DS.isSubprogram() && ObjectPointer != NULL)
667 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
672 // Look up the source id with the given directory and source file names.
673 // If none currently exists, create a new id and insert it in the
674 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
676 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
678 // If we print assembly, we can't separate .file entries according to
679 // compile units. Thus all files will belong to the default compile unit.
681 // FIXME: add a better feature test than hasRawTextSupport. Even better,
682 // extend .file to support this.
683 if (Asm->OutStreamer.hasRawTextSupport())
686 // If FE did not provide a file name, then assume stdin.
687 if (FileName.empty()) {
688 FileName = "<stdin>";
692 // TODO: this might not belong here. See if we can factor this better.
693 if (DirName == CompilationDir)
696 // FileIDCUMap stores the current ID for the given compile unit.
697 unsigned SrcId = FileIDCUMap[CUID] + 1;
699 // We look up the CUID/file/dir by concatenating them with a zero byte.
700 SmallString<128> NamePair;
701 NamePair += utostr(CUID);
704 NamePair += '\0'; // Zero bytes are not allowed in paths.
705 NamePair += FileName;
707 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
708 if (Ent.getValue() != SrcId)
709 return Ent.getValue();
711 FileIDCUMap[CUID] = SrcId;
712 // Print out a .file directive to specify files for .loc directives.
713 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
718 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
719 if (!GenerateGnuPubSections)
722 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
725 // Create new DwarfCompileUnit for the given metadata node with tag
726 // DW_TAG_compile_unit.
727 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
728 StringRef FN = DIUnit.getFilename();
729 CompilationDir = DIUnit.getDirectory();
731 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
732 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
733 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
734 InfoHolder.addUnit(NewCU);
736 FileIDCUMap[NewCU->getUniqueID()] = 0;
738 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
739 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
740 DIUnit.getLanguage());
741 NewCU->addString(Die, dwarf::DW_AT_name, FN);
743 if (!useSplitDwarf()) {
744 NewCU->initStmtList(DwarfLineSectionSym);
746 // If we're using split dwarf the compilation dir is going to be in the
747 // skeleton CU and so we don't need to duplicate it here.
748 if (!CompilationDir.empty())
749 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
751 addGnuPubAttributes(NewCU, Die);
754 if (DIUnit.isOptimized())
755 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
757 StringRef Flags = DIUnit.getFlags();
759 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
761 if (unsigned RVer = DIUnit.getRunTimeVersion())
762 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
763 dwarf::DW_FORM_data1, RVer);
768 if (useSplitDwarf()) {
769 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
770 DwarfInfoDWOSectionSym);
771 NewCU->setSkeleton(constructSkeletonCU(NewCU));
773 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
774 DwarfInfoSectionSym);
776 CUMap.insert(std::make_pair(DIUnit, NewCU));
777 CUDieMap.insert(std::make_pair(Die, NewCU));
781 // Construct subprogram DIE.
782 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
784 // FIXME: We should only call this routine once, however, during LTO if a
785 // program is defined in multiple CUs we could end up calling it out of
786 // beginModule as we walk the CUs.
788 DwarfCompileUnit *&CURef = SPMap[N];
794 if (!SP.isDefinition())
795 // This is a method declaration which will be handled while constructing
799 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
801 // Expose as a global name.
802 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
805 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
807 DIImportedEntity Module(N);
808 assert(Module.Verify());
809 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
810 constructImportedEntityDIE(TheCU, Module, D);
813 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
814 const MDNode *N, DIE *Context) {
815 DIImportedEntity Module(N);
816 assert(Module.Verify());
817 return constructImportedEntityDIE(TheCU, Module, Context);
820 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
821 const DIImportedEntity &Module,
823 assert(Module.Verify() &&
824 "Use one of the MDNode * overloads to handle invalid metadata");
825 assert(Context && "Should always have a context for an imported_module");
826 DIE *IMDie = new DIE(Module.getTag());
827 TheCU->insertDIE(Module, IMDie);
829 DIDescriptor Entity = Module.getEntity();
830 if (Entity.isNameSpace())
831 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
832 else if (Entity.isSubprogram())
833 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
834 else if (Entity.isType())
835 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
837 EntityDie = TheCU->getDIE(Entity);
838 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
839 Module.getContext().getFilename(),
840 Module.getContext().getDirectory());
841 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
842 StringRef Name = Module.getName();
844 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
845 Context->addChild(IMDie);
848 // Emit all Dwarf sections that should come prior to the content. Create
849 // global DIEs and emit initial debug info sections. This is invoked by
850 // the target AsmPrinter.
851 void DwarfDebug::beginModule() {
852 if (DisableDebugInfoPrinting)
855 const Module *M = MMI->getModule();
857 // If module has named metadata anchors then use them, otherwise scan the
858 // module using debug info finder to collect debug info.
859 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
862 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
864 // Emit initial sections so we can reference labels later.
867 for (MDNode *N : CU_Nodes->operands()) {
868 DICompileUnit CUNode(N);
869 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
870 DIArray ImportedEntities = CUNode.getImportedEntities();
871 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
872 ScopesWithImportedEntities.push_back(std::make_pair(
873 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
874 ImportedEntities.getElement(i)));
875 std::sort(ScopesWithImportedEntities.begin(),
876 ScopesWithImportedEntities.end(), less_first());
877 DIArray GVs = CUNode.getGlobalVariables();
878 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
879 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
880 DIArray SPs = CUNode.getSubprograms();
881 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
882 constructSubprogramDIE(CU, SPs.getElement(i));
883 DIArray EnumTypes = CUNode.getEnumTypes();
884 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
885 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
886 DIArray RetainedTypes = CUNode.getRetainedTypes();
887 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
888 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
889 // Emit imported_modules last so that the relevant context is already
891 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
892 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
895 // Tell MMI that we have debug info.
896 MMI->setDebugInfoAvailability(true);
898 // Prime section data.
899 SectionMap[Asm->getObjFileLowering().getTextSection()];
902 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
903 void DwarfDebug::computeInlinedDIEs() {
904 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
905 for (DIE *ISP : InlinedSubprogramDIEs)
906 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
908 for (const auto &AI : AbstractSPDies) {
909 DIE *ISP = AI.second;
910 if (InlinedSubprogramDIEs.count(ISP))
912 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
916 // Collect info for variables that were optimized out.
917 void DwarfDebug::collectDeadVariables() {
918 const Module *M = MMI->getModule();
920 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
921 for (MDNode *N : CU_Nodes->operands()) {
922 DICompileUnit TheCU(N);
923 DIArray Subprograms = TheCU.getSubprograms();
924 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
925 DISubprogram SP(Subprograms.getElement(i));
926 if (ProcessedSPNodes.count(SP) != 0)
928 if (!SP.isSubprogram())
930 if (!SP.isDefinition())
932 DIArray Variables = SP.getVariables();
933 if (Variables.getNumElements() == 0)
936 // Construct subprogram DIE and add variables DIEs.
937 DwarfCompileUnit *SPCU =
938 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
939 assert(SPCU && "Unable to find Compile Unit!");
940 // FIXME: See the comment in constructSubprogramDIE about duplicate
942 constructSubprogramDIE(SPCU, SP);
943 DIE *SPDIE = SPCU->getDIE(SP);
944 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
945 DIVariable DV(Variables.getElement(vi));
946 if (!DV.isVariable())
948 DbgVariable NewVar(DV, NULL, this);
949 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
950 SPDIE->addChild(VariableDIE);
957 void DwarfDebug::finalizeModuleInfo() {
958 // Collect info for variables that were optimized out.
959 collectDeadVariables();
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 computeInlinedDIEs();
964 // Handle anything that needs to be done on a per-unit basis after
965 // all other generation.
966 for (DwarfUnit *TheU : getUnits()) {
967 // Emit DW_AT_containing_type attribute to connect types with their
968 // vtable holding type.
969 TheU->constructContainingTypeDIEs();
971 // Add CU specific attributes if we need to add any.
972 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
973 // If we're splitting the dwarf out now that we've got the entire
974 // CU then add the dwo id to it.
975 DwarfCompileUnit *SkCU =
976 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
977 if (useSplitDwarf()) {
978 // This should be a unique identifier when we want to build .dwp files.
980 if (GenerateCUHash) {
982 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
984 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
985 dwarf::DW_FORM_data8, ID);
986 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
987 dwarf::DW_FORM_data8, ID);
990 // If we have code split among multiple sections or we've requested
991 // it then emit a DW_AT_ranges attribute on the unit that will remain
992 // in the .o file, otherwise add a DW_AT_low_pc.
993 // FIXME: Also add a high pc if we can.
994 // FIXME: We should use ranges if we have multiple compile units or
995 // allow reordering of code ala .subsections_via_symbols in mach-o.
996 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
997 if (useCURanges() && TheU->getRanges().size()) {
998 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
999 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1000 DwarfDebugRangeSectionSym);
1002 // A DW_AT_low_pc attribute may also be specified in combination with
1003 // DW_AT_ranges to specify the default base address for use in location
1004 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1005 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1008 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1013 // Compute DIE offsets and sizes.
1014 InfoHolder.computeSizeAndOffsets();
1015 if (useSplitDwarf())
1016 SkeletonHolder.computeSizeAndOffsets();
1019 void DwarfDebug::endSections() {
1020 // Filter labels by section.
1021 for (const SymbolCU &SCU : ArangeLabels) {
1022 if (SCU.Sym->isInSection()) {
1023 // Make a note of this symbol and it's section.
1024 const MCSection *Section = &SCU.Sym->getSection();
1025 if (!Section->getKind().isMetadata())
1026 SectionMap[Section].push_back(SCU);
1028 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1029 // appear in the output. This sucks as we rely on sections to build
1030 // arange spans. We can do it without, but it's icky.
1031 SectionMap[NULL].push_back(SCU);
1035 // Build a list of sections used.
1036 std::vector<const MCSection *> Sections;
1037 for (const auto &it : SectionMap) {
1038 const MCSection *Section = it.first;
1039 Sections.push_back(Section);
1042 // Sort the sections into order.
1043 // This is only done to ensure consistent output order across different runs.
1044 std::sort(Sections.begin(), Sections.end(), SectionSort);
1046 // Add terminating symbols for each section.
1047 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1048 const MCSection *Section = Sections[ID];
1049 MCSymbol *Sym = NULL;
1052 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1053 // if we know the section name up-front. For user-created sections, the
1054 // resulting label may not be valid to use as a label. (section names can
1055 // use a greater set of characters on some systems)
1056 Sym = Asm->GetTempSymbol("debug_end", ID);
1057 Asm->OutStreamer.SwitchSection(Section);
1058 Asm->OutStreamer.EmitLabel(Sym);
1061 // Insert a final terminator.
1062 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1065 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1066 // we've emitted a function into a unique section, or we're using LTO. If
1067 // we're using LTO then we can't know that any particular function in the
1068 // module is correlated to a particular CU and so we need to be conservative.
1069 // At this point all sections should be finalized except for dwarf sections.
1070 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1071 TargetMachine::getFunctionSections();
1074 // Emit all Dwarf sections that should come after the content.
1075 void DwarfDebug::endModule() {
1082 // End any existing sections.
1083 // TODO: Does this need to happen?
1086 // Finalize the debug info for the module.
1087 finalizeModuleInfo();
1091 // Emit all the DIEs into a debug info section.
1094 // Corresponding abbreviations into a abbrev section.
1095 emitAbbreviations();
1097 // Emit info into a debug loc section.
1100 // Emit info into a debug aranges section.
1101 if (GenerateARangeSection)
1104 // Emit info into a debug ranges section.
1107 if (useSplitDwarf()) {
1110 emitDebugAbbrevDWO();
1111 // Emit DWO addresses.
1112 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1115 // Emit info into the dwarf accelerator table sections.
1116 if (useDwarfAccelTables()) {
1119 emitAccelNamespaces();
1123 // Emit the pubnames and pubtypes sections if requested.
1124 if (HasDwarfPubSections) {
1125 emitDebugPubNames(GenerateGnuPubSections);
1126 emitDebugPubTypes(GenerateGnuPubSections);
1132 // Reset these for the next Module if we have one.
1136 // Find abstract variable, if any, associated with Var.
1137 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1138 DebugLoc ScopeLoc) {
1139 LLVMContext &Ctx = DV->getContext();
1140 // More then one inlined variable corresponds to one abstract variable.
1141 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1142 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1144 return AbsDbgVariable;
1146 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1150 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1151 addScopeVariable(Scope, AbsDbgVariable);
1152 AbstractVariables[Var] = AbsDbgVariable;
1153 return AbsDbgVariable;
1156 // If Var is a current function argument then add it to CurrentFnArguments list.
1157 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1158 if (!LScopes.isCurrentFunctionScope(Scope))
1160 DIVariable DV = Var->getVariable();
1161 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1163 unsigned ArgNo = DV.getArgNumber();
1167 size_t Size = CurrentFnArguments.size();
1169 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1170 // llvm::Function argument size is not good indicator of how many
1171 // arguments does the function have at source level.
1173 CurrentFnArguments.resize(ArgNo * 2);
1174 CurrentFnArguments[ArgNo - 1] = Var;
1178 // Collect variable information from side table maintained by MMI.
1179 void DwarfDebug::collectVariableInfoFromMMITable(
1180 SmallPtrSet<const MDNode *, 16> &Processed) {
1181 for (const auto &VI : MMI->getVariableDbgInfo()) {
1184 Processed.insert(VI.Var);
1185 DIVariable DV(VI.Var);
1186 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1188 // If variable scope is not found then skip this variable.
1192 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1193 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1194 RegVar->setFrameIndex(VI.Slot);
1195 if (!addCurrentFnArgument(RegVar, Scope))
1196 addScopeVariable(Scope, RegVar);
1198 AbsDbgVariable->setFrameIndex(VI.Slot);
1202 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1204 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1205 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1206 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1207 MI->getOperand(0).getReg() &&
1208 (MI->getOperand(1).isImm() ||
1209 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1212 // Get .debug_loc entry for the instruction range starting at MI.
1213 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1214 const MCSymbol *FLabel,
1215 const MCSymbol *SLabel,
1216 const MachineInstr *MI) {
1217 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1219 assert(MI->getNumOperands() == 3);
1220 if (MI->getOperand(0).isReg()) {
1221 MachineLocation MLoc;
1222 // If the second operand is an immediate, this is a
1223 // register-indirect address.
1224 if (!MI->getOperand(1).isImm())
1225 MLoc.set(MI->getOperand(0).getReg());
1227 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1228 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1230 if (MI->getOperand(0).isImm())
1231 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1232 if (MI->getOperand(0).isFPImm())
1233 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1234 if (MI->getOperand(0).isCImm())
1235 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1237 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1240 // Find variables for each lexical scope.
1242 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1244 // Grab the variable info that was squirreled away in the MMI side-table.
1245 collectVariableInfoFromMMITable(Processed);
1247 for (const MDNode *Var : UserVariables) {
1248 if (Processed.count(Var))
1251 // History contains relevant DBG_VALUE instructions for Var and instructions
1253 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1254 if (History.empty())
1256 const MachineInstr *MInsn = History.front();
1259 LexicalScope *Scope = NULL;
1260 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1261 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1262 Scope = LScopes.getCurrentFunctionScope();
1263 else if (MDNode *IA = DV.getInlinedAt())
1264 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1266 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1267 // If variable scope is not found then skip this variable.
1271 Processed.insert(DV);
1272 assert(MInsn->isDebugValue() && "History must begin with debug value");
1273 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1274 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1275 if (!addCurrentFnArgument(RegVar, Scope))
1276 addScopeVariable(Scope, RegVar);
1278 AbsVar->setMInsn(MInsn);
1280 // Simplify ranges that are fully coalesced.
1281 if (History.size() <= 1 ||
1282 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1283 RegVar->setMInsn(MInsn);
1287 // Handle multiple DBG_VALUE instructions describing one variable.
1288 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1290 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1291 HI = History.begin(),
1294 const MachineInstr *Begin = *HI;
1295 assert(Begin->isDebugValue() && "Invalid History entry");
1297 // Check if DBG_VALUE is truncating a range.
1298 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1299 !Begin->getOperand(0).getReg())
1302 // Compute the range for a register location.
1303 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1304 const MCSymbol *SLabel = 0;
1307 // If Begin is the last instruction in History then its value is valid
1308 // until the end of the function.
1309 SLabel = FunctionEndSym;
1311 const MachineInstr *End = HI[1];
1312 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1313 << "\t" << *Begin << "\t" << *End << "\n");
1314 if (End->isDebugValue())
1315 SLabel = getLabelBeforeInsn(End);
1317 // End is a normal instruction clobbering the range.
1318 SLabel = getLabelAfterInsn(End);
1319 assert(SLabel && "Forgot label after clobber instruction");
1324 // The value is valid until the next DBG_VALUE or clobber.
1325 DotDebugLocEntries.push_back(
1326 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1328 DotDebugLocEntries.push_back(DotDebugLocEntry());
1331 // Collect info for variables that were optimized out.
1332 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1333 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1334 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1335 DIVariable DV(Variables.getElement(i));
1336 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1338 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1339 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1343 // Return Label preceding the instruction.
1344 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1345 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1346 assert(Label && "Didn't insert label before instruction");
1350 // Return Label immediately following the instruction.
1351 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1352 return LabelsAfterInsn.lookup(MI);
1355 // Process beginning of an instruction.
1356 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1359 // Check if source location changes, but ignore DBG_VALUE locations.
1360 if (!MI->isDebugValue()) {
1361 DebugLoc DL = MI->getDebugLoc();
1362 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1365 if (DL == PrologEndLoc) {
1366 Flags |= DWARF2_FLAG_PROLOGUE_END;
1367 PrologEndLoc = DebugLoc();
1369 if (PrologEndLoc.isUnknown())
1370 Flags |= DWARF2_FLAG_IS_STMT;
1372 if (!DL.isUnknown()) {
1373 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1374 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1376 recordSourceLine(0, 0, 0, 0);
1380 // Insert labels where requested.
1381 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1382 LabelsBeforeInsn.find(MI);
1385 if (I == LabelsBeforeInsn.end())
1388 // Label already assigned.
1393 PrevLabel = MMI->getContext().CreateTempSymbol();
1394 Asm->OutStreamer.EmitLabel(PrevLabel);
1396 I->second = PrevLabel;
1399 // Process end of an instruction.
1400 void DwarfDebug::endInstruction() {
1402 // Don't create a new label after DBG_VALUE instructions.
1403 // They don't generate code.
1404 if (!CurMI->isDebugValue())
1407 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1408 LabelsAfterInsn.find(CurMI);
1412 if (I == LabelsAfterInsn.end())
1415 // Label already assigned.
1419 // We need a label after this instruction.
1421 PrevLabel = MMI->getContext().CreateTempSymbol();
1422 Asm->OutStreamer.EmitLabel(PrevLabel);
1424 I->second = PrevLabel;
1427 // Each LexicalScope has first instruction and last instruction to mark
1428 // beginning and end of a scope respectively. Create an inverse map that list
1429 // scopes starts (and ends) with an instruction. One instruction may start (or
1430 // end) multiple scopes. Ignore scopes that are not reachable.
1431 void DwarfDebug::identifyScopeMarkers() {
1432 SmallVector<LexicalScope *, 4> WorkList;
1433 WorkList.push_back(LScopes.getCurrentFunctionScope());
1434 while (!WorkList.empty()) {
1435 LexicalScope *S = WorkList.pop_back_val();
1437 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1438 if (!Children.empty())
1439 WorkList.append(Children.begin(), Children.end());
1441 if (S->isAbstractScope())
1444 for (const InsnRange &R : S->getRanges()) {
1445 assert(R.first && "InsnRange does not have first instruction!");
1446 assert(R.second && "InsnRange does not have second instruction!");
1447 requestLabelBeforeInsn(R.first);
1448 requestLabelAfterInsn(R.second);
1453 // Gather pre-function debug information. Assumes being called immediately
1454 // after the function entry point has been emitted.
1455 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1458 // If there's no debug info for the function we're not going to do anything.
1459 if (!MMI->hasDebugInfo())
1462 // Grab the lexical scopes for the function, if we don't have any of those
1463 // then we're not going to be able to do anything.
1464 LScopes.initialize(*MF);
1465 if (LScopes.empty()) {
1466 UsedNonDefaultText = true;
1470 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1472 // Make sure that each lexical scope will have a begin/end label.
1473 identifyScopeMarkers();
1475 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1476 // belongs to so that we add to the correct per-cu line table in the
1478 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1479 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1480 assert(TheCU && "Unable to find compile unit!");
1481 if (Asm->OutStreamer.hasRawTextSupport())
1482 // Use a single line table if we are generating assembly.
1483 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1485 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1487 // Check the current section against the standard text section. If different
1488 // keep track so that we will know when we're emitting functions into multiple
1490 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1491 UsedNonDefaultText = true;
1493 // Emit a label for the function so that we have a beginning address.
1494 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1495 // Assumes in correct section after the entry point.
1496 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1498 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1499 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1500 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1502 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1504 bool AtBlockEntry = true;
1505 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1507 const MachineInstr *MI = II;
1509 if (MI->isDebugValue()) {
1510 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1512 // Keep track of user variables.
1514 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1516 // Variable is in a register, we need to check for clobbers.
1517 if (isDbgValueInDefinedReg(MI))
1518 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1520 // Check the history of this variable.
1521 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1522 if (History.empty()) {
1523 UserVariables.push_back(Var);
1524 // The first mention of a function argument gets the FunctionBeginSym
1525 // label, so arguments are visible when breaking at function entry.
1527 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1528 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1529 LabelsBeforeInsn[MI] = FunctionBeginSym;
1531 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1532 const MachineInstr *Prev = History.back();
1533 if (Prev->isDebugValue()) {
1534 // Coalesce identical entries at the end of History.
1535 if (History.size() >= 2 &&
1536 Prev->isIdenticalTo(History[History.size() - 2])) {
1537 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1538 << "\t" << *Prev << "\t"
1539 << *History[History.size() - 2] << "\n");
1543 // Terminate old register assignments that don't reach MI;
1544 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1545 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1546 isDbgValueInDefinedReg(Prev)) {
1547 // Previous register assignment needs to terminate at the end of
1549 MachineBasicBlock::const_iterator LastMI =
1550 PrevMBB->getLastNonDebugInstr();
1551 if (LastMI == PrevMBB->end()) {
1552 // Drop DBG_VALUE for empty range.
1553 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1554 << "\t" << *Prev << "\n");
1556 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1557 // Terminate after LastMI.
1558 History.push_back(LastMI);
1562 History.push_back(MI);
1564 // Not a DBG_VALUE instruction.
1565 if (!MI->isPosition())
1566 AtBlockEntry = false;
1568 // First known non-DBG_VALUE and non-frame setup location marks
1569 // the beginning of the function body.
1570 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1571 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1572 PrologEndLoc = MI->getDebugLoc();
1574 // Check if the instruction clobbers any registers with debug vars.
1575 for (const MachineOperand &MO : MI->operands()) {
1576 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1578 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1581 const MDNode *Var = LiveUserVar[Reg];
1584 // Reg is now clobbered.
1585 LiveUserVar[Reg] = 0;
1587 // Was MD last defined by a DBG_VALUE referring to Reg?
1588 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1589 if (HistI == DbgValues.end())
1591 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1592 if (History.empty())
1594 const MachineInstr *Prev = History.back();
1595 // Sanity-check: Register assignments are terminated at the end of
1597 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1599 // Is the variable still in Reg?
1600 if (!isDbgValueInDefinedReg(Prev) ||
1601 Prev->getOperand(0).getReg() != Reg)
1603 // Var is clobbered. Make sure the next instruction gets a label.
1604 History.push_back(MI);
1611 for (auto &I : DbgValues) {
1612 SmallVectorImpl<const MachineInstr *> &History = I.second;
1613 if (History.empty())
1616 // Make sure the final register assignments are terminated.
1617 const MachineInstr *Prev = History.back();
1618 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1619 const MachineBasicBlock *PrevMBB = Prev->getParent();
1620 MachineBasicBlock::const_iterator LastMI =
1621 PrevMBB->getLastNonDebugInstr();
1622 if (LastMI == PrevMBB->end())
1623 // Drop DBG_VALUE for empty range.
1625 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1626 // Terminate after LastMI.
1627 History.push_back(LastMI);
1630 // Request labels for the full history.
1631 for (const MachineInstr *MI : History) {
1632 if (MI->isDebugValue())
1633 requestLabelBeforeInsn(MI);
1635 requestLabelAfterInsn(MI);
1639 PrevInstLoc = DebugLoc();
1640 PrevLabel = FunctionBeginSym;
1642 // Record beginning of function.
1643 if (!PrologEndLoc.isUnknown()) {
1644 DebugLoc FnStartDL =
1645 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1647 FnStartDL.getLine(), FnStartDL.getCol(),
1648 FnStartDL.getScope(MF->getFunction()->getContext()),
1649 // We'd like to list the prologue as "not statements" but GDB behaves
1650 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1651 DWARF2_FLAG_IS_STMT);
1655 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1656 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1657 DIVariable DV = Var->getVariable();
1658 // Variables with positive arg numbers are parameters.
1659 if (unsigned ArgNum = DV.getArgNumber()) {
1660 // Keep all parameters in order at the start of the variable list to ensure
1661 // function types are correct (no out-of-order parameters)
1663 // This could be improved by only doing it for optimized builds (unoptimized
1664 // builds have the right order to begin with), searching from the back (this
1665 // would catch the unoptimized case quickly), or doing a binary search
1666 // rather than linear search.
1667 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1668 while (I != Vars.end()) {
1669 unsigned CurNum = (*I)->getVariable().getArgNumber();
1670 // A local (non-parameter) variable has been found, insert immediately
1674 // A later indexed parameter has been found, insert immediately before it.
1675 if (CurNum > ArgNum)
1679 Vars.insert(I, Var);
1683 Vars.push_back(Var);
1686 // Gather and emit post-function debug information.
1687 void DwarfDebug::endFunction(const MachineFunction *MF) {
1688 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1689 // though the beginFunction may not be called at all.
1690 // We should handle both cases.
1694 assert(CurFn == MF);
1697 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1702 // Define end label for subprogram.
1703 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1704 // Assumes in correct section after the entry point.
1705 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1707 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1708 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1710 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1711 collectVariableInfo(ProcessedVars);
1713 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1714 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1715 assert(TheCU && "Unable to find compile unit!");
1717 // Construct abstract scopes.
1718 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1719 DISubprogram SP(AScope->getScopeNode());
1720 if (SP.isSubprogram()) {
1721 // Collect info for variables that were optimized out.
1722 DIArray Variables = SP.getVariables();
1723 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1724 DIVariable DV(Variables.getElement(i));
1725 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1727 // Check that DbgVariable for DV wasn't created earlier, when
1728 // findAbstractVariable() was called for inlined instance of DV.
1729 LLVMContext &Ctx = DV->getContext();
1730 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1731 if (AbstractVariables.lookup(CleanDV))
1733 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1734 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1737 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1738 constructScopeDIE(TheCU, AScope);
1741 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1742 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1743 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1745 // Add the range of this function to the list of ranges for the CU.
1746 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1747 TheCU->addRange(std::move(Span));
1750 for (auto &I : ScopeVariables)
1751 DeleteContainerPointers(I.second);
1752 ScopeVariables.clear();
1753 DeleteContainerPointers(CurrentFnArguments);
1754 UserVariables.clear();
1756 AbstractVariables.clear();
1757 LabelsBeforeInsn.clear();
1758 LabelsAfterInsn.clear();
1763 // Register a source line with debug info. Returns the unique label that was
1764 // emitted and which provides correspondence to the source line list.
1765 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1770 unsigned Discriminator = 0;
1772 DIDescriptor Scope(S);
1774 if (Scope.isCompileUnit()) {
1775 DICompileUnit CU(S);
1776 Fn = CU.getFilename();
1777 Dir = CU.getDirectory();
1778 } else if (Scope.isFile()) {
1780 Fn = F.getFilename();
1781 Dir = F.getDirectory();
1782 } else if (Scope.isSubprogram()) {
1784 Fn = SP.getFilename();
1785 Dir = SP.getDirectory();
1786 } else if (Scope.isLexicalBlockFile()) {
1787 DILexicalBlockFile DBF(S);
1788 Fn = DBF.getFilename();
1789 Dir = DBF.getDirectory();
1790 } else if (Scope.isLexicalBlock()) {
1791 DILexicalBlock DB(S);
1792 Fn = DB.getFilename();
1793 Dir = DB.getDirectory();
1794 Discriminator = DB.getDiscriminator();
1796 llvm_unreachable("Unexpected scope info");
1798 Src = getOrCreateSourceID(
1799 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1801 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1805 //===----------------------------------------------------------------------===//
1807 //===----------------------------------------------------------------------===//
1809 // Compute the size and offset of a DIE. The offset is relative to start of the
1810 // CU. It returns the offset after laying out the DIE.
1811 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1812 // Record the abbreviation.
1813 assignAbbrevNumber(Die->getAbbrev());
1815 // Get the abbreviation for this DIE.
1816 const DIEAbbrev &Abbrev = Die->getAbbrev();
1819 Die->setOffset(Offset);
1821 // Start the size with the size of abbreviation code.
1822 Offset += getULEB128Size(Die->getAbbrevNumber());
1824 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1825 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1827 // Size the DIE attribute values.
1828 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1829 // Size attribute value.
1830 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1832 // Get the children.
1833 const std::vector<DIE *> &Children = Die->getChildren();
1835 // Size the DIE children if any.
1836 if (!Children.empty()) {
1837 assert(Abbrev.hasChildren() && "Children flag not set");
1839 for (DIE *Child : Children)
1840 Offset = computeSizeAndOffset(Child, Offset);
1842 // End of children marker.
1843 Offset += sizeof(int8_t);
1846 Die->setSize(Offset - Die->getOffset());
1850 // Compute the size and offset for each DIE.
1851 void DwarfFile::computeSizeAndOffsets() {
1852 // Offset from the first CU in the debug info section is 0 initially.
1853 unsigned SecOffset = 0;
1855 // Iterate over each compile unit and set the size and offsets for each
1856 // DIE within each compile unit. All offsets are CU relative.
1857 for (DwarfUnit *TheU : CUs) {
1858 TheU->setDebugInfoOffset(SecOffset);
1860 // CU-relative offset is reset to 0 here.
1861 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1862 TheU->getHeaderSize(); // Unit-specific headers
1864 // EndOffset here is CU-relative, after laying out
1865 // all of the CU DIE.
1866 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1867 SecOffset += EndOffset;
1871 // Emit initial Dwarf sections with a label at the start of each one.
1872 void DwarfDebug::emitSectionLabels() {
1873 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1875 // Dwarf sections base addresses.
1876 DwarfInfoSectionSym =
1877 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1878 if (useSplitDwarf())
1879 DwarfInfoDWOSectionSym =
1880 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1881 DwarfAbbrevSectionSym =
1882 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1883 if (useSplitDwarf())
1884 DwarfAbbrevDWOSectionSym = emitSectionSym(
1885 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1886 if (GenerateARangeSection)
1887 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1889 DwarfLineSectionSym =
1890 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1891 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1892 if (GenerateGnuPubSections) {
1893 DwarfGnuPubNamesSectionSym =
1894 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1895 DwarfGnuPubTypesSectionSym =
1896 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1897 } else if (HasDwarfPubSections) {
1898 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1899 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1902 DwarfStrSectionSym =
1903 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1904 if (useSplitDwarf()) {
1905 DwarfStrDWOSectionSym =
1906 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1907 DwarfAddrSectionSym =
1908 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1910 DwarfDebugRangeSectionSym =
1911 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1913 DwarfDebugLocSectionSym =
1914 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1917 // Recursively emits a debug information entry.
1918 void DwarfDebug::emitDIE(DIE *Die) {
1919 // Get the abbreviation for this DIE.
1920 const DIEAbbrev &Abbrev = Die->getAbbrev();
1922 // Emit the code (index) for the abbreviation.
1923 if (Asm->isVerbose())
1924 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1925 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1926 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1927 dwarf::TagString(Abbrev.getTag()));
1928 Asm->EmitULEB128(Abbrev.getNumber());
1930 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1931 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1933 // Emit the DIE attribute values.
1934 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1935 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1936 dwarf::Form Form = AbbrevData[i].getForm();
1937 assert(Form && "Too many attributes for DIE (check abbreviation)");
1939 if (Asm->isVerbose()) {
1940 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1941 if (Attr == dwarf::DW_AT_accessibility)
1942 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1943 cast<DIEInteger>(Values[i])->getValue()));
1946 // Emit an attribute using the defined form.
1947 Values[i]->EmitValue(Asm, Form);
1950 // Emit the DIE children if any.
1951 if (Abbrev.hasChildren()) {
1952 const std::vector<DIE *> &Children = Die->getChildren();
1954 for (DIE *Child : Children)
1957 Asm->OutStreamer.AddComment("End Of Children Mark");
1962 // Emit the various dwarf units to the unit section USection with
1963 // the abbreviations going into ASection.
1964 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1965 const MCSymbol *ASectionSym) {
1966 for (DwarfUnit *TheU : CUs) {
1967 DIE *Die = TheU->getUnitDie();
1968 const MCSection *USection = TheU->getSection();
1969 Asm->OutStreamer.SwitchSection(USection);
1971 // Emit the compile units header.
1972 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1974 // Emit size of content not including length itself
1975 Asm->OutStreamer.AddComment("Length of Unit");
1976 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1978 TheU->emitHeader(ASection, ASectionSym);
1981 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1985 // Emit the debug info section.
1986 void DwarfDebug::emitDebugInfo() {
1987 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1989 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1990 DwarfAbbrevSectionSym);
1993 // Emit the abbreviation section.
1994 void DwarfDebug::emitAbbreviations() {
1995 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1997 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2000 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2001 // Check to see if it is worth the effort.
2002 if (!Abbreviations.empty()) {
2003 // Start the debug abbrev section.
2004 Asm->OutStreamer.SwitchSection(Section);
2006 // For each abbrevation.
2007 for (const DIEAbbrev *Abbrev : Abbreviations) {
2008 // Emit the abbrevations code (base 1 index.)
2009 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2011 // Emit the abbreviations data.
2015 // Mark end of abbreviations.
2016 Asm->EmitULEB128(0, "EOM(3)");
2020 // Emit the last address of the section and the end of the line matrix.
2021 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2022 // Define last address of section.
2023 Asm->OutStreamer.AddComment("Extended Op");
2026 Asm->OutStreamer.AddComment("Op size");
2027 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2028 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2029 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2031 Asm->OutStreamer.AddComment("Section end label");
2033 Asm->OutStreamer.EmitSymbolValue(
2034 Asm->GetTempSymbol("section_end", SectionEnd),
2035 Asm->getDataLayout().getPointerSize());
2037 // Mark end of matrix.
2038 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2044 // Emit visible names into a hashed accelerator table section.
2045 void DwarfDebug::emitAccelNames() {
2047 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2048 for (DwarfUnit *TheU : getUnits()) {
2049 for (const auto &GI : TheU->getAccelNames()) {
2050 StringRef Name = GI.getKey();
2051 for (const DIE *D : GI.second)
2052 AT.AddName(Name, D);
2056 AT.FinalizeTable(Asm, "Names");
2057 Asm->OutStreamer.SwitchSection(
2058 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2059 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2060 Asm->OutStreamer.EmitLabel(SectionBegin);
2062 // Emit the full data.
2063 AT.Emit(Asm, SectionBegin, &InfoHolder);
2066 // Emit objective C classes and categories into a hashed accelerator table
2068 void DwarfDebug::emitAccelObjC() {
2070 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2071 for (DwarfUnit *TheU : getUnits()) {
2072 for (const auto &GI : TheU->getAccelObjC()) {
2073 StringRef Name = GI.getKey();
2074 for (const DIE *D : GI.second)
2075 AT.AddName(Name, D);
2079 AT.FinalizeTable(Asm, "ObjC");
2080 Asm->OutStreamer.SwitchSection(
2081 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2082 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2083 Asm->OutStreamer.EmitLabel(SectionBegin);
2085 // Emit the full data.
2086 AT.Emit(Asm, SectionBegin, &InfoHolder);
2089 // Emit namespace dies into a hashed accelerator table.
2090 void DwarfDebug::emitAccelNamespaces() {
2092 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2093 for (DwarfUnit *TheU : getUnits()) {
2094 for (const auto &GI : TheU->getAccelNamespace()) {
2095 StringRef Name = GI.getKey();
2096 for (const DIE *D : GI.second)
2097 AT.AddName(Name, D);
2101 AT.FinalizeTable(Asm, "namespac");
2102 Asm->OutStreamer.SwitchSection(
2103 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2104 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2105 Asm->OutStreamer.EmitLabel(SectionBegin);
2107 // Emit the full data.
2108 AT.Emit(Asm, SectionBegin, &InfoHolder);
2111 // Emit type dies into a hashed accelerator table.
2112 void DwarfDebug::emitAccelTypes() {
2113 std::vector<DwarfAccelTable::Atom> Atoms;
2115 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2117 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2119 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2120 DwarfAccelTable AT(Atoms);
2121 for (DwarfUnit *TheU : getUnits()) {
2122 for (const auto &GI : TheU->getAccelTypes()) {
2123 StringRef Name = GI.getKey();
2124 for (const auto &DI : GI.second)
2125 AT.AddName(Name, DI.first, DI.second);
2129 AT.FinalizeTable(Asm, "types");
2130 Asm->OutStreamer.SwitchSection(
2131 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2132 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2133 Asm->OutStreamer.EmitLabel(SectionBegin);
2135 // Emit the full data.
2136 AT.Emit(Asm, SectionBegin, &InfoHolder);
2139 // Public name handling.
2140 // The format for the various pubnames:
2142 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2143 // for the DIE that is named.
2145 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2146 // into the CU and the index value is computed according to the type of value
2147 // for the DIE that is named.
2149 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2150 // it's the offset within the debug_info/debug_types dwo section, however, the
2151 // reference in the pubname header doesn't change.
2153 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2154 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2156 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2158 // We could have a specification DIE that has our most of our knowledge,
2159 // look for that now.
2160 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2162 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2163 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2164 Linkage = dwarf::GIEL_EXTERNAL;
2165 } else if (Die->findAttribute(dwarf::DW_AT_external))
2166 Linkage = dwarf::GIEL_EXTERNAL;
2168 switch (Die->getTag()) {
2169 case dwarf::DW_TAG_class_type:
2170 case dwarf::DW_TAG_structure_type:
2171 case dwarf::DW_TAG_union_type:
2172 case dwarf::DW_TAG_enumeration_type:
2173 return dwarf::PubIndexEntryDescriptor(
2174 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2175 ? dwarf::GIEL_STATIC
2176 : dwarf::GIEL_EXTERNAL);
2177 case dwarf::DW_TAG_typedef:
2178 case dwarf::DW_TAG_base_type:
2179 case dwarf::DW_TAG_subrange_type:
2180 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2181 case dwarf::DW_TAG_namespace:
2182 return dwarf::GIEK_TYPE;
2183 case dwarf::DW_TAG_subprogram:
2184 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2185 case dwarf::DW_TAG_constant:
2186 case dwarf::DW_TAG_variable:
2187 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2188 case dwarf::DW_TAG_enumerator:
2189 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2190 dwarf::GIEL_STATIC);
2192 return dwarf::GIEK_NONE;
2196 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2198 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2199 const MCSection *PSec =
2200 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2201 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2203 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2206 void DwarfDebug::emitDebugPubSection(
2207 bool GnuStyle, const MCSection *PSec, StringRef Name,
2208 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2209 for (const auto &NU : CUMap) {
2210 DwarfCompileUnit *TheU = NU.second;
2212 const auto &Globals = (TheU->*Accessor)();
2214 if (Globals.empty())
2217 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2219 unsigned ID = TheU->getUniqueID();
2221 // Start the dwarf pubnames section.
2222 Asm->OutStreamer.SwitchSection(PSec);
2225 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2226 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2227 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2228 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2230 Asm->OutStreamer.EmitLabel(BeginLabel);
2232 Asm->OutStreamer.AddComment("DWARF Version");
2233 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2235 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2236 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2238 Asm->OutStreamer.AddComment("Compilation Unit Length");
2239 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2241 // Emit the pubnames for this compilation unit.
2242 for (const auto &GI : Globals) {
2243 const char *Name = GI.getKeyData();
2244 const DIE *Entity = GI.second;
2246 Asm->OutStreamer.AddComment("DIE offset");
2247 Asm->EmitInt32(Entity->getOffset());
2250 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2251 Asm->OutStreamer.AddComment(
2252 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2253 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2254 Asm->EmitInt8(Desc.toBits());
2257 Asm->OutStreamer.AddComment("External Name");
2258 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2261 Asm->OutStreamer.AddComment("End Mark");
2263 Asm->OutStreamer.EmitLabel(EndLabel);
2267 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2268 const MCSection *PSec =
2269 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2270 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2272 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2275 // Emit strings into a string section.
2276 void DwarfFile::emitStrings(const MCSection *StrSection,
2277 const MCSection *OffsetSection = NULL,
2278 const MCSymbol *StrSecSym = NULL) {
2280 if (StringPool.empty())
2283 // Start the dwarf str section.
2284 Asm->OutStreamer.SwitchSection(StrSection);
2286 // Get all of the string pool entries and put them in an array by their ID so
2287 // we can sort them.
2288 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2290 for (const auto &I : StringPool)
2291 Entries.push_back(std::make_pair(I.second.second, &I));
2293 array_pod_sort(Entries.begin(), Entries.end());
2295 for (const auto &Entry : Entries) {
2296 // Emit a label for reference from debug information entries.
2297 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2299 // Emit the string itself with a terminating null byte.
2300 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2301 Entry.second->getKeyLength() + 1));
2304 // If we've got an offset section go ahead and emit that now as well.
2305 if (OffsetSection) {
2306 Asm->OutStreamer.SwitchSection(OffsetSection);
2307 unsigned offset = 0;
2308 unsigned size = 4; // FIXME: DWARF64 is 8.
2309 for (const auto &Entry : Entries) {
2310 Asm->OutStreamer.EmitIntValue(offset, size);
2311 offset += Entry.second->getKeyLength() + 1;
2316 // Emit addresses into the section given.
2317 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2319 if (AddressPool.empty())
2322 // Start the dwarf addr section.
2323 Asm->OutStreamer.SwitchSection(AddrSection);
2325 // Order the address pool entries by ID
2326 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2328 for (const auto &I : AddressPool)
2329 Entries[I.second.Number] =
2331 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2332 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2334 for (const MCExpr *Entry : Entries)
2335 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2338 // Emit visible names into a debug str section.
2339 void DwarfDebug::emitDebugStr() {
2340 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2341 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2344 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2345 const DotDebugLocEntry &Entry) {
2346 DIVariable DV(Entry.getVariable());
2347 if (Entry.isInt()) {
2348 DIBasicType BTy(DV.getType());
2349 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2350 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2351 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2352 Streamer.EmitSLEB128(Entry.getInt());
2354 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2355 Streamer.EmitULEB128(Entry.getInt());
2357 } else if (Entry.isLocation()) {
2358 MachineLocation Loc = Entry.getLoc();
2359 if (!DV.hasComplexAddress())
2361 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2363 // Complex address entry.
2364 unsigned N = DV.getNumAddrElements();
2366 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2367 if (Loc.getOffset()) {
2369 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2370 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2371 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2372 Streamer.EmitSLEB128(DV.getAddrElement(1));
2374 // If first address element is OpPlus then emit
2375 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2376 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2377 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2381 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2384 // Emit remaining complex address elements.
2385 for (; i < N; ++i) {
2386 uint64_t Element = DV.getAddrElement(i);
2387 if (Element == DIBuilder::OpPlus) {
2388 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2389 Streamer.EmitULEB128(DV.getAddrElement(++i));
2390 } else if (Element == DIBuilder::OpDeref) {
2392 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2394 llvm_unreachable("unknown Opcode found in complex address");
2398 // else ... ignore constant fp. There is not any good way to
2399 // to represent them here in dwarf.
2403 // Emit locations into the debug loc section.
2404 void DwarfDebug::emitDebugLoc() {
2405 if (DotDebugLocEntries.empty())
2408 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2409 I = DotDebugLocEntries.begin(),
2410 E = DotDebugLocEntries.end();
2412 DotDebugLocEntry &Entry = *I;
2413 if (I + 1 != DotDebugLocEntries.end())
2417 // Start the dwarf loc section.
2418 Asm->OutStreamer.SwitchSection(
2419 Asm->getObjFileLowering().getDwarfLocSection());
2420 unsigned char Size = Asm->getDataLayout().getPointerSize();
2421 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2423 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2424 I = DotDebugLocEntries.begin(),
2425 E = DotDebugLocEntries.end();
2426 I != E; ++I, ++index) {
2427 const DotDebugLocEntry &Entry = *I;
2428 if (Entry.isMerged())
2431 if (Entry.isEmpty()) {
2432 Asm->OutStreamer.EmitIntValue(0, Size);
2433 Asm->OutStreamer.EmitIntValue(0, Size);
2434 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2436 // Set up the range.
2437 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2438 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2439 Asm->OutStreamer.AddComment("Loc expr size");
2440 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2441 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2442 Asm->EmitLabelDifference(end, begin, 2);
2443 Asm->OutStreamer.EmitLabel(begin);
2445 APByteStreamer Streamer(*Asm);
2446 emitDebugLocEntry(Streamer, Entry);
2448 Asm->OutStreamer.EmitLabel(end);
2454 const MCSymbol *Start, *End;
2457 // Emit a debug aranges section, containing a CU lookup for any
2458 // address we can tie back to a CU.
2459 void DwarfDebug::emitDebugARanges() {
2460 // Start the dwarf aranges section.
2461 Asm->OutStreamer.SwitchSection(
2462 Asm->getObjFileLowering().getDwarfARangesSection());
2464 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2468 // Build a list of sections used.
2469 std::vector<const MCSection *> Sections;
2470 for (const auto &it : SectionMap) {
2471 const MCSection *Section = it.first;
2472 Sections.push_back(Section);
2475 // Sort the sections into order.
2476 // This is only done to ensure consistent output order across different runs.
2477 std::sort(Sections.begin(), Sections.end(), SectionSort);
2479 // Build a set of address spans, sorted by CU.
2480 for (const MCSection *Section : Sections) {
2481 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2482 if (List.size() < 2)
2485 // Sort the symbols by offset within the section.
2486 std::sort(List.begin(), List.end(),
2487 [&](const SymbolCU &A, const SymbolCU &B) {
2488 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2489 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2491 // Symbols with no order assigned should be placed at the end.
2492 // (e.g. section end labels)
2500 // If we have no section (e.g. common), just write out
2501 // individual spans for each symbol.
2502 if (Section == NULL) {
2503 for (const SymbolCU &Cur : List) {
2505 Span.Start = Cur.Sym;
2508 Spans[Cur.CU].push_back(Span);
2511 // Build spans between each label.
2512 const MCSymbol *StartSym = List[0].Sym;
2513 for (size_t n = 1, e = List.size(); n < e; n++) {
2514 const SymbolCU &Prev = List[n - 1];
2515 const SymbolCU &Cur = List[n];
2517 // Try and build the longest span we can within the same CU.
2518 if (Cur.CU != Prev.CU) {
2520 Span.Start = StartSym;
2522 Spans[Prev.CU].push_back(Span);
2529 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2531 // Build a list of CUs used.
2532 std::vector<DwarfCompileUnit *> CUs;
2533 for (const auto &it : Spans) {
2534 DwarfCompileUnit *CU = it.first;
2538 // Sort the CU list (again, to ensure consistent output order).
2539 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2540 return A->getUniqueID() < B->getUniqueID();
2543 // Emit an arange table for each CU we used.
2544 for (DwarfCompileUnit *CU : CUs) {
2545 std::vector<ArangeSpan> &List = Spans[CU];
2547 // Emit size of content not including length itself.
2548 unsigned ContentSize =
2549 sizeof(int16_t) + // DWARF ARange version number
2550 sizeof(int32_t) + // Offset of CU in the .debug_info section
2551 sizeof(int8_t) + // Pointer Size (in bytes)
2552 sizeof(int8_t); // Segment Size (in bytes)
2554 unsigned TupleSize = PtrSize * 2;
2556 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2558 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2560 ContentSize += Padding;
2561 ContentSize += (List.size() + 1) * TupleSize;
2563 // For each compile unit, write the list of spans it covers.
2564 Asm->OutStreamer.AddComment("Length of ARange Set");
2565 Asm->EmitInt32(ContentSize);
2566 Asm->OutStreamer.AddComment("DWARF Arange version number");
2567 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2568 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2569 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2570 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2571 Asm->EmitInt8(PtrSize);
2572 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2575 Asm->OutStreamer.EmitFill(Padding, 0xff);
2577 for (const ArangeSpan &Span : List) {
2578 Asm->EmitLabelReference(Span.Start, PtrSize);
2580 // Calculate the size as being from the span start to it's end.
2582 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2584 // For symbols without an end marker (e.g. common), we
2585 // write a single arange entry containing just that one symbol.
2586 uint64_t Size = SymSize[Span.Start];
2590 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2594 Asm->OutStreamer.AddComment("ARange terminator");
2595 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2596 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2600 // Emit visible names into a debug ranges section.
2601 void DwarfDebug::emitDebugRanges() {
2602 // Start the dwarf ranges section.
2603 Asm->OutStreamer.SwitchSection(
2604 Asm->getObjFileLowering().getDwarfRangesSection());
2606 // Size for our labels.
2607 unsigned char Size = Asm->getDataLayout().getPointerSize();
2609 // Grab the specific ranges for the compile units in the module.
2610 for (const auto &I : CUMap) {
2611 DwarfCompileUnit *TheCU = I.second;
2613 // Emit a symbol so we can find the beginning of our ranges.
2614 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2616 // Iterate over the misc ranges for the compile units in the module.
2617 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2618 // Emit our symbol so we can find the beginning of the range.
2619 Asm->OutStreamer.EmitLabel(List.getSym());
2621 for (const RangeSpan &Range : List.getRanges()) {
2622 const MCSymbol *Begin = Range.getStart();
2623 const MCSymbol *End = Range.getEnd();
2624 assert(Begin && "Range without a begin symbol?");
2625 assert(End && "Range without an end symbol?");
2626 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2627 Asm->OutStreamer.EmitSymbolValue(End, Size);
2630 // And terminate the list with two 0 values.
2631 Asm->OutStreamer.EmitIntValue(0, Size);
2632 Asm->OutStreamer.EmitIntValue(0, Size);
2635 // Now emit a range for the CU itself.
2636 if (useCURanges() && TheCU->getRanges().size()) {
2637 Asm->OutStreamer.EmitLabel(
2638 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2639 for (const RangeSpan &Range : TheCU->getRanges()) {
2640 const MCSymbol *Begin = Range.getStart();
2641 const MCSymbol *End = Range.getEnd();
2642 assert(Begin && "Range without a begin symbol?");
2643 assert(End && "Range without an end symbol?");
2644 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2645 Asm->OutStreamer.EmitSymbolValue(End, Size);
2647 // And terminate the list with two 0 values.
2648 Asm->OutStreamer.EmitIntValue(0, Size);
2649 Asm->OutStreamer.EmitIntValue(0, Size);
2654 // DWARF5 Experimental Separate Dwarf emitters.
2656 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2658 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2659 U->getCUNode().getSplitDebugFilename());
2661 // Relocate to the beginning of the addr_base section, else 0 for the
2662 // beginning of the one for this compile unit.
2663 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2664 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2666 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2668 if (!CompilationDir.empty())
2669 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2671 addGnuPubAttributes(NewU, Die);
2673 SkeletonHolder.addUnit(NewU);
2676 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2677 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2678 // DW_AT_ranges_base, DW_AT_addr_base.
2679 // TODO: Implement DW_AT_ranges_base.
2680 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2682 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2683 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2684 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2685 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2686 DwarfInfoSectionSym);
2688 NewCU->initStmtList(DwarfLineSectionSym);
2690 initSkeletonUnit(CU, Die, NewCU);
2695 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2697 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2698 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2699 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2701 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2702 DwarfTypeUnit *NewTU =
2703 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2704 NewTU->setTypeSignature(TU->getTypeSignature());
2705 NewTU->setType(NULL);
2707 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2708 CU.applyStmtList(*Die);
2710 initSkeletonUnit(TU, Die, NewTU);
2714 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2715 // compile units that would normally be in debug_info.
2716 void DwarfDebug::emitDebugInfoDWO() {
2717 assert(useSplitDwarf() && "No split dwarf debug info?");
2718 InfoHolder.emitUnits(this,
2719 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2720 DwarfAbbrevDWOSectionSym);
2723 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2724 // abbreviations for the .debug_info.dwo section.
2725 void DwarfDebug::emitDebugAbbrevDWO() {
2726 assert(useSplitDwarf() && "No split dwarf?");
2727 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2730 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2731 // string section and is identical in format to traditional .debug_str
2733 void DwarfDebug::emitDebugStrDWO() {
2734 assert(useSplitDwarf() && "No split dwarf?");
2735 const MCSection *OffSec =
2736 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2737 const MCSymbol *StrSym = DwarfStrSectionSym;
2738 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2742 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2743 StringRef Identifier, DIE *RefDie,
2744 DICompositeType CTy) {
2745 // Flag the type unit reference as a declaration so that if it contains
2746 // members (implicit special members, static data member definitions, member
2747 // declarations for definitions in this CU, etc) consumers don't get confused
2748 // and think this is a full definition.
2749 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2751 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2753 CU.addDIETypeSignature(RefDie, *TU);
2757 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2758 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2759 UnitDie, CU, Asm, this, &InfoHolder);
2761 InfoHolder.addUnit(NewTU);
2763 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2767 Hash.update(Identifier);
2768 // ... take the least significant 8 bytes and return those. Our MD5
2769 // implementation always returns its results in little endian, swap bytes
2771 MD5::MD5Result Result;
2773 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2774 NewTU->setTypeSignature(Signature);
2775 if (useSplitDwarf())
2776 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2778 CU.applyStmtList(*UnitDie);
2780 NewTU->setType(NewTU->createTypeDIE(CTy));
2784 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2785 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2787 CU.addDIETypeSignature(RefDie, *NewTU);
2790 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2791 MCSymbol *Begin, MCSymbol *End) {
2792 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2793 if (DwarfVersion < 4)
2794 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2796 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);