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 "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
54 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
55 cl::desc("Disable debug info printing"));
57 static cl::opt<bool> UnknownLocations(
58 "use-unknown-locations", cl::Hidden,
59 cl::desc("Make an absence of debug location information explicit."),
62 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
63 cl::desc("Add the CU hash as the dwo_id."),
67 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
68 cl::desc("Generate GNU-style pubnames and pubtypes"),
71 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73 cl::desc("Generate dwarf aranges"),
77 enum DefaultOnOff { Default, Enable, Disable };
80 static cl::opt<DefaultOnOff>
81 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
82 cl::desc("Output prototype dwarf accelerator tables."),
83 cl::values(clEnumVal(Default, "Default for platform"),
84 clEnumVal(Enable, "Enabled"),
85 clEnumVal(Disable, "Disabled"), clEnumValEnd),
88 static cl::opt<DefaultOnOff>
89 SplitDwarf("split-dwarf", cl::Hidden,
90 cl::desc("Output DWARF5 split debug info."),
91 cl::values(clEnumVal(Default, "Default for platform"),
92 clEnumVal(Enable, "Enabled"),
93 clEnumVal(Disable, "Disabled"), clEnumValEnd),
96 static cl::opt<DefaultOnOff>
97 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
98 cl::desc("Generate DWARF pubnames and pubtypes sections"),
99 cl::values(clEnumVal(Default, "Default for platform"),
100 clEnumVal(Enable, "Enabled"),
101 clEnumVal(Disable, "Disabled"), clEnumValEnd),
104 static cl::opt<unsigned>
105 DwarfVersionNumber("dwarf-version", cl::Hidden,
106 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
109 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
110 cl::desc("Generate DW_AT_ranges for compile units"),
113 static const char *const DWARFGroupName = "DWARF Emission";
114 static const char *const DbgTimerName = "DWARF Debug Writer";
116 //===----------------------------------------------------------------------===//
120 /// resolve - Look in the DwarfDebug map for the MDNode that
121 /// corresponds to the reference.
122 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
123 return DD->resolve(Ref);
126 DIType DbgVariable::getType() const {
127 DIType Ty = Var.getType();
128 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
129 // addresses instead.
130 if (Var.isBlockByrefVariable()) {
131 /* Byref variables, in Blocks, are declared by the programmer as
132 "SomeType VarName;", but the compiler creates a
133 __Block_byref_x_VarName struct, and gives the variable VarName
134 either the struct, or a pointer to the struct, as its type. This
135 is necessary for various behind-the-scenes things the compiler
136 needs to do with by-reference variables in blocks.
138 However, as far as the original *programmer* is concerned, the
139 variable should still have type 'SomeType', as originally declared.
141 The following function dives into the __Block_byref_x_VarName
142 struct to find the original type of the variable. This will be
143 passed back to the code generating the type for the Debug
144 Information Entry for the variable 'VarName'. 'VarName' will then
145 have the original type 'SomeType' in its debug information.
147 The original type 'SomeType' will be the type of the field named
148 'VarName' inside the __Block_byref_x_VarName struct.
150 NOTE: In order for this to not completely fail on the debugger
151 side, the Debug Information Entry for the variable VarName needs to
152 have a DW_AT_location that tells the debugger how to unwind through
153 the pointers and __Block_byref_x_VarName struct to find the actual
154 value of the variable. The function addBlockByrefType does this. */
156 uint16_t tag = Ty.getTag();
158 if (tag == dwarf::DW_TAG_pointer_type)
159 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
161 DIArray Elements = DICompositeType(subType).getTypeArray();
162 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
163 DIDerivedType DT(Elements.getElement(i));
164 if (getName() == DT.getName())
165 return (resolve(DT.getTypeDerivedFrom()));
171 } // end llvm namespace
173 /// Return Dwarf Version by checking module flags.
174 static unsigned getDwarfVersionFromModule(const Module *M) {
175 Value *Val = M->getModuleFlag("Dwarf Version");
177 return dwarf::DWARF_VERSION;
178 return cast<ConstantInt>(Val)->getZExtValue();
181 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
182 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
183 PrevLabel(NULL), GlobalRangeCount(0),
184 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
185 UsedNonDefaultText(false),
186 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
188 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
189 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
190 DwarfAddrSectionSym = 0;
191 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
192 FunctionBeginSym = FunctionEndSym = 0;
196 // Turn on accelerator tables for Darwin by default, pubnames by
197 // default for non-Darwin, and handle split dwarf.
198 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
200 if (DwarfAccelTables == Default)
201 HasDwarfAccelTables = IsDarwin;
203 HasDwarfAccelTables = DwarfAccelTables == Enable;
205 if (SplitDwarf == Default)
206 HasSplitDwarf = false;
208 HasSplitDwarf = SplitDwarf == Enable;
210 if (DwarfPubSections == Default)
211 HasDwarfPubSections = !IsDarwin;
213 HasDwarfPubSections = DwarfPubSections == Enable;
215 DwarfVersion = DwarfVersionNumber
217 : getDwarfVersionFromModule(MMI->getModule());
220 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
225 // Switch to the specified MCSection and emit an assembler
226 // temporary label to it if SymbolStem is specified.
227 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
228 const char *SymbolStem = 0) {
229 Asm->OutStreamer.SwitchSection(Section);
233 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
234 Asm->OutStreamer.EmitLabel(TmpSym);
238 DwarfFile::~DwarfFile() {
239 for (DwarfUnit *DU : CUs)
243 MCSymbol *DwarfFile::getStringPoolSym() {
244 return Asm->GetTempSymbol(StringPref);
247 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
258 std::pair<MCSymbol *, unsigned> &Entry =
259 StringPool.GetOrCreateValue(Str).getValue();
263 Entry.second = NextStringPoolNumber++;
264 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
269 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
270 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
272 ++NextAddrPoolNumber;
273 return P.first->second.Number;
276 // Define a unique number for the abbreviation.
278 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
279 // Check the set for priors.
280 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
282 // If it's newly added.
283 if (InSet == &Abbrev) {
284 // Add to abbreviation list.
285 Abbreviations.push_back(&Abbrev);
287 // Assign the vector position + 1 as its number.
288 Abbrev.setNumber(Abbreviations.size());
290 // Assign existing abbreviation number.
291 Abbrev.setNumber(InSet->getNumber());
295 static bool isObjCClass(StringRef Name) {
296 return Name.startswith("+") || Name.startswith("-");
299 static bool hasObjCCategory(StringRef Name) {
300 if (!isObjCClass(Name))
303 return Name.find(") ") != StringRef::npos;
306 static void getObjCClassCategory(StringRef In, StringRef &Class,
307 StringRef &Category) {
308 if (!hasObjCCategory(In)) {
309 Class = In.slice(In.find('[') + 1, In.find(' '));
314 Class = In.slice(In.find('[') + 1, In.find('('));
315 Category = In.slice(In.find('[') + 1, In.find(' '));
319 static StringRef getObjCMethodName(StringRef In) {
320 return In.slice(In.find(' ') + 1, In.find(']'));
323 // Helper for sorting sections into a stable output order.
324 static bool SectionSort(const MCSection *A, const MCSection *B) {
325 std::string LA = (A ? A->getLabelBeginName() : "");
326 std::string LB = (B ? B->getLabelBeginName() : "");
330 // Add the various names to the Dwarf accelerator table names.
331 // TODO: Determine whether or not we should add names for programs
332 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
333 // is only slightly different than the lookup of non-standard ObjC names.
334 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
335 if (!SP.isDefinition())
337 TheU->addAccelName(SP.getName(), Die);
339 // If the linkage name is different than the name, go ahead and output
340 // that as well into the name table.
341 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
342 TheU->addAccelName(SP.getLinkageName(), Die);
344 // If this is an Objective-C selector name add it to the ObjC accelerator
346 if (isObjCClass(SP.getName())) {
347 StringRef Class, Category;
348 getObjCClassCategory(SP.getName(), Class, Category);
349 TheU->addAccelObjC(Class, Die);
351 TheU->addAccelObjC(Category, Die);
352 // Also add the base method name to the name table.
353 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
357 /// isSubprogramContext - Return true if Context is either a subprogram
358 /// or another context nested inside a subprogram.
359 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
362 DIDescriptor D(Context);
363 if (D.isSubprogram())
366 return isSubprogramContext(resolve(DIType(Context).getContext()));
370 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
371 // and DW_AT_high_pc attributes. If there are global variables in this
372 // scope then create and insert DIEs for these variables.
373 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
375 DIE *SPDie = SPCU->getDIE(SP);
377 assert(SPDie && "Unable to find subprogram DIE!");
379 // If we're updating an abstract DIE, then we will be adding the children and
380 // object pointer later on. But what we don't want to do is process the
381 // concrete DIE twice.
382 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
383 // Pick up abstract subprogram DIE.
385 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
386 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
388 DISubprogram SPDecl = SP.getFunctionDeclaration();
389 if (!SPDecl.isSubprogram()) {
390 // There is not any need to generate specification DIE for a function
391 // defined at compile unit level. If a function is defined inside another
392 // function then gdb prefers the definition at top level and but does not
393 // expect specification DIE in parent function. So avoid creating
394 // specification DIE for a function defined inside a function.
395 DIScope SPContext = resolve(SP.getContext());
396 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
397 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
398 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
401 DICompositeType SPTy = SP.getType();
402 DIArray Args = SPTy.getTypeArray();
403 uint16_t SPTag = SPTy.getTag();
404 if (SPTag == dwarf::DW_TAG_subroutine_type)
405 SPCU->constructSubprogramArguments(*SPDie, Args);
406 DIE *SPDeclDie = SPDie;
407 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
408 *SPCU->getUnitDie());
409 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
414 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
416 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
417 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
418 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
420 // Add name to the name table, we do this here because we're guaranteed
421 // to have concrete versions of our DW_TAG_subprogram nodes.
422 addSubprogramNames(SPCU, SP, SPDie);
427 /// Check whether we should create a DIE for the given Scope, return true
428 /// if we don't create a DIE (the corresponding DIE is null).
429 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
430 if (Scope->isAbstractScope())
433 // We don't create a DIE if there is no Range.
434 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
438 if (Ranges.size() > 1)
441 // We don't create a DIE if we have a single Range and the end label
443 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
444 MCSymbol *End = getLabelAfterInsn(RI->second);
448 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
449 dwarf::Attribute A, const MCSymbol *L,
450 const MCSymbol *Sec) {
451 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
452 U->addSectionLabel(D, A, L);
454 U->addSectionDelta(D, A, L, Sec);
457 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
458 const SmallVectorImpl<InsnRange> &Range) {
459 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
460 // emitting it appropriately.
461 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
462 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
463 DwarfDebugRangeSectionSym);
465 RangeSpanList List(RangeSym);
466 for (const InsnRange &R : Range) {
467 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
468 List.addRange(std::move(Span));
471 // Add the range list to the set of ranges to be emitted.
472 TheCU->addRangeList(std::move(List));
475 // Construct new DW_TAG_lexical_block for this scope and attach
476 // DW_AT_low_pc/DW_AT_high_pc labels.
477 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
478 LexicalScope *Scope) {
479 if (isLexicalScopeDIENull(Scope))
482 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
483 if (Scope->isAbstractScope())
486 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
488 // If we have multiple ranges, emit them into the range section.
489 if (ScopeRanges.size() > 1) {
490 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
494 // Construct the address range for this DIE.
495 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
496 MCSymbol *Start = getLabelBeforeInsn(RI->first);
497 MCSymbol *End = getLabelAfterInsn(RI->second);
498 assert(End && "End label should not be null!");
500 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
501 assert(End->isDefined() && "Invalid end label for an inlined scope!");
503 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
504 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
509 // This scope represents inlined body of a function. Construct DIE to
510 // represent this concrete inlined copy of the function.
511 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
512 LexicalScope *Scope) {
513 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
514 assert(!ScopeRanges.empty() &&
515 "LexicalScope does not have instruction markers!");
517 if (!Scope->getScopeNode())
519 DIScope DS(Scope->getScopeNode());
520 DISubprogram InlinedSP = getDISubprogram(DS);
521 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
523 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
527 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
528 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
530 // If we have multiple ranges, emit them into the range section.
531 if (ScopeRanges.size() > 1)
532 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
534 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
535 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
536 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
538 if (StartLabel == 0 || EndLabel == 0)
539 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
541 assert(StartLabel->isDefined() &&
542 "Invalid starting label for an inlined scope!");
543 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
545 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
546 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
549 InlinedSubprogramDIEs.insert(OriginDIE);
551 // Add the call site information to the DIE.
552 DILocation DL(Scope->getInlinedAt());
553 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
554 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
555 TheCU->getUniqueID()));
556 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
558 // Add name to the name table, we do this here because we're guaranteed
559 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
560 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
565 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
567 SmallVectorImpl<DIE *> &Children) {
568 DIE *ObjectPointer = NULL;
570 // Collect arguments for current function.
571 if (LScopes.isCurrentFunctionScope(Scope)) {
572 for (DbgVariable *ArgDV : CurrentFnArguments)
575 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
576 Children.push_back(Arg);
577 if (ArgDV->isObjectPointer())
581 // If this is a variadic function, add an unspecified parameter.
582 DISubprogram SP(Scope->getScopeNode());
583 DIArray FnArgs = SP.getType().getTypeArray();
584 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
585 .isUnspecifiedParameter()) {
586 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
587 Children.push_back(Ellipsis);
591 // Collect lexical scope children first.
592 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
593 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
594 Scope->isAbstractScope())) {
595 Children.push_back(Variable);
596 if (DV->isObjectPointer())
597 ObjectPointer = Variable;
599 for (LexicalScope *LS : Scope->getChildren())
600 if (DIE *Nested = constructScopeDIE(TheCU, LS))
601 Children.push_back(Nested);
602 return ObjectPointer;
605 // Construct a DIE for this scope.
606 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
607 LexicalScope *Scope) {
608 if (!Scope || !Scope->getScopeNode())
611 DIScope DS(Scope->getScopeNode());
613 SmallVector<DIE *, 8> Children;
614 DIE *ObjectPointer = NULL;
615 bool ChildrenCreated = false;
617 // We try to create the scope DIE first, then the children DIEs. This will
618 // avoid creating un-used children then removing them later when we find out
619 // the scope DIE is null.
620 DIE *ScopeDIE = NULL;
621 if (Scope->getInlinedAt())
622 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
623 else if (DS.isSubprogram()) {
624 ProcessedSPNodes.insert(DS);
625 if (Scope->isAbstractScope()) {
626 ScopeDIE = TheCU->getDIE(DS);
627 // Note down abstract DIE.
629 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
631 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
633 // Early exit when we know the scope DIE is going to be null.
634 if (isLexicalScopeDIENull(Scope))
637 // We create children here when we know the scope DIE is not going to be
638 // null and the children will be added to the scope DIE.
639 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
640 ChildrenCreated = true;
642 // There is no need to emit empty lexical block DIE.
643 std::pair<ImportedEntityMap::const_iterator,
644 ImportedEntityMap::const_iterator> Range =
646 ScopesWithImportedEntities.begin(),
647 ScopesWithImportedEntities.end(),
648 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
650 if (Children.empty() && Range.first == Range.second)
652 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
653 assert(ScopeDIE && "Scope DIE should not be null.");
654 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
656 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
660 assert(Children.empty() &&
661 "We create children only when the scope DIE is not null.");
664 if (!ChildrenCreated)
665 // We create children when the scope DIE is not null.
666 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
669 for (DIE *I : Children)
670 ScopeDIE->addChild(I);
672 if (DS.isSubprogram() && ObjectPointer != NULL)
673 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
678 // Look up the source id with the given directory and source file names.
679 // If none currently exists, create a new id and insert it in the
680 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
682 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
684 // If we print assembly, we can't separate .file entries according to
685 // compile units. Thus all files will belong to the default compile unit.
687 // FIXME: add a better feature test than hasRawTextSupport. Even better,
688 // extend .file to support this.
689 if (Asm->OutStreamer.hasRawTextSupport())
692 // If FE did not provide a file name, then assume stdin.
693 if (FileName.empty())
694 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
696 // TODO: this might not belong here. See if we can factor this better.
697 if (DirName == CompilationDir)
700 // FileIDCUMap stores the current ID for the given compile unit.
701 unsigned SrcId = FileIDCUMap[CUID] + 1;
703 // We look up the CUID/file/dir by concatenating them with a zero byte.
704 SmallString<128> NamePair;
705 NamePair += utostr(CUID);
708 NamePair += '\0'; // Zero bytes are not allowed in paths.
709 NamePair += FileName;
711 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
712 if (Ent.getValue() != SrcId)
713 return Ent.getValue();
715 FileIDCUMap[CUID] = SrcId;
716 // Print out a .file directive to specify files for .loc directives.
717 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
722 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
723 if (!GenerateGnuPubSections)
726 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
729 // Create new DwarfCompileUnit for the given metadata node with tag
730 // DW_TAG_compile_unit.
731 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
732 StringRef FN = DIUnit.getFilename();
733 CompilationDir = DIUnit.getDirectory();
735 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
736 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
737 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
738 InfoHolder.addUnit(NewCU);
740 FileIDCUMap[NewCU->getUniqueID()] = 0;
742 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
743 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
744 DIUnit.getLanguage());
745 NewCU->addString(Die, dwarf::DW_AT_name, FN);
747 if (!useSplitDwarf()) {
748 NewCU->initStmtList(DwarfLineSectionSym);
750 // If we're using split dwarf the compilation dir is going to be in the
751 // skeleton CU and so we don't need to duplicate it here.
752 if (!CompilationDir.empty())
753 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
755 addGnuPubAttributes(NewCU, Die);
758 if (DIUnit.isOptimized())
759 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
761 StringRef Flags = DIUnit.getFlags();
763 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
765 if (unsigned RVer = DIUnit.getRunTimeVersion())
766 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
767 dwarf::DW_FORM_data1, RVer);
772 if (useSplitDwarf()) {
773 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
774 DwarfInfoDWOSectionSym);
775 NewCU->setSkeleton(constructSkeletonCU(NewCU));
777 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
778 DwarfInfoSectionSym);
780 CUMap.insert(std::make_pair(DIUnit, NewCU));
781 CUDieMap.insert(std::make_pair(Die, NewCU));
785 // Construct subprogram DIE.
786 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
788 // FIXME: We should only call this routine once, however, during LTO if a
789 // program is defined in multiple CUs we could end up calling it out of
790 // beginModule as we walk the CUs.
792 DwarfCompileUnit *&CURef = SPMap[N];
798 if (!SP.isDefinition())
799 // This is a method declaration which will be handled while constructing
803 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
805 // Expose as a global name.
806 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
809 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
811 DIImportedEntity Module(N);
812 assert(Module.Verify());
813 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
814 constructImportedEntityDIE(TheCU, Module, D);
817 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
818 const MDNode *N, DIE *Context) {
819 DIImportedEntity Module(N);
820 assert(Module.Verify());
821 return constructImportedEntityDIE(TheCU, Module, Context);
824 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
825 const DIImportedEntity &Module,
827 assert(Module.Verify() &&
828 "Use one of the MDNode * overloads to handle invalid metadata");
829 assert(Context && "Should always have a context for an imported_module");
830 DIE *IMDie = new DIE(Module.getTag());
831 TheCU->insertDIE(Module, IMDie);
833 DIDescriptor Entity = Module.getEntity();
834 if (Entity.isNameSpace())
835 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
836 else if (Entity.isSubprogram())
837 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
838 else if (Entity.isType())
839 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
841 EntityDie = TheCU->getDIE(Entity);
842 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
843 Module.getContext().getDirectory(),
844 TheCU->getUniqueID());
845 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
846 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
847 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
848 StringRef Name = Module.getName();
850 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
851 Context->addChild(IMDie);
854 // Emit all Dwarf sections that should come prior to the content. Create
855 // global DIEs and emit initial debug info sections. This is invoked by
856 // the target AsmPrinter.
857 void DwarfDebug::beginModule() {
858 if (DisableDebugInfoPrinting)
861 const Module *M = MMI->getModule();
863 // If module has named metadata anchors then use them, otherwise scan the
864 // module using debug info finder to collect debug info.
865 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
868 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
870 // Emit initial sections so we can reference labels later.
873 for (MDNode *N : CU_Nodes->operands()) {
874 DICompileUnit CUNode(N);
875 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
876 DIArray ImportedEntities = CUNode.getImportedEntities();
877 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
878 ScopesWithImportedEntities.push_back(std::make_pair(
879 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
880 ImportedEntities.getElement(i)));
881 std::sort(ScopesWithImportedEntities.begin(),
882 ScopesWithImportedEntities.end(), less_first());
883 DIArray GVs = CUNode.getGlobalVariables();
884 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
885 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
886 DIArray SPs = CUNode.getSubprograms();
887 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
888 constructSubprogramDIE(CU, SPs.getElement(i));
889 DIArray EnumTypes = CUNode.getEnumTypes();
890 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
891 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
892 DIArray RetainedTypes = CUNode.getRetainedTypes();
893 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
894 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
895 // Emit imported_modules last so that the relevant context is already
897 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
898 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
901 // Tell MMI that we have debug info.
902 MMI->setDebugInfoAvailability(true);
904 // Prime section data.
905 SectionMap[Asm->getObjFileLowering().getTextSection()];
908 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
909 void DwarfDebug::computeInlinedDIEs() {
910 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
911 for (DIE *ISP : InlinedSubprogramDIEs)
912 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
914 for (const auto &AI : AbstractSPDies) {
915 DIE *ISP = AI.second;
916 if (InlinedSubprogramDIEs.count(ISP))
918 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
922 // Collect info for variables that were optimized out.
923 void DwarfDebug::collectDeadVariables() {
924 const Module *M = MMI->getModule();
926 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
927 for (MDNode *N : CU_Nodes->operands()) {
928 DICompileUnit TheCU(N);
929 DIArray Subprograms = TheCU.getSubprograms();
930 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
931 DISubprogram SP(Subprograms.getElement(i));
932 if (ProcessedSPNodes.count(SP) != 0)
934 if (!SP.isSubprogram())
936 if (!SP.isDefinition())
938 DIArray Variables = SP.getVariables();
939 if (Variables.getNumElements() == 0)
942 // Construct subprogram DIE and add variables DIEs.
943 DwarfCompileUnit *SPCU =
944 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
945 assert(SPCU && "Unable to find Compile Unit!");
946 // FIXME: See the comment in constructSubprogramDIE about duplicate
948 constructSubprogramDIE(SPCU, SP);
949 DIE *SPDIE = SPCU->getDIE(SP);
950 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
951 DIVariable DV(Variables.getElement(vi));
952 if (!DV.isVariable())
954 DbgVariable NewVar(DV, NULL, this);
955 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
956 SPDIE->addChild(VariableDIE);
963 void DwarfDebug::finalizeModuleInfo() {
964 // Collect info for variables that were optimized out.
965 collectDeadVariables();
967 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
968 computeInlinedDIEs();
970 // Handle anything that needs to be done on a per-unit basis after
971 // all other generation.
972 for (DwarfUnit *TheU : getUnits()) {
973 // Emit DW_AT_containing_type attribute to connect types with their
974 // vtable holding type.
975 TheU->constructContainingTypeDIEs();
977 // Add CU specific attributes if we need to add any.
978 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
979 // If we're splitting the dwarf out now that we've got the entire
980 // CU then add the dwo id to it.
981 DwarfCompileUnit *SkCU =
982 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
983 if (useSplitDwarf()) {
984 // This should be a unique identifier when we want to build .dwp files.
986 if (GenerateCUHash) {
988 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
990 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
991 dwarf::DW_FORM_data8, ID);
992 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
993 dwarf::DW_FORM_data8, ID);
996 // If we have code split among multiple sections or we've requested
997 // it then emit a DW_AT_ranges attribute on the unit that will remain
998 // in the .o file, otherwise add a DW_AT_low_pc.
999 // FIXME: Also add a high pc if we can.
1000 // FIXME: We should use ranges if we have multiple compile units or
1001 // allow reordering of code ala .subsections_via_symbols in mach-o.
1002 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1003 if (useCURanges() && TheU->getRanges().size()) {
1004 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1005 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1006 DwarfDebugRangeSectionSym);
1008 // A DW_AT_low_pc attribute may also be specified in combination with
1009 // DW_AT_ranges to specify the default base address for use in location
1010 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1011 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1014 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1019 // Compute DIE offsets and sizes.
1020 InfoHolder.computeSizeAndOffsets();
1021 if (useSplitDwarf())
1022 SkeletonHolder.computeSizeAndOffsets();
1025 void DwarfDebug::endSections() {
1026 // Filter labels by section.
1027 for (const SymbolCU &SCU : ArangeLabels) {
1028 if (SCU.Sym->isInSection()) {
1029 // Make a note of this symbol and it's section.
1030 const MCSection *Section = &SCU.Sym->getSection();
1031 if (!Section->getKind().isMetadata())
1032 SectionMap[Section].push_back(SCU);
1034 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1035 // appear in the output. This sucks as we rely on sections to build
1036 // arange spans. We can do it without, but it's icky.
1037 SectionMap[NULL].push_back(SCU);
1041 // Build a list of sections used.
1042 std::vector<const MCSection *> Sections;
1043 for (const auto &it : SectionMap) {
1044 const MCSection *Section = it.first;
1045 Sections.push_back(Section);
1048 // Sort the sections into order.
1049 // This is only done to ensure consistent output order across different runs.
1050 std::sort(Sections.begin(), Sections.end(), SectionSort);
1052 // Add terminating symbols for each section.
1053 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1054 const MCSection *Section = Sections[ID];
1055 MCSymbol *Sym = NULL;
1058 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1059 // if we know the section name up-front. For user-created sections, the
1060 // resulting label may not be valid to use as a label. (section names can
1061 // use a greater set of characters on some systems)
1062 Sym = Asm->GetTempSymbol("debug_end", ID);
1063 Asm->OutStreamer.SwitchSection(Section);
1064 Asm->OutStreamer.EmitLabel(Sym);
1067 // Insert a final terminator.
1068 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1071 // For now only turn on CU ranges if we've explicitly asked for it,
1072 // we have -ffunction-sections enabled, we've emitted a function
1073 // into a unique section, or we're using LTO. If we're using LTO then
1074 // we can't know that any particular function in the module is correlated
1075 // to a particular CU and so we need to be conservative. At this point all
1076 // sections should be finalized except for dwarf sections.
1077 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1078 TargetMachine::getFunctionSections();
1081 // Emit all Dwarf sections that should come after the content.
1082 void DwarfDebug::endModule() {
1089 // End any existing sections.
1090 // TODO: Does this need to happen?
1093 // Finalize the debug info for the module.
1094 finalizeModuleInfo();
1098 // Emit all the DIEs into a debug info section.
1101 // Corresponding abbreviations into a abbrev section.
1102 emitAbbreviations();
1104 // Emit info into a debug loc section.
1107 // Emit info into a debug aranges section.
1108 if (GenerateARangeSection)
1111 // Emit info into a debug ranges section.
1114 if (useSplitDwarf()) {
1117 emitDebugAbbrevDWO();
1118 // Emit DWO addresses.
1119 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1122 // Emit info into the dwarf accelerator table sections.
1123 if (useDwarfAccelTables()) {
1126 emitAccelNamespaces();
1130 // Emit the pubnames and pubtypes sections if requested.
1131 if (HasDwarfPubSections) {
1132 emitDebugPubNames(GenerateGnuPubSections);
1133 emitDebugPubTypes(GenerateGnuPubSections);
1139 // Reset these for the next Module if we have one.
1143 // Find abstract variable, if any, associated with Var.
1144 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1145 DebugLoc ScopeLoc) {
1146 LLVMContext &Ctx = DV->getContext();
1147 // More then one inlined variable corresponds to one abstract variable.
1148 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1149 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1151 return AbsDbgVariable;
1153 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1157 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1158 addScopeVariable(Scope, AbsDbgVariable);
1159 AbstractVariables[Var] = AbsDbgVariable;
1160 return AbsDbgVariable;
1163 // If Var is a current function argument then add it to CurrentFnArguments list.
1164 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1165 if (!LScopes.isCurrentFunctionScope(Scope))
1167 DIVariable DV = Var->getVariable();
1168 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1170 unsigned ArgNo = DV.getArgNumber();
1174 size_t Size = CurrentFnArguments.size();
1176 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1177 // llvm::Function argument size is not good indicator of how many
1178 // arguments does the function have at source level.
1180 CurrentFnArguments.resize(ArgNo * 2);
1181 CurrentFnArguments[ArgNo - 1] = Var;
1185 // Collect variable information from side table maintained by MMI.
1186 void DwarfDebug::collectVariableInfoFromMMITable(
1187 SmallPtrSet<const MDNode *, 16> &Processed) {
1188 for (const auto &VI : MMI->getVariableDbgInfo()) {
1189 const MDNode *Var = VI.first;
1192 Processed.insert(Var);
1194 const std::pair<unsigned, DebugLoc> &VP = VI.second;
1196 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1198 // If variable scope is not found then skip this variable.
1202 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1203 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1204 RegVar->setFrameIndex(VP.first);
1205 if (!addCurrentFnArgument(RegVar, Scope))
1206 addScopeVariable(Scope, RegVar);
1208 AbsDbgVariable->setFrameIndex(VP.first);
1212 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1214 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1215 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1216 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1217 MI->getOperand(0).getReg() &&
1218 (MI->getOperand(1).isImm() ||
1219 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1222 // Get .debug_loc entry for the instruction range starting at MI.
1223 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1224 const MCSymbol *FLabel,
1225 const MCSymbol *SLabel,
1226 const MachineInstr *MI) {
1227 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1229 assert(MI->getNumOperands() == 3);
1230 if (MI->getOperand(0).isReg()) {
1231 MachineLocation MLoc;
1232 // If the second operand is an immediate, this is a
1233 // register-indirect address.
1234 if (!MI->getOperand(1).isImm())
1235 MLoc.set(MI->getOperand(0).getReg());
1237 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1238 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1240 if (MI->getOperand(0).isImm())
1241 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1242 if (MI->getOperand(0).isFPImm())
1243 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1244 if (MI->getOperand(0).isCImm())
1245 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1247 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1250 // Find variables for each lexical scope.
1252 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1254 // Grab the variable info that was squirreled away in the MMI side-table.
1255 collectVariableInfoFromMMITable(Processed);
1257 for (const MDNode *Var : UserVariables) {
1258 if (Processed.count(Var))
1261 // History contains relevant DBG_VALUE instructions for Var and instructions
1263 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1264 if (History.empty())
1266 const MachineInstr *MInsn = History.front();
1269 LexicalScope *Scope = NULL;
1270 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1271 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1272 Scope = LScopes.getCurrentFunctionScope();
1273 else if (MDNode *IA = DV.getInlinedAt())
1274 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1276 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1277 // If variable scope is not found then skip this variable.
1281 Processed.insert(DV);
1282 assert(MInsn->isDebugValue() && "History must begin with debug value");
1283 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1284 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1285 if (!addCurrentFnArgument(RegVar, Scope))
1286 addScopeVariable(Scope, RegVar);
1288 AbsVar->setMInsn(MInsn);
1290 // Simplify ranges that are fully coalesced.
1291 if (History.size() <= 1 ||
1292 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1293 RegVar->setMInsn(MInsn);
1297 // Handle multiple DBG_VALUE instructions describing one variable.
1298 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1300 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1301 HI = History.begin(),
1304 const MachineInstr *Begin = *HI;
1305 assert(Begin->isDebugValue() && "Invalid History entry");
1307 // Check if DBG_VALUE is truncating a range.
1308 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1309 !Begin->getOperand(0).getReg())
1312 // Compute the range for a register location.
1313 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1314 const MCSymbol *SLabel = 0;
1317 // If Begin is the last instruction in History then its value is valid
1318 // until the end of the function.
1319 SLabel = FunctionEndSym;
1321 const MachineInstr *End = HI[1];
1322 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1323 << "\t" << *Begin << "\t" << *End << "\n");
1324 if (End->isDebugValue())
1325 SLabel = getLabelBeforeInsn(End);
1327 // End is a normal instruction clobbering the range.
1328 SLabel = getLabelAfterInsn(End);
1329 assert(SLabel && "Forgot label after clobber instruction");
1334 // The value is valid until the next DBG_VALUE or clobber.
1335 DotDebugLocEntries.push_back(
1336 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1338 DotDebugLocEntries.push_back(DotDebugLocEntry());
1341 // Collect info for variables that were optimized out.
1342 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1343 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1344 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1345 DIVariable DV(Variables.getElement(i));
1346 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1348 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1349 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1353 // Return Label preceding the instruction.
1354 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1355 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1356 assert(Label && "Didn't insert label before instruction");
1360 // Return Label immediately following the instruction.
1361 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1362 return LabelsAfterInsn.lookup(MI);
1365 // Process beginning of an instruction.
1366 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1369 // Check if source location changes, but ignore DBG_VALUE locations.
1370 if (!MI->isDebugValue()) {
1371 DebugLoc DL = MI->getDebugLoc();
1372 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1375 if (DL == PrologEndLoc) {
1376 Flags |= DWARF2_FLAG_PROLOGUE_END;
1377 PrologEndLoc = DebugLoc();
1379 if (PrologEndLoc.isUnknown())
1380 Flags |= DWARF2_FLAG_IS_STMT;
1382 if (!DL.isUnknown()) {
1383 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1384 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1386 recordSourceLine(0, 0, 0, 0);
1390 // Insert labels where requested.
1391 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1392 LabelsBeforeInsn.find(MI);
1395 if (I == LabelsBeforeInsn.end())
1398 // Label already assigned.
1403 PrevLabel = MMI->getContext().CreateTempSymbol();
1404 Asm->OutStreamer.EmitLabel(PrevLabel);
1406 I->second = PrevLabel;
1409 // Process end of an instruction.
1410 void DwarfDebug::endInstruction() {
1412 // Don't create a new label after DBG_VALUE instructions.
1413 // They don't generate code.
1414 if (!CurMI->isDebugValue())
1417 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1418 LabelsAfterInsn.find(CurMI);
1422 if (I == LabelsAfterInsn.end())
1425 // Label already assigned.
1429 // We need a label after this instruction.
1431 PrevLabel = MMI->getContext().CreateTempSymbol();
1432 Asm->OutStreamer.EmitLabel(PrevLabel);
1434 I->second = PrevLabel;
1437 // Each LexicalScope has first instruction and last instruction to mark
1438 // beginning and end of a scope respectively. Create an inverse map that list
1439 // scopes starts (and ends) with an instruction. One instruction may start (or
1440 // end) multiple scopes. Ignore scopes that are not reachable.
1441 void DwarfDebug::identifyScopeMarkers() {
1442 SmallVector<LexicalScope *, 4> WorkList;
1443 WorkList.push_back(LScopes.getCurrentFunctionScope());
1444 while (!WorkList.empty()) {
1445 LexicalScope *S = WorkList.pop_back_val();
1447 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1448 if (!Children.empty())
1449 WorkList.append(Children.begin(), Children.end());
1451 if (S->isAbstractScope())
1454 for (const InsnRange &R : S->getRanges()) {
1455 assert(R.first && "InsnRange does not have first instruction!");
1456 assert(R.second && "InsnRange does not have second instruction!");
1457 requestLabelBeforeInsn(R.first);
1458 requestLabelAfterInsn(R.second);
1463 // Gather pre-function debug information. Assumes being called immediately
1464 // after the function entry point has been emitted.
1465 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1468 // If there's no debug info for the function we're not going to do anything.
1469 if (!MMI->hasDebugInfo())
1472 // Grab the lexical scopes for the function, if we don't have any of those
1473 // then we're not going to be able to do anything.
1474 LScopes.initialize(*MF);
1475 if (LScopes.empty())
1478 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1480 // Make sure that each lexical scope will have a begin/end label.
1481 identifyScopeMarkers();
1483 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1484 // belongs to so that we add to the correct per-cu line table in the
1486 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1487 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1488 assert(TheCU && "Unable to find compile unit!");
1489 if (Asm->OutStreamer.hasRawTextSupport())
1490 // Use a single line table if we are generating assembly.
1491 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1493 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1495 // Check the current section against the standard text section. If different
1496 // keep track so that we will know when we're emitting functions into multiple
1498 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1499 UsedNonDefaultText = true;
1501 // Emit a label for the function so that we have a beginning address.
1502 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1503 // Assumes in correct section after the entry point.
1504 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1506 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1507 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1508 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1510 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1512 bool AtBlockEntry = true;
1513 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1515 const MachineInstr *MI = II;
1517 if (MI->isDebugValue()) {
1518 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1520 // Keep track of user variables.
1522 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1524 // Variable is in a register, we need to check for clobbers.
1525 if (isDbgValueInDefinedReg(MI))
1526 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1528 // Check the history of this variable.
1529 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1530 if (History.empty()) {
1531 UserVariables.push_back(Var);
1532 // The first mention of a function argument gets the FunctionBeginSym
1533 // label, so arguments are visible when breaking at function entry.
1535 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1536 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1537 LabelsBeforeInsn[MI] = FunctionBeginSym;
1539 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1540 const MachineInstr *Prev = History.back();
1541 if (Prev->isDebugValue()) {
1542 // Coalesce identical entries at the end of History.
1543 if (History.size() >= 2 &&
1544 Prev->isIdenticalTo(History[History.size() - 2])) {
1545 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1546 << "\t" << *Prev << "\t"
1547 << *History[History.size() - 2] << "\n");
1551 // Terminate old register assignments that don't reach MI;
1552 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1553 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1554 isDbgValueInDefinedReg(Prev)) {
1555 // Previous register assignment needs to terminate at the end of
1557 MachineBasicBlock::const_iterator LastMI =
1558 PrevMBB->getLastNonDebugInstr();
1559 if (LastMI == PrevMBB->end()) {
1560 // Drop DBG_VALUE for empty range.
1561 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1562 << "\t" << *Prev << "\n");
1564 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1565 // Terminate after LastMI.
1566 History.push_back(LastMI);
1570 History.push_back(MI);
1572 // Not a DBG_VALUE instruction.
1573 if (!MI->isPosition())
1574 AtBlockEntry = false;
1576 // First known non-DBG_VALUE and non-frame setup location marks
1577 // the beginning of the function body.
1578 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1579 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1580 PrologEndLoc = MI->getDebugLoc();
1582 // Check if the instruction clobbers any registers with debug vars.
1583 for (const MachineOperand &MO : MI->operands()) {
1584 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1586 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1589 const MDNode *Var = LiveUserVar[Reg];
1592 // Reg is now clobbered.
1593 LiveUserVar[Reg] = 0;
1595 // Was MD last defined by a DBG_VALUE referring to Reg?
1596 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1597 if (HistI == DbgValues.end())
1599 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1600 if (History.empty())
1602 const MachineInstr *Prev = History.back();
1603 // Sanity-check: Register assignments are terminated at the end of
1605 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1607 // Is the variable still in Reg?
1608 if (!isDbgValueInDefinedReg(Prev) ||
1609 Prev->getOperand(0).getReg() != Reg)
1611 // Var is clobbered. Make sure the next instruction gets a label.
1612 History.push_back(MI);
1619 for (auto &I : DbgValues) {
1620 SmallVectorImpl<const MachineInstr *> &History = I.second;
1621 if (History.empty())
1624 // Make sure the final register assignments are terminated.
1625 const MachineInstr *Prev = History.back();
1626 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1627 const MachineBasicBlock *PrevMBB = Prev->getParent();
1628 MachineBasicBlock::const_iterator LastMI =
1629 PrevMBB->getLastNonDebugInstr();
1630 if (LastMI == PrevMBB->end())
1631 // Drop DBG_VALUE for empty range.
1633 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1634 // Terminate after LastMI.
1635 History.push_back(LastMI);
1638 // Request labels for the full history.
1639 for (const MachineInstr *MI : History) {
1640 if (MI->isDebugValue())
1641 requestLabelBeforeInsn(MI);
1643 requestLabelAfterInsn(MI);
1647 PrevInstLoc = DebugLoc();
1648 PrevLabel = FunctionBeginSym;
1650 // Record beginning of function.
1651 if (!PrologEndLoc.isUnknown()) {
1652 DebugLoc FnStartDL =
1653 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1655 FnStartDL.getLine(), FnStartDL.getCol(),
1656 FnStartDL.getScope(MF->getFunction()->getContext()),
1657 // We'd like to list the prologue as "not statements" but GDB behaves
1658 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1659 DWARF2_FLAG_IS_STMT);
1663 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1664 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1665 DIVariable DV = Var->getVariable();
1666 // Variables with positive arg numbers are parameters.
1667 if (unsigned ArgNum = DV.getArgNumber()) {
1668 // Keep all parameters in order at the start of the variable list to ensure
1669 // function types are correct (no out-of-order parameters)
1671 // This could be improved by only doing it for optimized builds (unoptimized
1672 // builds have the right order to begin with), searching from the back (this
1673 // would catch the unoptimized case quickly), or doing a binary search
1674 // rather than linear search.
1675 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1676 while (I != Vars.end()) {
1677 unsigned CurNum = (*I)->getVariable().getArgNumber();
1678 // A local (non-parameter) variable has been found, insert immediately
1682 // A later indexed parameter has been found, insert immediately before it.
1683 if (CurNum > ArgNum)
1687 Vars.insert(I, Var);
1691 Vars.push_back(Var);
1694 // Gather and emit post-function debug information.
1695 void DwarfDebug::endFunction(const MachineFunction *MF) {
1696 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1697 // though the beginFunction may not be called at all.
1698 // We should handle both cases.
1702 assert(CurFn == MF);
1705 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1710 // Define end label for subprogram.
1711 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1712 // Assumes in correct section after the entry point.
1713 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1715 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1716 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1718 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1719 collectVariableInfo(ProcessedVars);
1721 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1722 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1723 assert(TheCU && "Unable to find compile unit!");
1725 // Construct abstract scopes.
1726 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1727 DISubprogram SP(AScope->getScopeNode());
1728 if (SP.isSubprogram()) {
1729 // Collect info for variables that were optimized out.
1730 DIArray Variables = SP.getVariables();
1731 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1732 DIVariable DV(Variables.getElement(i));
1733 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1735 // Check that DbgVariable for DV wasn't created earlier, when
1736 // findAbstractVariable() was called for inlined instance of DV.
1737 LLVMContext &Ctx = DV->getContext();
1738 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1739 if (AbstractVariables.lookup(CleanDV))
1741 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1742 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1745 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1746 constructScopeDIE(TheCU, AScope);
1749 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1750 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1751 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1753 // Add the range of this function to the list of ranges for the CU.
1754 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1755 TheCU->addRange(std::move(Span));
1758 for (auto &I : ScopeVariables)
1759 DeleteContainerPointers(I.second);
1760 ScopeVariables.clear();
1761 DeleteContainerPointers(CurrentFnArguments);
1762 UserVariables.clear();
1764 AbstractVariables.clear();
1765 LabelsBeforeInsn.clear();
1766 LabelsAfterInsn.clear();
1771 // Register a source line with debug info. Returns the unique label that was
1772 // emitted and which provides correspondence to the source line list.
1773 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1778 unsigned Discriminator = 0;
1780 DIDescriptor Scope(S);
1782 if (Scope.isCompileUnit()) {
1783 DICompileUnit CU(S);
1784 Fn = CU.getFilename();
1785 Dir = CU.getDirectory();
1786 } else if (Scope.isFile()) {
1788 Fn = F.getFilename();
1789 Dir = F.getDirectory();
1790 } else if (Scope.isSubprogram()) {
1792 Fn = SP.getFilename();
1793 Dir = SP.getDirectory();
1794 } else if (Scope.isLexicalBlockFile()) {
1795 DILexicalBlockFile DBF(S);
1796 Fn = DBF.getFilename();
1797 Dir = DBF.getDirectory();
1798 } else if (Scope.isLexicalBlock()) {
1799 DILexicalBlock DB(S);
1800 Fn = DB.getFilename();
1801 Dir = DB.getDirectory();
1802 Discriminator = DB.getDiscriminator();
1804 llvm_unreachable("Unexpected scope info");
1806 Src = getOrCreateSourceID(
1807 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1809 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1813 //===----------------------------------------------------------------------===//
1815 //===----------------------------------------------------------------------===//
1817 // Compute the size and offset of a DIE. The offset is relative to start of the
1818 // CU. It returns the offset after laying out the DIE.
1819 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1820 // Record the abbreviation.
1821 assignAbbrevNumber(Die->getAbbrev());
1823 // Get the abbreviation for this DIE.
1824 const DIEAbbrev &Abbrev = Die->getAbbrev();
1827 Die->setOffset(Offset);
1829 // Start the size with the size of abbreviation code.
1830 Offset += getULEB128Size(Die->getAbbrevNumber());
1832 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1833 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1835 // Size the DIE attribute values.
1836 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1837 // Size attribute value.
1838 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1840 // Get the children.
1841 const std::vector<DIE *> &Children = Die->getChildren();
1843 // Size the DIE children if any.
1844 if (!Children.empty()) {
1845 assert(Abbrev.hasChildren() && "Children flag not set");
1847 for (DIE *Child : Children)
1848 Offset = computeSizeAndOffset(Child, Offset);
1850 // End of children marker.
1851 Offset += sizeof(int8_t);
1854 Die->setSize(Offset - Die->getOffset());
1858 // Compute the size and offset for each DIE.
1859 void DwarfFile::computeSizeAndOffsets() {
1860 // Offset from the first CU in the debug info section is 0 initially.
1861 unsigned SecOffset = 0;
1863 // Iterate over each compile unit and set the size and offsets for each
1864 // DIE within each compile unit. All offsets are CU relative.
1865 for (DwarfUnit *TheU : CUs) {
1866 TheU->setDebugInfoOffset(SecOffset);
1868 // CU-relative offset is reset to 0 here.
1869 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1870 TheU->getHeaderSize(); // Unit-specific headers
1872 // EndOffset here is CU-relative, after laying out
1873 // all of the CU DIE.
1874 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1875 SecOffset += EndOffset;
1879 // Emit initial Dwarf sections with a label at the start of each one.
1880 void DwarfDebug::emitSectionLabels() {
1881 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1883 // Dwarf sections base addresses.
1884 DwarfInfoSectionSym =
1885 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1886 if (useSplitDwarf())
1887 DwarfInfoDWOSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1889 DwarfAbbrevSectionSym =
1890 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1891 if (useSplitDwarf())
1892 DwarfAbbrevDWOSectionSym = emitSectionSym(
1893 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1894 if (GenerateARangeSection)
1895 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1897 DwarfLineSectionSym =
1898 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1899 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1900 if (GenerateGnuPubSections) {
1901 DwarfGnuPubNamesSectionSym =
1902 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1903 DwarfGnuPubTypesSectionSym =
1904 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1905 } else if (HasDwarfPubSections) {
1906 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1907 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1910 DwarfStrSectionSym =
1911 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1912 if (useSplitDwarf()) {
1913 DwarfStrDWOSectionSym =
1914 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1915 DwarfAddrSectionSym =
1916 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1918 DwarfDebugRangeSectionSym =
1919 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1921 DwarfDebugLocSectionSym =
1922 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1925 // Recursively emits a debug information entry.
1926 void DwarfDebug::emitDIE(DIE *Die) {
1927 // Get the abbreviation for this DIE.
1928 const DIEAbbrev &Abbrev = Die->getAbbrev();
1930 // Emit the code (index) for the abbreviation.
1931 if (Asm->isVerbose())
1932 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1933 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1934 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1935 dwarf::TagString(Abbrev.getTag()));
1936 Asm->EmitULEB128(Abbrev.getNumber());
1938 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1939 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1941 // Emit the DIE attribute values.
1942 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1943 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1944 dwarf::Form Form = AbbrevData[i].getForm();
1945 assert(Form && "Too many attributes for DIE (check abbreviation)");
1947 if (Asm->isVerbose()) {
1948 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1949 if (Attr == dwarf::DW_AT_accessibility)
1950 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1951 cast<DIEInteger>(Values[i])->getValue()));
1954 // Emit an attribute using the defined form.
1955 Values[i]->EmitValue(Asm, Form);
1958 // Emit the DIE children if any.
1959 if (Abbrev.hasChildren()) {
1960 const std::vector<DIE *> &Children = Die->getChildren();
1962 for (DIE *Child : Children)
1965 Asm->OutStreamer.AddComment("End Of Children Mark");
1970 // Emit the various dwarf units to the unit section USection with
1971 // the abbreviations going into ASection.
1972 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1973 const MCSymbol *ASectionSym) {
1974 for (DwarfUnit *TheU : CUs) {
1975 DIE *Die = TheU->getUnitDie();
1976 const MCSection *USection = TheU->getSection();
1977 Asm->OutStreamer.SwitchSection(USection);
1979 // Emit the compile units header.
1980 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1982 // Emit size of content not including length itself
1983 Asm->OutStreamer.AddComment("Length of Unit");
1984 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1986 TheU->emitHeader(ASection, ASectionSym);
1989 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1993 // Emit the debug info section.
1994 void DwarfDebug::emitDebugInfo() {
1995 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1997 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1998 DwarfAbbrevSectionSym);
2001 // Emit the abbreviation section.
2002 void DwarfDebug::emitAbbreviations() {
2003 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2005 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2008 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2009 // Check to see if it is worth the effort.
2010 if (!Abbreviations.empty()) {
2011 // Start the debug abbrev section.
2012 Asm->OutStreamer.SwitchSection(Section);
2014 // For each abbrevation.
2015 for (const DIEAbbrev *Abbrev : Abbreviations) {
2016 // Emit the abbrevations code (base 1 index.)
2017 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2019 // Emit the abbreviations data.
2023 // Mark end of abbreviations.
2024 Asm->EmitULEB128(0, "EOM(3)");
2028 // Emit the last address of the section and the end of the line matrix.
2029 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2030 // Define last address of section.
2031 Asm->OutStreamer.AddComment("Extended Op");
2034 Asm->OutStreamer.AddComment("Op size");
2035 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2036 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2037 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2039 Asm->OutStreamer.AddComment("Section end label");
2041 Asm->OutStreamer.EmitSymbolValue(
2042 Asm->GetTempSymbol("section_end", SectionEnd),
2043 Asm->getDataLayout().getPointerSize());
2045 // Mark end of matrix.
2046 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2052 // Emit visible names into a hashed accelerator table section.
2053 void DwarfDebug::emitAccelNames() {
2055 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2056 for (DwarfUnit *TheU : getUnits()) {
2057 for (const auto &GI : TheU->getAccelNames()) {
2058 StringRef Name = GI.getKey();
2059 for (const DIE *D : GI.second)
2060 AT.AddName(Name, D);
2064 AT.FinalizeTable(Asm, "Names");
2065 Asm->OutStreamer.SwitchSection(
2066 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2067 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2068 Asm->OutStreamer.EmitLabel(SectionBegin);
2070 // Emit the full data.
2071 AT.Emit(Asm, SectionBegin, &InfoHolder);
2074 // Emit objective C classes and categories into a hashed accelerator table
2076 void DwarfDebug::emitAccelObjC() {
2078 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2079 for (DwarfUnit *TheU : getUnits()) {
2080 for (const auto &GI : TheU->getAccelObjC()) {
2081 StringRef Name = GI.getKey();
2082 for (const DIE *D : GI.second)
2083 AT.AddName(Name, D);
2087 AT.FinalizeTable(Asm, "ObjC");
2088 Asm->OutStreamer.SwitchSection(
2089 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2090 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2091 Asm->OutStreamer.EmitLabel(SectionBegin);
2093 // Emit the full data.
2094 AT.Emit(Asm, SectionBegin, &InfoHolder);
2097 // Emit namespace dies into a hashed accelerator table.
2098 void DwarfDebug::emitAccelNamespaces() {
2100 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2101 for (DwarfUnit *TheU : getUnits()) {
2102 for (const auto &GI : TheU->getAccelNamespace()) {
2103 StringRef Name = GI.getKey();
2104 for (const DIE *D : GI.second)
2105 AT.AddName(Name, D);
2109 AT.FinalizeTable(Asm, "namespac");
2110 Asm->OutStreamer.SwitchSection(
2111 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2112 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2113 Asm->OutStreamer.EmitLabel(SectionBegin);
2115 // Emit the full data.
2116 AT.Emit(Asm, SectionBegin, &InfoHolder);
2119 // Emit type dies into a hashed accelerator table.
2120 void DwarfDebug::emitAccelTypes() {
2121 std::vector<DwarfAccelTable::Atom> Atoms;
2123 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2125 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2127 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2128 DwarfAccelTable AT(Atoms);
2129 for (DwarfUnit *TheU : getUnits()) {
2130 for (const auto &GI : TheU->getAccelTypes()) {
2131 StringRef Name = GI.getKey();
2132 for (const auto &DI : GI.second)
2133 AT.AddName(Name, DI.first, DI.second);
2137 AT.FinalizeTable(Asm, "types");
2138 Asm->OutStreamer.SwitchSection(
2139 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2140 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2141 Asm->OutStreamer.EmitLabel(SectionBegin);
2143 // Emit the full data.
2144 AT.Emit(Asm, SectionBegin, &InfoHolder);
2147 // Public name handling.
2148 // The format for the various pubnames:
2150 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2151 // for the DIE that is named.
2153 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2154 // into the CU and the index value is computed according to the type of value
2155 // for the DIE that is named.
2157 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2158 // it's the offset within the debug_info/debug_types dwo section, however, the
2159 // reference in the pubname header doesn't change.
2161 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2162 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2164 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2166 // We could have a specification DIE that has our most of our knowledge,
2167 // look for that now.
2168 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2170 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2171 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2172 Linkage = dwarf::GIEL_EXTERNAL;
2173 } else if (Die->findAttribute(dwarf::DW_AT_external))
2174 Linkage = dwarf::GIEL_EXTERNAL;
2176 switch (Die->getTag()) {
2177 case dwarf::DW_TAG_class_type:
2178 case dwarf::DW_TAG_structure_type:
2179 case dwarf::DW_TAG_union_type:
2180 case dwarf::DW_TAG_enumeration_type:
2181 return dwarf::PubIndexEntryDescriptor(
2182 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2183 ? dwarf::GIEL_STATIC
2184 : dwarf::GIEL_EXTERNAL);
2185 case dwarf::DW_TAG_typedef:
2186 case dwarf::DW_TAG_base_type:
2187 case dwarf::DW_TAG_subrange_type:
2188 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2189 case dwarf::DW_TAG_namespace:
2190 return dwarf::GIEK_TYPE;
2191 case dwarf::DW_TAG_subprogram:
2192 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2193 case dwarf::DW_TAG_constant:
2194 case dwarf::DW_TAG_variable:
2195 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2196 case dwarf::DW_TAG_enumerator:
2197 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2198 dwarf::GIEL_STATIC);
2200 return dwarf::GIEK_NONE;
2204 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2206 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2207 const MCSection *PSec =
2208 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2209 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2211 for (const auto &NU : CUMap) {
2212 DwarfCompileUnit *TheU = NU.second;
2213 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2215 unsigned ID = TheU->getUniqueID();
2217 // Start the dwarf pubnames section.
2218 Asm->OutStreamer.SwitchSection(PSec);
2220 // Emit a label so we can reference the beginning of this pubname section.
2222 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2225 Asm->OutStreamer.AddComment("Length of Public Names Info");
2226 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2227 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2228 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2230 Asm->OutStreamer.EmitLabel(BeginLabel);
2232 Asm->OutStreamer.AddComment("DWARF Version");
2233 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2235 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2236 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2238 Asm->OutStreamer.AddComment("Compilation Unit Length");
2239 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2241 // Emit the pubnames for this compilation unit.
2242 for (const auto &GI : getUnits()[ID]->getGlobalNames()) {
2243 const char *Name = GI.getKeyData();
2244 const DIE *Entity = GI.second;
2246 Asm->OutStreamer.AddComment("DIE offset");
2247 Asm->EmitInt32(Entity->getOffset());
2250 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2251 Asm->OutStreamer.AddComment(
2252 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2253 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2254 Asm->EmitInt8(Desc.toBits());
2257 Asm->OutStreamer.AddComment("External Name");
2258 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2261 Asm->OutStreamer.AddComment("End Mark");
2263 Asm->OutStreamer.EmitLabel(EndLabel);
2267 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2268 const MCSection *PSec =
2269 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2270 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2272 for (const auto &NU : CUMap) {
2273 DwarfCompileUnit *TheU = NU.second;
2274 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2276 unsigned ID = TheU->getUniqueID();
2278 // Start the dwarf pubtypes section.
2279 Asm->OutStreamer.SwitchSection(PSec);
2281 // Emit a label so we can reference the beginning of this pubtype section.
2283 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2286 Asm->OutStreamer.AddComment("Length of Public Types Info");
2287 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2288 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2289 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2291 Asm->OutStreamer.EmitLabel(BeginLabel);
2293 Asm->OutStreamer.AddComment("DWARF Version");
2294 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2296 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2297 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2299 Asm->OutStreamer.AddComment("Compilation Unit Length");
2300 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2302 // Emit the pubtypes.
2303 for (const auto &GI : getUnits()[ID]->getGlobalTypes()) {
2304 const char *Name = GI.getKeyData();
2305 const DIE *Entity = GI.second;
2307 Asm->OutStreamer.AddComment("DIE offset");
2308 Asm->EmitInt32(Entity->getOffset());
2311 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2312 Asm->OutStreamer.AddComment(
2313 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2314 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2315 Asm->EmitInt8(Desc.toBits());
2318 Asm->OutStreamer.AddComment("External Name");
2320 // Emit the name with a terminating null byte.
2321 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2324 Asm->OutStreamer.AddComment("End Mark");
2326 Asm->OutStreamer.EmitLabel(EndLabel);
2330 // Emit strings into a string section.
2331 void DwarfFile::emitStrings(const MCSection *StrSection,
2332 const MCSection *OffsetSection = NULL,
2333 const MCSymbol *StrSecSym = NULL) {
2335 if (StringPool.empty())
2338 // Start the dwarf str section.
2339 Asm->OutStreamer.SwitchSection(StrSection);
2341 // Get all of the string pool entries and put them in an array by their ID so
2342 // we can sort them.
2343 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2345 for (const auto &I : StringPool)
2346 Entries.push_back(std::make_pair(I.second.second, &I));
2348 array_pod_sort(Entries.begin(), Entries.end());
2350 for (const auto &Entry : Entries) {
2351 // Emit a label for reference from debug information entries.
2352 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2354 // Emit the string itself with a terminating null byte.
2355 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2356 Entry.second->getKeyLength() + 1));
2359 // If we've got an offset section go ahead and emit that now as well.
2360 if (OffsetSection) {
2361 Asm->OutStreamer.SwitchSection(OffsetSection);
2362 unsigned offset = 0;
2363 unsigned size = 4; // FIXME: DWARF64 is 8.
2364 for (const auto &Entry : Entries) {
2365 Asm->OutStreamer.EmitIntValue(offset, size);
2366 offset += Entry.second->getKeyLength() + 1;
2371 // Emit addresses into the section given.
2372 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2374 if (AddressPool.empty())
2377 // Start the dwarf addr section.
2378 Asm->OutStreamer.SwitchSection(AddrSection);
2380 // Order the address pool entries by ID
2381 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2383 for (const auto &I : AddressPool)
2384 Entries[I.second.Number] =
2386 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2387 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2389 for (const MCExpr *Entry : Entries)
2390 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2393 // Emit visible names into a debug str section.
2394 void DwarfDebug::emitDebugStr() {
2395 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2396 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2399 // Emit locations into the debug loc section.
2400 void DwarfDebug::emitDebugLoc() {
2401 if (DotDebugLocEntries.empty())
2404 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2405 I = DotDebugLocEntries.begin(),
2406 E = DotDebugLocEntries.end();
2408 DotDebugLocEntry &Entry = *I;
2409 if (I + 1 != DotDebugLocEntries.end())
2413 // Start the dwarf loc section.
2414 Asm->OutStreamer.SwitchSection(
2415 Asm->getObjFileLowering().getDwarfLocSection());
2416 unsigned char Size = Asm->getDataLayout().getPointerSize();
2417 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2419 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2420 I = DotDebugLocEntries.begin(),
2421 E = DotDebugLocEntries.end();
2422 I != E; ++I, ++index) {
2423 const DotDebugLocEntry &Entry = *I;
2424 if (Entry.isMerged())
2426 if (Entry.isEmpty()) {
2427 Asm->OutStreamer.EmitIntValue(0, Size);
2428 Asm->OutStreamer.EmitIntValue(0, Size);
2429 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2431 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2432 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2433 DIVariable DV(Entry.getVariable());
2434 Asm->OutStreamer.AddComment("Loc expr size");
2435 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2436 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2437 Asm->EmitLabelDifference(end, begin, 2);
2438 Asm->OutStreamer.EmitLabel(begin);
2439 if (Entry.isInt()) {
2440 DIBasicType BTy(DV.getType());
2441 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2442 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2443 Asm->OutStreamer.AddComment("DW_OP_consts");
2444 Asm->EmitInt8(dwarf::DW_OP_consts);
2445 Asm->EmitSLEB128(Entry.getInt());
2447 Asm->OutStreamer.AddComment("DW_OP_constu");
2448 Asm->EmitInt8(dwarf::DW_OP_constu);
2449 Asm->EmitULEB128(Entry.getInt());
2451 } else if (Entry.isLocation()) {
2452 MachineLocation Loc = Entry.getLoc();
2453 if (!DV.hasComplexAddress())
2455 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2457 // Complex address entry.
2458 unsigned N = DV.getNumAddrElements();
2460 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2461 if (Loc.getOffset()) {
2463 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2464 Asm->OutStreamer.AddComment("DW_OP_deref");
2465 Asm->EmitInt8(dwarf::DW_OP_deref);
2466 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2467 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2468 Asm->EmitSLEB128(DV.getAddrElement(1));
2470 // If first address element is OpPlus then emit
2471 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2472 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2473 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2477 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2480 // Emit remaining complex address elements.
2481 for (; i < N; ++i) {
2482 uint64_t Element = DV.getAddrElement(i);
2483 if (Element == DIBuilder::OpPlus) {
2484 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2485 Asm->EmitULEB128(DV.getAddrElement(++i));
2486 } else if (Element == DIBuilder::OpDeref) {
2488 Asm->EmitInt8(dwarf::DW_OP_deref);
2490 llvm_unreachable("unknown Opcode found in complex address");
2494 // else ... ignore constant fp. There is not any good way to
2495 // to represent them here in dwarf.
2496 Asm->OutStreamer.EmitLabel(end);
2502 const MCSymbol *Start, *End;
2505 // Emit a debug aranges section, containing a CU lookup for any
2506 // address we can tie back to a CU.
2507 void DwarfDebug::emitDebugARanges() {
2508 // Start the dwarf aranges section.
2509 Asm->OutStreamer.SwitchSection(
2510 Asm->getObjFileLowering().getDwarfARangesSection());
2512 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2516 // Build a list of sections used.
2517 std::vector<const MCSection *> Sections;
2518 for (const auto &it : SectionMap) {
2519 const MCSection *Section = it.first;
2520 Sections.push_back(Section);
2523 // Sort the sections into order.
2524 // This is only done to ensure consistent output order across different runs.
2525 std::sort(Sections.begin(), Sections.end(), SectionSort);
2527 // Build a set of address spans, sorted by CU.
2528 for (const MCSection *Section : Sections) {
2529 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2530 if (List.size() < 2)
2533 // Sort the symbols by offset within the section.
2534 std::sort(List.begin(), List.end(),
2535 [&](const SymbolCU &A, const SymbolCU &B) {
2536 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2537 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2539 // Symbols with no order assigned should be placed at the end.
2540 // (e.g. section end labels)
2548 // If we have no section (e.g. common), just write out
2549 // individual spans for each symbol.
2550 if (Section == NULL) {
2551 for (const SymbolCU &Cur : List) {
2553 Span.Start = Cur.Sym;
2556 Spans[Cur.CU].push_back(Span);
2559 // Build spans between each label.
2560 const MCSymbol *StartSym = List[0].Sym;
2561 for (size_t n = 1, e = List.size(); n < e; n++) {
2562 const SymbolCU &Prev = List[n - 1];
2563 const SymbolCU &Cur = List[n];
2565 // Try and build the longest span we can within the same CU.
2566 if (Cur.CU != Prev.CU) {
2568 Span.Start = StartSym;
2570 Spans[Prev.CU].push_back(Span);
2577 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2579 // Build a list of CUs used.
2580 std::vector<DwarfCompileUnit *> CUs;
2581 for (const auto &it : Spans) {
2582 DwarfCompileUnit *CU = it.first;
2586 // Sort the CU list (again, to ensure consistent output order).
2587 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2588 return A->getUniqueID() < B->getUniqueID();
2591 // Emit an arange table for each CU we used.
2592 for (DwarfCompileUnit *CU : CUs) {
2593 std::vector<ArangeSpan> &List = Spans[CU];
2595 // Emit size of content not including length itself.
2596 unsigned ContentSize =
2597 sizeof(int16_t) + // DWARF ARange version number
2598 sizeof(int32_t) + // Offset of CU in the .debug_info section
2599 sizeof(int8_t) + // Pointer Size (in bytes)
2600 sizeof(int8_t); // Segment Size (in bytes)
2602 unsigned TupleSize = PtrSize * 2;
2604 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2606 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2608 ContentSize += Padding;
2609 ContentSize += (List.size() + 1) * TupleSize;
2611 // For each compile unit, write the list of spans it covers.
2612 Asm->OutStreamer.AddComment("Length of ARange Set");
2613 Asm->EmitInt32(ContentSize);
2614 Asm->OutStreamer.AddComment("DWARF Arange version number");
2615 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2616 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2617 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2618 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2619 Asm->EmitInt8(PtrSize);
2620 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2623 Asm->OutStreamer.EmitFill(Padding, 0xff);
2625 for (const ArangeSpan &Span : List) {
2626 Asm->EmitLabelReference(Span.Start, PtrSize);
2628 // Calculate the size as being from the span start to it's end.
2630 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2632 // For symbols without an end marker (e.g. common), we
2633 // write a single arange entry containing just that one symbol.
2634 uint64_t Size = SymSize[Span.Start];
2638 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2642 Asm->OutStreamer.AddComment("ARange terminator");
2643 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2644 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2648 // Emit visible names into a debug ranges section.
2649 void DwarfDebug::emitDebugRanges() {
2650 // Start the dwarf ranges section.
2651 Asm->OutStreamer.SwitchSection(
2652 Asm->getObjFileLowering().getDwarfRangesSection());
2654 // Size for our labels.
2655 unsigned char Size = Asm->getDataLayout().getPointerSize();
2657 // Grab the specific ranges for the compile units in the module.
2658 for (const auto &I : CUMap) {
2659 DwarfCompileUnit *TheCU = I.second;
2661 // Emit a symbol so we can find the beginning of our ranges.
2662 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2664 // Iterate over the misc ranges for the compile units in the module.
2665 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2666 // Emit our symbol so we can find the beginning of the range.
2667 Asm->OutStreamer.EmitLabel(List.getSym());
2669 for (const RangeSpan &Range : List.getRanges()) {
2670 const MCSymbol *Begin = Range.getStart();
2671 const MCSymbol *End = Range.getEnd();
2672 assert(Begin && "Range without a begin symbol?");
2673 assert(End && "Range without an end symbol?");
2674 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2675 Asm->OutStreamer.EmitSymbolValue(End, Size);
2678 // And terminate the list with two 0 values.
2679 Asm->OutStreamer.EmitIntValue(0, Size);
2680 Asm->OutStreamer.EmitIntValue(0, Size);
2683 // Now emit a range for the CU itself.
2684 if (useCURanges() && TheCU->getRanges().size()) {
2685 Asm->OutStreamer.EmitLabel(
2686 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2687 for (const RangeSpan &Range : TheCU->getRanges()) {
2688 const MCSymbol *Begin = Range.getStart();
2689 const MCSymbol *End = Range.getEnd();
2690 assert(Begin && "Range without a begin symbol?");
2691 assert(End && "Range without an end symbol?");
2692 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2693 Asm->OutStreamer.EmitSymbolValue(End, Size);
2695 // And terminate the list with two 0 values.
2696 Asm->OutStreamer.EmitIntValue(0, Size);
2697 Asm->OutStreamer.EmitIntValue(0, Size);
2702 // DWARF5 Experimental Separate Dwarf emitters.
2704 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2706 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2707 U->getCUNode().getSplitDebugFilename());
2709 // Relocate to the beginning of the addr_base section, else 0 for the
2710 // beginning of the one for this compile unit.
2711 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2712 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2714 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2716 if (!CompilationDir.empty())
2717 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2719 addGnuPubAttributes(NewU, Die);
2721 SkeletonHolder.addUnit(NewU);
2724 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2725 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2726 // DW_AT_ranges_base, DW_AT_addr_base.
2727 // TODO: Implement DW_AT_ranges_base.
2728 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2730 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2731 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2732 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2733 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2734 DwarfInfoSectionSym);
2736 NewCU->initStmtList(DwarfLineSectionSym);
2738 initSkeletonUnit(CU, Die, NewCU);
2743 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2745 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2746 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2747 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2749 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2750 DwarfTypeUnit *NewTU =
2751 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2752 NewTU->setTypeSignature(TU->getTypeSignature());
2753 NewTU->setType(NULL);
2755 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2756 CU.applyStmtList(*Die);
2758 initSkeletonUnit(TU, Die, NewTU);
2762 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2763 // compile units that would normally be in debug_info.
2764 void DwarfDebug::emitDebugInfoDWO() {
2765 assert(useSplitDwarf() && "No split dwarf debug info?");
2766 InfoHolder.emitUnits(this,
2767 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2768 DwarfAbbrevDWOSectionSym);
2771 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2772 // abbreviations for the .debug_info.dwo section.
2773 void DwarfDebug::emitDebugAbbrevDWO() {
2774 assert(useSplitDwarf() && "No split dwarf?");
2775 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2778 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2779 // string section and is identical in format to traditional .debug_str
2781 void DwarfDebug::emitDebugStrDWO() {
2782 assert(useSplitDwarf() && "No split dwarf?");
2783 const MCSection *OffSec =
2784 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2785 const MCSymbol *StrSym = DwarfStrSectionSym;
2786 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2790 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2791 StringRef Identifier, DIE *RefDie,
2792 DICompositeType CTy) {
2793 // Flag the type unit reference as a declaration so that if it contains
2794 // members (implicit special members, static data member definitions, member
2795 // declarations for definitions in this CU, etc) consumers don't get confused
2796 // and think this is a full definition.
2797 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2799 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2801 CU.addDIETypeSignature(RefDie, *TU);
2805 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2806 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2807 UnitDie, CU, Asm, this, &InfoHolder);
2809 InfoHolder.addUnit(NewTU);
2811 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2815 Hash.update(Identifier);
2816 // ... take the least significant 8 bytes and return those. Our MD5
2817 // implementation always returns its results in little endian, swap bytes
2819 MD5::MD5Result Result;
2821 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2822 NewTU->setTypeSignature(Signature);
2823 if (useSplitDwarf())
2824 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2826 CU.applyStmtList(*UnitDie);
2828 NewTU->setType(NewTU->createTypeDIE(CTy));
2832 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2833 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2835 CU.addDIETypeSignature(RefDie, *NewTU);
2838 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2839 MCSymbol *Begin, MCSymbol *End) {
2840 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2841 if (DwarfVersion < 4 || Triple(Asm->getTargetTriple()).isOSDarwin())
2842 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2844 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);