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 (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
244 MCSymbol *DwarfFile::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol *, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
264 Entry.second = NextStringPoolNumber++;
265 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
273 ++NextAddrPoolNumber;
274 return P.first->second.Number;
277 // Define a unique number for the abbreviation.
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280 // Check the set for priors.
281 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
283 // If it's newly added.
284 if (InSet == &Abbrev) {
285 // Add to abbreviation list.
286 Abbreviations.push_back(&Abbrev);
288 // Assign the vector position + 1 as its number.
289 Abbrev.setNumber(Abbreviations.size());
291 // Assign existing abbreviation number.
292 Abbrev.setNumber(InSet->getNumber());
296 static bool isObjCClass(StringRef Name) {
297 return Name.startswith("+") || Name.startswith("-");
300 static bool hasObjCCategory(StringRef Name) {
301 if (!isObjCClass(Name))
304 return Name.find(") ") != StringRef::npos;
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326 std::string LA = (A ? A->getLabelBeginName() : "");
327 std::string LB = (B ? B->getLabelBeginName() : "");
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336 if (!SP.isDefinition())
338 TheU->addAccelName(SP.getName(), Die);
340 // If the linkage name is different than the name, go ahead and output
341 // that as well into the name table.
342 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343 TheU->addAccelName(SP.getLinkageName(), Die);
345 // If this is an Objective-C selector name add it to the ObjC accelerator
347 if (isObjCClass(SP.getName())) {
348 StringRef Class, Category;
349 getObjCClassCategory(SP.getName(), Class, Category);
350 TheU->addAccelObjC(Class, Die);
352 TheU->addAccelObjC(Category, Die);
353 // Also add the base method name to the name table.
354 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
363 DIDescriptor D(Context);
364 if (D.isSubprogram())
367 return isSubprogramContext(resolve(DIType(Context).getContext()));
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
376 DIE *SPDie = SPCU->getDIE(SP);
378 assert(SPDie && "Unable to find subprogram DIE!");
380 // If we're updating an abstract DIE, then we will be adding the children and
381 // object pointer later on. But what we don't want to do is process the
382 // concrete DIE twice.
383 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384 // Pick up abstract subprogram DIE.
386 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 SPCU->constructSubprogramArguments(*SPDie, Args);
407 DIE *SPDeclDie = SPDie;
408 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
409 *SPCU->getUnitDie());
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
415 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
416 if (Triple(Asm->getTargetTriple()).isOSDarwin())
417 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
419 SPCU->addLabelDelta(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym,
422 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
423 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
424 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
426 // Add name to the name table, we do this here because we're guaranteed
427 // to have concrete versions of our DW_TAG_subprogram nodes.
428 addSubprogramNames(SPCU, SP, SPDie);
433 /// Check whether we should create a DIE for the given Scope, return true
434 /// if we don't create a DIE (the corresponding DIE is null).
435 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
436 if (Scope->isAbstractScope())
439 // We don't create a DIE if there is no Range.
440 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
444 if (Ranges.size() > 1)
447 // We don't create a DIE if we have a single Range and the end label
449 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
450 MCSymbol *End = getLabelAfterInsn(RI->second);
454 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
455 dwarf::Attribute A, const MCSymbol *L,
456 const MCSymbol *Sec) {
457 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
458 U->addSectionLabel(D, A, L);
460 U->addSectionDelta(D, A, L, Sec);
463 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
464 const SmallVectorImpl<InsnRange> &Range) {
465 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
466 // emitting it appropriately.
467 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
468 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
469 DwarfDebugRangeSectionSym);
471 RangeSpanList List(RangeSym);
472 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
475 RangeSpan Span(getLabelBeforeInsn(RI->first),
476 getLabelAfterInsn(RI->second));
477 List.addRange(std::move(Span));
480 // Add the range list to the set of ranges to be emitted.
481 TheCU->addRangeList(std::move(List));
484 // Construct new DW_TAG_lexical_block for this scope and attach
485 // DW_AT_low_pc/DW_AT_high_pc labels.
486 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
487 LexicalScope *Scope) {
488 if (isLexicalScopeDIENull(Scope))
491 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
492 if (Scope->isAbstractScope())
495 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
497 // If we have multiple ranges, emit them into the range section.
498 if (ScopeRanges.size() > 1) {
499 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
503 // Construct the address range for this DIE.
504 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
505 MCSymbol *Start = getLabelBeforeInsn(RI->first);
506 MCSymbol *End = getLabelAfterInsn(RI->second);
507 assert(End && "End label should not be null!");
509 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
510 assert(End->isDefined() && "Invalid end label for an inlined scope!");
512 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
513 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
518 // This scope represents inlined body of a function. Construct DIE to
519 // represent this concrete inlined copy of the function.
520 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
521 LexicalScope *Scope) {
522 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
523 assert(!ScopeRanges.empty() &&
524 "LexicalScope does not have instruction markers!");
526 if (!Scope->getScopeNode())
528 DIScope DS(Scope->getScopeNode());
529 DISubprogram InlinedSP = getDISubprogram(DS);
530 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
532 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
536 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
537 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
539 // If we have multiple ranges, emit them into the range section.
540 if (ScopeRanges.size() > 1)
541 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
543 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
544 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
545 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
547 if (StartLabel == 0 || EndLabel == 0)
548 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
550 assert(StartLabel->isDefined() &&
551 "Invalid starting label for an inlined scope!");
552 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
554 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
555 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
558 InlinedSubprogramDIEs.insert(OriginDIE);
560 // Add the call site information to the DIE.
561 DILocation DL(Scope->getInlinedAt());
562 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
563 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
564 TheCU->getUniqueID()));
565 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
567 // Add name to the name table, we do this here because we're guaranteed
568 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
569 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
574 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
576 SmallVectorImpl<DIE *> &Children) {
577 DIE *ObjectPointer = NULL;
579 // Collect arguments for current function.
580 if (LScopes.isCurrentFunctionScope(Scope)) {
581 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
582 if (DbgVariable *ArgDV = CurrentFnArguments[i])
584 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
585 Children.push_back(Arg);
586 if (ArgDV->isObjectPointer())
590 // If this is a variadic function, add an unspecified parameter.
591 DISubprogram SP(Scope->getScopeNode());
592 DIArray FnArgs = SP.getType().getTypeArray();
593 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
594 .isUnspecifiedParameter()) {
595 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
596 Children.push_back(Ellipsis);
600 // Collect lexical scope children first.
601 const SmallVectorImpl<DbgVariable *> &Variables =
602 ScopeVariables.lookup(Scope);
603 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
604 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
605 Scope->isAbstractScope())) {
606 Children.push_back(Variable);
607 if (Variables[i]->isObjectPointer())
608 ObjectPointer = Variable;
610 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
611 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
612 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
613 Children.push_back(Nested);
614 return ObjectPointer;
617 // Construct a DIE for this scope.
618 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
619 LexicalScope *Scope) {
620 if (!Scope || !Scope->getScopeNode())
623 DIScope DS(Scope->getScopeNode());
625 SmallVector<DIE *, 8> Children;
626 DIE *ObjectPointer = NULL;
627 bool ChildrenCreated = false;
629 // We try to create the scope DIE first, then the children DIEs. This will
630 // avoid creating un-used children then removing them later when we find out
631 // the scope DIE is null.
632 DIE *ScopeDIE = NULL;
633 if (Scope->getInlinedAt())
634 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
635 else if (DS.isSubprogram()) {
636 ProcessedSPNodes.insert(DS);
637 if (Scope->isAbstractScope()) {
638 ScopeDIE = TheCU->getDIE(DS);
639 // Note down abstract DIE.
641 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
643 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
645 // Early exit when we know the scope DIE is going to be null.
646 if (isLexicalScopeDIENull(Scope))
649 // We create children here when we know the scope DIE is not going to be
650 // null and the children will be added to the scope DIE.
651 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
652 ChildrenCreated = true;
654 // There is no need to emit empty lexical block DIE.
655 std::pair<ImportedEntityMap::const_iterator,
656 ImportedEntityMap::const_iterator> Range =
658 ScopesWithImportedEntities.begin(),
659 ScopesWithImportedEntities.end(),
660 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
662 if (Children.empty() && Range.first == Range.second)
664 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
665 assert(ScopeDIE && "Scope DIE should not be null.");
666 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
668 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
672 assert(Children.empty() &&
673 "We create children only when the scope DIE is not null.");
676 if (!ChildrenCreated)
677 // We create children when the scope DIE is not null.
678 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
681 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
684 ScopeDIE->addChild(*I);
686 if (DS.isSubprogram() && ObjectPointer != NULL)
687 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
692 // Look up the source id with the given directory and source file names.
693 // If none currently exists, create a new id and insert it in the
694 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
696 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
698 // If we print assembly, we can't separate .file entries according to
699 // compile units. Thus all files will belong to the default compile unit.
701 // FIXME: add a better feature test than hasRawTextSupport. Even better,
702 // extend .file to support this.
703 if (Asm->OutStreamer.hasRawTextSupport())
706 // If FE did not provide a file name, then assume stdin.
707 if (FileName.empty())
708 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
710 // TODO: this might not belong here. See if we can factor this better.
711 if (DirName == CompilationDir)
714 // FileIDCUMap stores the current ID for the given compile unit.
715 unsigned SrcId = FileIDCUMap[CUID] + 1;
717 // We look up the CUID/file/dir by concatenating them with a zero byte.
718 SmallString<128> NamePair;
719 NamePair += utostr(CUID);
722 NamePair += '\0'; // Zero bytes are not allowed in paths.
723 NamePair += FileName;
725 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
726 if (Ent.getValue() != SrcId)
727 return Ent.getValue();
729 FileIDCUMap[CUID] = SrcId;
730 // Print out a .file directive to specify files for .loc directives.
731 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
736 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
737 if (!GenerateGnuPubSections)
740 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
743 // Create new DwarfCompileUnit for the given metadata node with tag
744 // DW_TAG_compile_unit.
745 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
746 StringRef FN = DIUnit.getFilename();
747 CompilationDir = DIUnit.getDirectory();
749 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
750 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
751 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
752 InfoHolder.addUnit(NewCU);
754 FileIDCUMap[NewCU->getUniqueID()] = 0;
756 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
757 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
758 DIUnit.getLanguage());
759 NewCU->addString(Die, dwarf::DW_AT_name, FN);
761 if (!useSplitDwarf()) {
762 NewCU->initStmtList(DwarfLineSectionSym);
764 // If we're using split dwarf the compilation dir is going to be in the
765 // skeleton CU and so we don't need to duplicate it here.
766 if (!CompilationDir.empty())
767 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
769 addGnuPubAttributes(NewCU, Die);
772 if (DIUnit.isOptimized())
773 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
775 StringRef Flags = DIUnit.getFlags();
777 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
779 if (unsigned RVer = DIUnit.getRunTimeVersion())
780 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
781 dwarf::DW_FORM_data1, RVer);
786 if (useSplitDwarf()) {
787 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
788 DwarfInfoDWOSectionSym);
789 NewCU->setSkeleton(constructSkeletonCU(NewCU));
791 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
792 DwarfInfoSectionSym);
794 CUMap.insert(std::make_pair(DIUnit, NewCU));
795 CUDieMap.insert(std::make_pair(Die, NewCU));
799 // Construct subprogram DIE.
800 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
802 // FIXME: We should only call this routine once, however, during LTO if a
803 // program is defined in multiple CUs we could end up calling it out of
804 // beginModule as we walk the CUs.
806 DwarfCompileUnit *&CURef = SPMap[N];
812 if (!SP.isDefinition())
813 // This is a method declaration which will be handled while constructing
817 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
819 // Expose as a global name.
820 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
823 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
825 DIImportedEntity Module(N);
826 assert(Module.Verify());
827 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
828 constructImportedEntityDIE(TheCU, Module, D);
831 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
832 const MDNode *N, DIE *Context) {
833 DIImportedEntity Module(N);
834 assert(Module.Verify());
835 return constructImportedEntityDIE(TheCU, Module, Context);
838 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
839 const DIImportedEntity &Module,
841 assert(Module.Verify() &&
842 "Use one of the MDNode * overloads to handle invalid metadata");
843 assert(Context && "Should always have a context for an imported_module");
844 DIE *IMDie = new DIE(Module.getTag());
845 TheCU->insertDIE(Module, IMDie);
847 DIDescriptor Entity = Module.getEntity();
848 if (Entity.isNameSpace())
849 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
850 else if (Entity.isSubprogram())
851 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
852 else if (Entity.isType())
853 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
855 EntityDie = TheCU->getDIE(Entity);
856 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
857 Module.getContext().getDirectory(),
858 TheCU->getUniqueID());
859 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
860 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
861 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
862 StringRef Name = Module.getName();
864 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
865 Context->addChild(IMDie);
868 // Emit all Dwarf sections that should come prior to the content. Create
869 // global DIEs and emit initial debug info sections. This is invoked by
870 // the target AsmPrinter.
871 void DwarfDebug::beginModule() {
872 if (DisableDebugInfoPrinting)
875 const Module *M = MMI->getModule();
877 // If module has named metadata anchors then use them, otherwise scan the
878 // module using debug info finder to collect debug info.
879 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
882 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
884 // Emit initial sections so we can reference labels later.
887 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
888 DICompileUnit CUNode(CU_Nodes->getOperand(i));
889 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
890 DIArray ImportedEntities = CUNode.getImportedEntities();
891 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
892 ScopesWithImportedEntities.push_back(std::make_pair(
893 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
894 ImportedEntities.getElement(i)));
895 std::sort(ScopesWithImportedEntities.begin(),
896 ScopesWithImportedEntities.end(), less_first());
897 DIArray GVs = CUNode.getGlobalVariables();
898 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
899 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
900 DIArray SPs = CUNode.getSubprograms();
901 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
902 constructSubprogramDIE(CU, SPs.getElement(i));
903 DIArray EnumTypes = CUNode.getEnumTypes();
904 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
905 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
906 DIArray RetainedTypes = CUNode.getRetainedTypes();
907 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
908 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
909 // Emit imported_modules last so that the relevant context is already
911 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
912 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
915 // Tell MMI that we have debug info.
916 MMI->setDebugInfoAvailability(true);
918 // Prime section data.
919 SectionMap[Asm->getObjFileLowering().getTextSection()];
922 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
923 void DwarfDebug::computeInlinedDIEs() {
924 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
925 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
926 AE = InlinedSubprogramDIEs.end();
929 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
931 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
932 AE = AbstractSPDies.end();
934 DIE *ISP = AI->second;
935 if (InlinedSubprogramDIEs.count(ISP))
937 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
941 // Collect info for variables that were optimized out.
942 void DwarfDebug::collectDeadVariables() {
943 const Module *M = MMI->getModule();
945 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
946 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
947 DICompileUnit TheCU(CU_Nodes->getOperand(i));
948 DIArray Subprograms = TheCU.getSubprograms();
949 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
950 DISubprogram SP(Subprograms.getElement(i));
951 if (ProcessedSPNodes.count(SP) != 0)
953 if (!SP.isSubprogram())
955 if (!SP.isDefinition())
957 DIArray Variables = SP.getVariables();
958 if (Variables.getNumElements() == 0)
961 // Construct subprogram DIE and add variables DIEs.
962 DwarfCompileUnit *SPCU =
963 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
964 assert(SPCU && "Unable to find Compile Unit!");
965 // FIXME: See the comment in constructSubprogramDIE about duplicate
967 constructSubprogramDIE(SPCU, SP);
968 DIE *SPDIE = SPCU->getDIE(SP);
969 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
970 DIVariable DV(Variables.getElement(vi));
971 if (!DV.isVariable())
973 DbgVariable NewVar(DV, NULL, this);
974 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
975 SPDIE->addChild(VariableDIE);
982 void DwarfDebug::finalizeModuleInfo() {
983 // Collect info for variables that were optimized out.
984 collectDeadVariables();
986 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
987 computeInlinedDIEs();
989 // Handle anything that needs to be done on a per-unit basis after
990 // all other generation.
991 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
992 E = getUnits().end();
994 DwarfUnit *TheU = *I;
995 // Emit DW_AT_containing_type attribute to connect types with their
996 // vtable holding type.
997 TheU->constructContainingTypeDIEs();
999 // Add CU specific attributes if we need to add any.
1000 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1001 // If we're splitting the dwarf out now that we've got the entire
1002 // CU then add the dwo id to it.
1003 DwarfCompileUnit *SkCU =
1004 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1005 if (useSplitDwarf()) {
1006 // This should be a unique identifier when we want to build .dwp files.
1008 if (GenerateCUHash) {
1009 DIEHash CUHash(Asm);
1010 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1012 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1013 dwarf::DW_FORM_data8, ID);
1014 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1015 dwarf::DW_FORM_data8, ID);
1018 // If we have code split among multiple sections or we've requested
1019 // it then emit a DW_AT_ranges attribute on the unit that will remain
1020 // in the .o file, otherwise add a DW_AT_low_pc.
1021 // FIXME: Also add a high pc if we can.
1022 // FIXME: We should use ranges if we have multiple compile units or
1023 // allow reordering of code ala .subsections_via_symbols in mach-o.
1024 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1025 if (useCURanges() && TheU->getRanges().size()) {
1026 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1027 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1028 DwarfDebugRangeSectionSym);
1030 // A DW_AT_low_pc attribute may also be specified in combination with
1031 // DW_AT_ranges to specify the default base address for use in location
1032 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1033 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1036 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1041 // Compute DIE offsets and sizes.
1042 InfoHolder.computeSizeAndOffsets();
1043 if (useSplitDwarf())
1044 SkeletonHolder.computeSizeAndOffsets();
1047 void DwarfDebug::endSections() {
1048 // Filter labels by section.
1049 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1050 const SymbolCU &SCU = ArangeLabels[n];
1051 if (SCU.Sym->isInSection()) {
1052 // Make a note of this symbol and it's section.
1053 const MCSection *Section = &SCU.Sym->getSection();
1054 if (!Section->getKind().isMetadata())
1055 SectionMap[Section].push_back(SCU);
1057 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1058 // appear in the output. This sucks as we rely on sections to build
1059 // arange spans. We can do it without, but it's icky.
1060 SectionMap[NULL].push_back(SCU);
1064 // Build a list of sections used.
1065 std::vector<const MCSection *> Sections;
1066 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1068 const MCSection *Section = it->first;
1069 Sections.push_back(Section);
1072 // Sort the sections into order.
1073 // This is only done to ensure consistent output order across different runs.
1074 std::sort(Sections.begin(), Sections.end(), SectionSort);
1076 // Add terminating symbols for each section.
1077 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1078 const MCSection *Section = Sections[ID];
1079 MCSymbol *Sym = NULL;
1082 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1083 // if we know the section name up-front. For user-created sections, the
1084 // resulting label may not be valid to use as a label. (section names can
1085 // use a greater set of characters on some systems)
1086 Sym = Asm->GetTempSymbol("debug_end", ID);
1087 Asm->OutStreamer.SwitchSection(Section);
1088 Asm->OutStreamer.EmitLabel(Sym);
1091 // Insert a final terminator.
1092 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1095 // For now only turn on CU ranges if we've explicitly asked for it,
1096 // we have -ffunction-sections enabled, we've emitted a function
1097 // into a unique section, or we're using LTO. If we're using LTO then
1098 // we can't know that any particular function in the module is correlated
1099 // to a particular CU and so we need to be conservative. At this point all
1100 // sections should be finalized except for dwarf sections.
1101 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1102 TargetMachine::getFunctionSections();
1105 // Emit all Dwarf sections that should come after the content.
1106 void DwarfDebug::endModule() {
1113 // End any existing sections.
1114 // TODO: Does this need to happen?
1117 // Finalize the debug info for the module.
1118 finalizeModuleInfo();
1122 // Emit all the DIEs into a debug info section.
1125 // Corresponding abbreviations into a abbrev section.
1126 emitAbbreviations();
1128 // Emit info into a debug loc section.
1131 // Emit info into a debug aranges section.
1132 if (GenerateARangeSection)
1135 // Emit info into a debug ranges section.
1138 if (useSplitDwarf()) {
1141 emitDebugAbbrevDWO();
1142 // Emit DWO addresses.
1143 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1146 // Emit info into the dwarf accelerator table sections.
1147 if (useDwarfAccelTables()) {
1150 emitAccelNamespaces();
1154 // Emit the pubnames and pubtypes sections if requested.
1155 if (HasDwarfPubSections) {
1156 emitDebugPubNames(GenerateGnuPubSections);
1157 emitDebugPubTypes(GenerateGnuPubSections);
1163 // Reset these for the next Module if we have one.
1167 // Find abstract variable, if any, associated with Var.
1168 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1169 DebugLoc ScopeLoc) {
1170 LLVMContext &Ctx = DV->getContext();
1171 // More then one inlined variable corresponds to one abstract variable.
1172 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1173 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1175 return AbsDbgVariable;
1177 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1181 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1182 addScopeVariable(Scope, AbsDbgVariable);
1183 AbstractVariables[Var] = AbsDbgVariable;
1184 return AbsDbgVariable;
1187 // If Var is a current function argument then add it to CurrentFnArguments list.
1188 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1189 if (!LScopes.isCurrentFunctionScope(Scope))
1191 DIVariable DV = Var->getVariable();
1192 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1194 unsigned ArgNo = DV.getArgNumber();
1198 size_t Size = CurrentFnArguments.size();
1200 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1201 // llvm::Function argument size is not good indicator of how many
1202 // arguments does the function have at source level.
1204 CurrentFnArguments.resize(ArgNo * 2);
1205 CurrentFnArguments[ArgNo - 1] = Var;
1209 // Collect variable information from side table maintained by MMI.
1210 void DwarfDebug::collectVariableInfoFromMMITable(
1211 SmallPtrSet<const MDNode *, 16> &Processed) {
1212 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1213 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1216 const MDNode *Var = VI->first;
1219 Processed.insert(Var);
1221 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1223 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1225 // If variable scope is not found then skip this variable.
1229 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1230 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1231 RegVar->setFrameIndex(VP.first);
1232 if (!addCurrentFnArgument(RegVar, Scope))
1233 addScopeVariable(Scope, RegVar);
1235 AbsDbgVariable->setFrameIndex(VP.first);
1239 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1241 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1242 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1243 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1244 MI->getOperand(0).getReg() &&
1245 (MI->getOperand(1).isImm() ||
1246 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1249 // Get .debug_loc entry for the instruction range starting at MI.
1250 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1251 const MCSymbol *FLabel,
1252 const MCSymbol *SLabel,
1253 const MachineInstr *MI) {
1254 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1256 assert(MI->getNumOperands() == 3);
1257 if (MI->getOperand(0).isReg()) {
1258 MachineLocation MLoc;
1259 // If the second operand is an immediate, this is a
1260 // register-indirect address.
1261 if (!MI->getOperand(1).isImm())
1262 MLoc.set(MI->getOperand(0).getReg());
1264 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1265 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1267 if (MI->getOperand(0).isImm())
1268 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1269 if (MI->getOperand(0).isFPImm())
1270 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1271 if (MI->getOperand(0).isCImm())
1272 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1274 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1277 // Find variables for each lexical scope.
1279 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1281 // Grab the variable info that was squirreled away in the MMI side-table.
1282 collectVariableInfoFromMMITable(Processed);
1284 for (SmallVectorImpl<const MDNode *>::const_iterator
1285 UVI = UserVariables.begin(),
1286 UVE = UserVariables.end();
1287 UVI != UVE; ++UVI) {
1288 const MDNode *Var = *UVI;
1289 if (Processed.count(Var))
1292 // History contains relevant DBG_VALUE instructions for Var and instructions
1294 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1295 if (History.empty())
1297 const MachineInstr *MInsn = History.front();
1300 LexicalScope *Scope = NULL;
1301 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1302 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1303 Scope = LScopes.getCurrentFunctionScope();
1304 else if (MDNode *IA = DV.getInlinedAt())
1305 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1307 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1308 // If variable scope is not found then skip this variable.
1312 Processed.insert(DV);
1313 assert(MInsn->isDebugValue() && "History must begin with debug value");
1314 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1315 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1316 if (!addCurrentFnArgument(RegVar, Scope))
1317 addScopeVariable(Scope, RegVar);
1319 AbsVar->setMInsn(MInsn);
1321 // Simplify ranges that are fully coalesced.
1322 if (History.size() <= 1 ||
1323 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1324 RegVar->setMInsn(MInsn);
1328 // Handle multiple DBG_VALUE instructions describing one variable.
1329 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1331 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1332 HI = History.begin(),
1335 const MachineInstr *Begin = *HI;
1336 assert(Begin->isDebugValue() && "Invalid History entry");
1338 // Check if DBG_VALUE is truncating a range.
1339 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1340 !Begin->getOperand(0).getReg())
1343 // Compute the range for a register location.
1344 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1345 const MCSymbol *SLabel = 0;
1348 // If Begin is the last instruction in History then its value is valid
1349 // until the end of the function.
1350 SLabel = FunctionEndSym;
1352 const MachineInstr *End = HI[1];
1353 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1354 << "\t" << *Begin << "\t" << *End << "\n");
1355 if (End->isDebugValue())
1356 SLabel = getLabelBeforeInsn(End);
1358 // End is a normal instruction clobbering the range.
1359 SLabel = getLabelAfterInsn(End);
1360 assert(SLabel && "Forgot label after clobber instruction");
1365 // The value is valid until the next DBG_VALUE or clobber.
1366 DotDebugLocEntries.push_back(
1367 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1369 DotDebugLocEntries.push_back(DotDebugLocEntry());
1372 // Collect info for variables that were optimized out.
1373 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1374 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1375 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1376 DIVariable DV(Variables.getElement(i));
1377 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1379 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1380 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1384 // Return Label preceding the instruction.
1385 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1386 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1387 assert(Label && "Didn't insert label before instruction");
1391 // Return Label immediately following the instruction.
1392 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1393 return LabelsAfterInsn.lookup(MI);
1396 // Process beginning of an instruction.
1397 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1400 // Check if source location changes, but ignore DBG_VALUE locations.
1401 if (!MI->isDebugValue()) {
1402 DebugLoc DL = MI->getDebugLoc();
1403 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1406 if (DL == PrologEndLoc) {
1407 Flags |= DWARF2_FLAG_PROLOGUE_END;
1408 PrologEndLoc = DebugLoc();
1410 if (PrologEndLoc.isUnknown())
1411 Flags |= DWARF2_FLAG_IS_STMT;
1413 if (!DL.isUnknown()) {
1414 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1415 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1417 recordSourceLine(0, 0, 0, 0);
1421 // Insert labels where requested.
1422 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1423 LabelsBeforeInsn.find(MI);
1426 if (I == LabelsBeforeInsn.end())
1429 // Label already assigned.
1434 PrevLabel = MMI->getContext().CreateTempSymbol();
1435 Asm->OutStreamer.EmitLabel(PrevLabel);
1437 I->second = PrevLabel;
1440 // Process end of an instruction.
1441 void DwarfDebug::endInstruction() {
1443 // Don't create a new label after DBG_VALUE instructions.
1444 // They don't generate code.
1445 if (!CurMI->isDebugValue())
1448 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1449 LabelsAfterInsn.find(CurMI);
1453 if (I == LabelsAfterInsn.end())
1456 // Label already assigned.
1460 // We need a label after this instruction.
1462 PrevLabel = MMI->getContext().CreateTempSymbol();
1463 Asm->OutStreamer.EmitLabel(PrevLabel);
1465 I->second = PrevLabel;
1468 // Each LexicalScope has first instruction and last instruction to mark
1469 // beginning and end of a scope respectively. Create an inverse map that list
1470 // scopes starts (and ends) with an instruction. One instruction may start (or
1471 // end) multiple scopes. Ignore scopes that are not reachable.
1472 void DwarfDebug::identifyScopeMarkers() {
1473 SmallVector<LexicalScope *, 4> WorkList;
1474 WorkList.push_back(LScopes.getCurrentFunctionScope());
1475 while (!WorkList.empty()) {
1476 LexicalScope *S = WorkList.pop_back_val();
1478 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1479 if (!Children.empty())
1480 for (SmallVectorImpl<LexicalScope *>::const_iterator
1481 SI = Children.begin(),
1482 SE = Children.end();
1484 WorkList.push_back(*SI);
1486 if (S->isAbstractScope())
1489 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1492 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1495 assert(RI->first && "InsnRange does not have first instruction!");
1496 assert(RI->second && "InsnRange does not have second instruction!");
1497 requestLabelBeforeInsn(RI->first);
1498 requestLabelAfterInsn(RI->second);
1503 // Gather pre-function debug information. Assumes being called immediately
1504 // after the function entry point has been emitted.
1505 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1508 // If there's no debug info for the function we're not going to do anything.
1509 if (!MMI->hasDebugInfo())
1512 // Grab the lexical scopes for the function, if we don't have any of those
1513 // then we're not going to be able to do anything.
1514 LScopes.initialize(*MF);
1515 if (LScopes.empty())
1518 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1520 // Make sure that each lexical scope will have a begin/end label.
1521 identifyScopeMarkers();
1523 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1524 // belongs to so that we add to the correct per-cu line table in the
1526 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1527 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1528 assert(TheCU && "Unable to find compile unit!");
1529 if (Asm->OutStreamer.hasRawTextSupport())
1530 // Use a single line table if we are generating assembly.
1531 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1533 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1535 // Check the current section against the standard text section. If different
1536 // keep track so that we will know when we're emitting functions into multiple
1538 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1539 UsedNonDefaultText = true;
1541 // Emit a label for the function so that we have a beginning address.
1542 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1543 // Assumes in correct section after the entry point.
1544 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1546 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1547 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1548 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1550 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1552 bool AtBlockEntry = true;
1553 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1555 const MachineInstr *MI = II;
1557 if (MI->isDebugValue()) {
1558 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1560 // Keep track of user variables.
1562 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1564 // Variable is in a register, we need to check for clobbers.
1565 if (isDbgValueInDefinedReg(MI))
1566 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1568 // Check the history of this variable.
1569 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1570 if (History.empty()) {
1571 UserVariables.push_back(Var);
1572 // The first mention of a function argument gets the FunctionBeginSym
1573 // label, so arguments are visible when breaking at function entry.
1575 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1576 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1577 LabelsBeforeInsn[MI] = FunctionBeginSym;
1579 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1580 const MachineInstr *Prev = History.back();
1581 if (Prev->isDebugValue()) {
1582 // Coalesce identical entries at the end of History.
1583 if (History.size() >= 2 &&
1584 Prev->isIdenticalTo(History[History.size() - 2])) {
1585 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1586 << "\t" << *Prev << "\t"
1587 << *History[History.size() - 2] << "\n");
1591 // Terminate old register assignments that don't reach MI;
1592 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1593 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1594 isDbgValueInDefinedReg(Prev)) {
1595 // Previous register assignment needs to terminate at the end of
1597 MachineBasicBlock::const_iterator LastMI =
1598 PrevMBB->getLastNonDebugInstr();
1599 if (LastMI == PrevMBB->end()) {
1600 // Drop DBG_VALUE for empty range.
1601 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1602 << "\t" << *Prev << "\n");
1604 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1605 // Terminate after LastMI.
1606 History.push_back(LastMI);
1610 History.push_back(MI);
1612 // Not a DBG_VALUE instruction.
1614 AtBlockEntry = false;
1616 // First known non-DBG_VALUE and non-frame setup location marks
1617 // the beginning of the function body.
1618 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1619 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1620 PrologEndLoc = MI->getDebugLoc();
1622 // Check if the instruction clobbers any registers with debug vars.
1623 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1624 MOE = MI->operands_end();
1625 MOI != MOE; ++MOI) {
1626 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1628 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1631 const MDNode *Var = LiveUserVar[Reg];
1634 // Reg is now clobbered.
1635 LiveUserVar[Reg] = 0;
1637 // Was MD last defined by a DBG_VALUE referring to Reg?
1638 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1639 if (HistI == DbgValues.end())
1641 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1642 if (History.empty())
1644 const MachineInstr *Prev = History.back();
1645 // Sanity-check: Register assignments are terminated at the end of
1647 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1649 // Is the variable still in Reg?
1650 if (!isDbgValueInDefinedReg(Prev) ||
1651 Prev->getOperand(0).getReg() != Reg)
1653 // Var is clobbered. Make sure the next instruction gets a label.
1654 History.push_back(MI);
1661 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1663 SmallVectorImpl<const MachineInstr *> &History = I->second;
1664 if (History.empty())
1667 // Make sure the final register assignments are terminated.
1668 const MachineInstr *Prev = History.back();
1669 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1670 const MachineBasicBlock *PrevMBB = Prev->getParent();
1671 MachineBasicBlock::const_iterator LastMI =
1672 PrevMBB->getLastNonDebugInstr();
1673 if (LastMI == PrevMBB->end())
1674 // Drop DBG_VALUE for empty range.
1676 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1677 // Terminate after LastMI.
1678 History.push_back(LastMI);
1681 // Request labels for the full history.
1682 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1683 const MachineInstr *MI = History[i];
1684 if (MI->isDebugValue())
1685 requestLabelBeforeInsn(MI);
1687 requestLabelAfterInsn(MI);
1691 PrevInstLoc = DebugLoc();
1692 PrevLabel = FunctionBeginSym;
1694 // Record beginning of function.
1695 if (!PrologEndLoc.isUnknown()) {
1696 DebugLoc FnStartDL =
1697 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1699 FnStartDL.getLine(), FnStartDL.getCol(),
1700 FnStartDL.getScope(MF->getFunction()->getContext()),
1701 // We'd like to list the prologue as "not statements" but GDB behaves
1702 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1703 DWARF2_FLAG_IS_STMT);
1707 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1708 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1709 DIVariable DV = Var->getVariable();
1710 // Variables with positive arg numbers are parameters.
1711 if (unsigned ArgNum = DV.getArgNumber()) {
1712 // Keep all parameters in order at the start of the variable list to ensure
1713 // function types are correct (no out-of-order parameters)
1715 // This could be improved by only doing it for optimized builds (unoptimized
1716 // builds have the right order to begin with), searching from the back (this
1717 // would catch the unoptimized case quickly), or doing a binary search
1718 // rather than linear search.
1719 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1720 while (I != Vars.end()) {
1721 unsigned CurNum = (*I)->getVariable().getArgNumber();
1722 // A local (non-parameter) variable has been found, insert immediately
1726 // A later indexed parameter has been found, insert immediately before it.
1727 if (CurNum > ArgNum)
1731 Vars.insert(I, Var);
1735 Vars.push_back(Var);
1738 // Gather and emit post-function debug information.
1739 void DwarfDebug::endFunction(const MachineFunction *MF) {
1740 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1741 // though the beginFunction may not be called at all.
1742 // We should handle both cases.
1746 assert(CurFn == MF);
1749 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1754 // Define end label for subprogram.
1755 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1756 // Assumes in correct section after the entry point.
1757 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1759 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1760 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1762 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1763 collectVariableInfo(ProcessedVars);
1765 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1766 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1767 assert(TheCU && "Unable to find compile unit!");
1769 // Construct abstract scopes.
1770 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1771 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1772 LexicalScope *AScope = AList[i];
1773 DISubprogram SP(AScope->getScopeNode());
1774 if (SP.isSubprogram()) {
1775 // Collect info for variables that were optimized out.
1776 DIArray Variables = SP.getVariables();
1777 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1778 DIVariable DV(Variables.getElement(i));
1779 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1781 // Check that DbgVariable for DV wasn't created earlier, when
1782 // findAbstractVariable() was called for inlined instance of DV.
1783 LLVMContext &Ctx = DV->getContext();
1784 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1785 if (AbstractVariables.lookup(CleanDV))
1787 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1788 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1791 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1792 constructScopeDIE(TheCU, AScope);
1795 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1796 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1797 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1799 // Add the range of this function to the list of ranges for the CU.
1800 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1801 TheCU->addRange(std::move(Span));
1804 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1805 E = ScopeVariables.end();
1807 DeleteContainerPointers(I->second);
1808 ScopeVariables.clear();
1809 DeleteContainerPointers(CurrentFnArguments);
1810 UserVariables.clear();
1812 AbstractVariables.clear();
1813 LabelsBeforeInsn.clear();
1814 LabelsAfterInsn.clear();
1819 // Register a source line with debug info. Returns the unique label that was
1820 // emitted and which provides correspondence to the source line list.
1821 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1826 unsigned Discriminator = 0;
1828 DIDescriptor Scope(S);
1830 if (Scope.isCompileUnit()) {
1831 DICompileUnit CU(S);
1832 Fn = CU.getFilename();
1833 Dir = CU.getDirectory();
1834 } else if (Scope.isFile()) {
1836 Fn = F.getFilename();
1837 Dir = F.getDirectory();
1838 } else if (Scope.isSubprogram()) {
1840 Fn = SP.getFilename();
1841 Dir = SP.getDirectory();
1842 } else if (Scope.isLexicalBlockFile()) {
1843 DILexicalBlockFile DBF(S);
1844 Fn = DBF.getFilename();
1845 Dir = DBF.getDirectory();
1846 } else if (Scope.isLexicalBlock()) {
1847 DILexicalBlock DB(S);
1848 Fn = DB.getFilename();
1849 Dir = DB.getDirectory();
1850 Discriminator = DB.getDiscriminator();
1852 llvm_unreachable("Unexpected scope info");
1854 Src = getOrCreateSourceID(
1855 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1857 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1861 //===----------------------------------------------------------------------===//
1863 //===----------------------------------------------------------------------===//
1865 // Compute the size and offset of a DIE. The offset is relative to start of the
1866 // CU. It returns the offset after laying out the DIE.
1867 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1868 // Get the children.
1869 const std::vector<DIE *> &Children = Die->getChildren();
1871 // Record the abbreviation.
1872 assignAbbrevNumber(Die->getAbbrev());
1874 // Get the abbreviation for this DIE.
1875 const DIEAbbrev &Abbrev = Die->getAbbrev();
1878 Die->setOffset(Offset);
1880 // Start the size with the size of abbreviation code.
1881 Offset += getULEB128Size(Die->getAbbrevNumber());
1883 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1884 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1886 // Size the DIE attribute values.
1887 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1888 // Size attribute value.
1889 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1891 // Size the DIE children if any.
1892 if (!Children.empty()) {
1893 assert(Abbrev.hasChildren() && "Children flag not set");
1895 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1896 Offset = computeSizeAndOffset(Children[j], Offset);
1898 // End of children marker.
1899 Offset += sizeof(int8_t);
1902 Die->setSize(Offset - Die->getOffset());
1906 // Compute the size and offset for each DIE.
1907 void DwarfFile::computeSizeAndOffsets() {
1908 // Offset from the first CU in the debug info section is 0 initially.
1909 unsigned SecOffset = 0;
1911 // Iterate over each compile unit and set the size and offsets for each
1912 // DIE within each compile unit. All offsets are CU relative.
1913 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1916 (*I)->setDebugInfoOffset(SecOffset);
1918 // CU-relative offset is reset to 0 here.
1919 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1920 (*I)->getHeaderSize(); // Unit-specific headers
1922 // EndOffset here is CU-relative, after laying out
1923 // all of the CU DIE.
1924 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1925 SecOffset += EndOffset;
1929 // Emit initial Dwarf sections with a label at the start of each one.
1930 void DwarfDebug::emitSectionLabels() {
1931 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1933 // Dwarf sections base addresses.
1934 DwarfInfoSectionSym =
1935 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1936 if (useSplitDwarf())
1937 DwarfInfoDWOSectionSym =
1938 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1939 DwarfAbbrevSectionSym =
1940 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1941 if (useSplitDwarf())
1942 DwarfAbbrevDWOSectionSym = emitSectionSym(
1943 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1944 if (GenerateARangeSection)
1945 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1947 DwarfLineSectionSym =
1948 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1949 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1950 if (GenerateGnuPubSections) {
1951 DwarfGnuPubNamesSectionSym =
1952 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1953 DwarfGnuPubTypesSectionSym =
1954 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1955 } else if (HasDwarfPubSections) {
1956 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1957 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1960 DwarfStrSectionSym =
1961 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1962 if (useSplitDwarf()) {
1963 DwarfStrDWOSectionSym =
1964 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1965 DwarfAddrSectionSym =
1966 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1968 DwarfDebugRangeSectionSym =
1969 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1971 DwarfDebugLocSectionSym =
1972 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1975 // Recursively emits a debug information entry.
1976 void DwarfDebug::emitDIE(DIE *Die) {
1977 // Get the abbreviation for this DIE.
1978 const DIEAbbrev &Abbrev = Die->getAbbrev();
1980 // Emit the code (index) for the abbreviation.
1981 if (Asm->isVerbose())
1982 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1983 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1984 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1985 dwarf::TagString(Abbrev.getTag()));
1986 Asm->EmitULEB128(Abbrev.getNumber());
1988 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1989 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1991 // Emit the DIE attribute values.
1992 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1993 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1994 dwarf::Form Form = AbbrevData[i].getForm();
1995 assert(Form && "Too many attributes for DIE (check abbreviation)");
1997 if (Asm->isVerbose()) {
1998 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1999 if (Attr == dwarf::DW_AT_accessibility)
2000 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
2001 cast<DIEInteger>(Values[i])->getValue()));
2004 // Emit an attribute using the defined form.
2005 Values[i]->EmitValue(Asm, Form);
2008 // Emit the DIE children if any.
2009 if (Abbrev.hasChildren()) {
2010 const std::vector<DIE *> &Children = Die->getChildren();
2012 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2013 emitDIE(Children[j]);
2015 Asm->OutStreamer.AddComment("End Of Children Mark");
2020 // Emit the various dwarf units to the unit section USection with
2021 // the abbreviations going into ASection.
2022 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2023 const MCSymbol *ASectionSym) {
2024 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2026 DwarfUnit *TheU = *I;
2027 DIE *Die = TheU->getUnitDie();
2028 const MCSection *USection = TheU->getSection();
2029 Asm->OutStreamer.SwitchSection(USection);
2031 // Emit the compile units header.
2032 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2034 // Emit size of content not including length itself
2035 Asm->OutStreamer.AddComment("Length of Unit");
2036 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2038 TheU->emitHeader(ASection, ASectionSym);
2041 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2045 // Emit the debug info section.
2046 void DwarfDebug::emitDebugInfo() {
2047 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2049 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2050 DwarfAbbrevSectionSym);
2053 // Emit the abbreviation section.
2054 void DwarfDebug::emitAbbreviations() {
2055 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2057 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2060 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2061 // Check to see if it is worth the effort.
2062 if (!Abbreviations.empty()) {
2063 // Start the debug abbrev section.
2064 Asm->OutStreamer.SwitchSection(Section);
2066 // For each abbrevation.
2067 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2068 // Get abbreviation data
2069 const DIEAbbrev *Abbrev = Abbreviations[i];
2071 // Emit the abbrevations code (base 1 index.)
2072 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2074 // Emit the abbreviations data.
2078 // Mark end of abbreviations.
2079 Asm->EmitULEB128(0, "EOM(3)");
2083 // Emit the last address of the section and the end of the line matrix.
2084 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2085 // Define last address of section.
2086 Asm->OutStreamer.AddComment("Extended Op");
2089 Asm->OutStreamer.AddComment("Op size");
2090 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2091 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2092 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2094 Asm->OutStreamer.AddComment("Section end label");
2096 Asm->OutStreamer.EmitSymbolValue(
2097 Asm->GetTempSymbol("section_end", SectionEnd),
2098 Asm->getDataLayout().getPointerSize());
2100 // Mark end of matrix.
2101 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2107 // Emit visible names into a hashed accelerator table section.
2108 void DwarfDebug::emitAccelNames() {
2110 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2111 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2112 E = getUnits().end();
2114 DwarfUnit *TheU = *I;
2115 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2116 for (StringMap<std::vector<const DIE *> >::const_iterator
2120 StringRef Name = GI->getKey();
2121 const std::vector<const DIE *> &Entities = GI->second;
2122 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2123 DE = Entities.end();
2125 AT.AddName(Name, *DI);
2129 AT.FinalizeTable(Asm, "Names");
2130 Asm->OutStreamer.SwitchSection(
2131 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2132 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2133 Asm->OutStreamer.EmitLabel(SectionBegin);
2135 // Emit the full data.
2136 AT.Emit(Asm, SectionBegin, &InfoHolder);
2139 // Emit objective C classes and categories into a hashed accelerator table
2141 void DwarfDebug::emitAccelObjC() {
2143 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2144 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2145 E = getUnits().end();
2147 DwarfUnit *TheU = *I;
2148 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2149 for (StringMap<std::vector<const DIE *> >::const_iterator
2153 StringRef Name = GI->getKey();
2154 const std::vector<const DIE *> &Entities = GI->second;
2155 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2156 DE = Entities.end();
2158 AT.AddName(Name, *DI);
2162 AT.FinalizeTable(Asm, "ObjC");
2163 Asm->OutStreamer.SwitchSection(
2164 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2165 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2166 Asm->OutStreamer.EmitLabel(SectionBegin);
2168 // Emit the full data.
2169 AT.Emit(Asm, SectionBegin, &InfoHolder);
2172 // Emit namespace dies into a hashed accelerator table.
2173 void DwarfDebug::emitAccelNamespaces() {
2175 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2176 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2177 E = getUnits().end();
2179 DwarfUnit *TheU = *I;
2180 const StringMap<std::vector<const DIE *> > &Names =
2181 TheU->getAccelNamespace();
2182 for (StringMap<std::vector<const DIE *> >::const_iterator
2186 StringRef Name = GI->getKey();
2187 const std::vector<const DIE *> &Entities = GI->second;
2188 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2189 DE = Entities.end();
2191 AT.AddName(Name, *DI);
2195 AT.FinalizeTable(Asm, "namespac");
2196 Asm->OutStreamer.SwitchSection(
2197 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2198 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2199 Asm->OutStreamer.EmitLabel(SectionBegin);
2201 // Emit the full data.
2202 AT.Emit(Asm, SectionBegin, &InfoHolder);
2205 // Emit type dies into a hashed accelerator table.
2206 void DwarfDebug::emitAccelTypes() {
2207 std::vector<DwarfAccelTable::Atom> Atoms;
2209 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2211 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2213 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2214 DwarfAccelTable AT(Atoms);
2215 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2216 E = getUnits().end();
2218 DwarfUnit *TheU = *I;
2219 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2220 TheU->getAccelTypes();
2222 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2226 StringRef Name = GI->getKey();
2227 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2229 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2230 DI = Entities.begin(),
2231 DE = Entities.end();
2233 AT.AddName(Name, DI->first, DI->second);
2237 AT.FinalizeTable(Asm, "types");
2238 Asm->OutStreamer.SwitchSection(
2239 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2240 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2241 Asm->OutStreamer.EmitLabel(SectionBegin);
2243 // Emit the full data.
2244 AT.Emit(Asm, SectionBegin, &InfoHolder);
2247 // Public name handling.
2248 // The format for the various pubnames:
2250 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2251 // for the DIE that is named.
2253 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2254 // into the CU and the index value is computed according to the type of value
2255 // for the DIE that is named.
2257 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2258 // it's the offset within the debug_info/debug_types dwo section, however, the
2259 // reference in the pubname header doesn't change.
2261 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2262 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2264 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2266 // We could have a specification DIE that has our most of our knowledge,
2267 // look for that now.
2268 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2270 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2271 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2272 Linkage = dwarf::GIEL_EXTERNAL;
2273 } else if (Die->findAttribute(dwarf::DW_AT_external))
2274 Linkage = dwarf::GIEL_EXTERNAL;
2276 switch (Die->getTag()) {
2277 case dwarf::DW_TAG_class_type:
2278 case dwarf::DW_TAG_structure_type:
2279 case dwarf::DW_TAG_union_type:
2280 case dwarf::DW_TAG_enumeration_type:
2281 return dwarf::PubIndexEntryDescriptor(
2282 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2283 ? dwarf::GIEL_STATIC
2284 : dwarf::GIEL_EXTERNAL);
2285 case dwarf::DW_TAG_typedef:
2286 case dwarf::DW_TAG_base_type:
2287 case dwarf::DW_TAG_subrange_type:
2288 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2289 case dwarf::DW_TAG_namespace:
2290 return dwarf::GIEK_TYPE;
2291 case dwarf::DW_TAG_subprogram:
2292 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2293 case dwarf::DW_TAG_constant:
2294 case dwarf::DW_TAG_variable:
2295 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2296 case dwarf::DW_TAG_enumerator:
2297 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2298 dwarf::GIEL_STATIC);
2300 return dwarf::GIEK_NONE;
2304 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2306 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2307 const MCSection *PSec =
2308 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2309 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2311 for (const auto &NU : CUMap) {
2312 DwarfCompileUnit *TheU = NU.second;
2313 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2315 unsigned ID = TheU->getUniqueID();
2317 // Start the dwarf pubnames section.
2318 Asm->OutStreamer.SwitchSection(PSec);
2320 // Emit a label so we can reference the beginning of this pubname section.
2322 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2325 Asm->OutStreamer.AddComment("Length of Public Names Info");
2326 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2327 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2328 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2330 Asm->OutStreamer.EmitLabel(BeginLabel);
2332 Asm->OutStreamer.AddComment("DWARF Version");
2333 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2335 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2336 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2338 Asm->OutStreamer.AddComment("Compilation Unit Length");
2339 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2341 // Emit the pubnames for this compilation unit.
2342 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2343 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2346 const char *Name = GI->getKeyData();
2347 const DIE *Entity = GI->second;
2349 Asm->OutStreamer.AddComment("DIE offset");
2350 Asm->EmitInt32(Entity->getOffset());
2353 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2354 Asm->OutStreamer.AddComment(
2355 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2356 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2357 Asm->EmitInt8(Desc.toBits());
2360 Asm->OutStreamer.AddComment("External Name");
2361 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2364 Asm->OutStreamer.AddComment("End Mark");
2366 Asm->OutStreamer.EmitLabel(EndLabel);
2370 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2371 const MCSection *PSec =
2372 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2373 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2375 for (const auto &NU : CUMap) {
2376 DwarfCompileUnit *TheU = NU.second;
2377 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2379 unsigned ID = TheU->getUniqueID();
2381 // Start the dwarf pubtypes section.
2382 Asm->OutStreamer.SwitchSection(PSec);
2384 // Emit a label so we can reference the beginning of this pubtype section.
2386 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2389 Asm->OutStreamer.AddComment("Length of Public Types Info");
2390 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2391 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2392 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2394 Asm->OutStreamer.EmitLabel(BeginLabel);
2396 Asm->OutStreamer.AddComment("DWARF Version");
2397 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2399 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2400 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2402 Asm->OutStreamer.AddComment("Compilation Unit Length");
2403 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2405 // Emit the pubtypes.
2406 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2407 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2410 const char *Name = GI->getKeyData();
2411 const DIE *Entity = GI->second;
2413 Asm->OutStreamer.AddComment("DIE offset");
2414 Asm->EmitInt32(Entity->getOffset());
2417 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2418 Asm->OutStreamer.AddComment(
2419 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2420 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2421 Asm->EmitInt8(Desc.toBits());
2424 Asm->OutStreamer.AddComment("External Name");
2426 // Emit the name with a terminating null byte.
2427 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2430 Asm->OutStreamer.AddComment("End Mark");
2432 Asm->OutStreamer.EmitLabel(EndLabel);
2436 // Emit strings into a string section.
2437 void DwarfFile::emitStrings(const MCSection *StrSection,
2438 const MCSection *OffsetSection = NULL,
2439 const MCSymbol *StrSecSym = NULL) {
2441 if (StringPool.empty())
2444 // Start the dwarf str section.
2445 Asm->OutStreamer.SwitchSection(StrSection);
2447 // Get all of the string pool entries and put them in an array by their ID so
2448 // we can sort them.
2450 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2453 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2454 I = StringPool.begin(),
2455 E = StringPool.end();
2457 Entries.push_back(std::make_pair(I->second.second, &*I));
2459 array_pod_sort(Entries.begin(), Entries.end());
2461 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2462 // Emit a label for reference from debug information entries.
2463 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2465 // Emit the string itself with a terminating null byte.
2466 Asm->OutStreamer.EmitBytes(
2467 StringRef(Entries[i].second->getKeyData(),
2468 Entries[i].second->getKeyLength() + 1));
2471 // If we've got an offset section go ahead and emit that now as well.
2472 if (OffsetSection) {
2473 Asm->OutStreamer.SwitchSection(OffsetSection);
2474 unsigned offset = 0;
2475 unsigned size = 4; // FIXME: DWARF64 is 8.
2476 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2477 Asm->OutStreamer.EmitIntValue(offset, size);
2478 offset += Entries[i].second->getKeyLength() + 1;
2483 // Emit addresses into the section given.
2484 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2486 if (AddressPool.empty())
2489 // Start the dwarf addr section.
2490 Asm->OutStreamer.SwitchSection(AddrSection);
2492 // Order the address pool entries by ID
2493 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2495 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2497 Entries[I->second.Number] =
2499 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2500 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2502 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2503 Asm->OutStreamer.EmitValue(Entries[i],
2504 Asm->getDataLayout().getPointerSize());
2507 // Emit visible names into a debug str section.
2508 void DwarfDebug::emitDebugStr() {
2509 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2510 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2513 // Emit locations into the debug loc section.
2514 void DwarfDebug::emitDebugLoc() {
2515 if (DotDebugLocEntries.empty())
2518 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2519 I = DotDebugLocEntries.begin(),
2520 E = DotDebugLocEntries.end();
2522 DotDebugLocEntry &Entry = *I;
2523 if (I + 1 != DotDebugLocEntries.end())
2527 // Start the dwarf loc section.
2528 Asm->OutStreamer.SwitchSection(
2529 Asm->getObjFileLowering().getDwarfLocSection());
2530 unsigned char Size = Asm->getDataLayout().getPointerSize();
2531 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2533 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2534 I = DotDebugLocEntries.begin(),
2535 E = DotDebugLocEntries.end();
2536 I != E; ++I, ++index) {
2537 const DotDebugLocEntry &Entry = *I;
2538 if (Entry.isMerged())
2540 if (Entry.isEmpty()) {
2541 Asm->OutStreamer.EmitIntValue(0, Size);
2542 Asm->OutStreamer.EmitIntValue(0, Size);
2543 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2545 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2546 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2547 DIVariable DV(Entry.getVariable());
2548 Asm->OutStreamer.AddComment("Loc expr size");
2549 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2550 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2551 Asm->EmitLabelDifference(end, begin, 2);
2552 Asm->OutStreamer.EmitLabel(begin);
2553 if (Entry.isInt()) {
2554 DIBasicType BTy(DV.getType());
2555 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2556 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2557 Asm->OutStreamer.AddComment("DW_OP_consts");
2558 Asm->EmitInt8(dwarf::DW_OP_consts);
2559 Asm->EmitSLEB128(Entry.getInt());
2561 Asm->OutStreamer.AddComment("DW_OP_constu");
2562 Asm->EmitInt8(dwarf::DW_OP_constu);
2563 Asm->EmitULEB128(Entry.getInt());
2565 } else if (Entry.isLocation()) {
2566 MachineLocation Loc = Entry.getLoc();
2567 if (!DV.hasComplexAddress())
2569 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2571 // Complex address entry.
2572 unsigned N = DV.getNumAddrElements();
2574 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2575 if (Loc.getOffset()) {
2577 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2578 Asm->OutStreamer.AddComment("DW_OP_deref");
2579 Asm->EmitInt8(dwarf::DW_OP_deref);
2580 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2581 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2582 Asm->EmitSLEB128(DV.getAddrElement(1));
2584 // If first address element is OpPlus then emit
2585 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2586 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2587 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2591 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2594 // Emit remaining complex address elements.
2595 for (; i < N; ++i) {
2596 uint64_t Element = DV.getAddrElement(i);
2597 if (Element == DIBuilder::OpPlus) {
2598 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2599 Asm->EmitULEB128(DV.getAddrElement(++i));
2600 } else if (Element == DIBuilder::OpDeref) {
2602 Asm->EmitInt8(dwarf::DW_OP_deref);
2604 llvm_unreachable("unknown Opcode found in complex address");
2608 // else ... ignore constant fp. There is not any good way to
2609 // to represent them here in dwarf.
2610 Asm->OutStreamer.EmitLabel(end);
2615 struct SymbolCUSorter {
2616 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2617 const MCStreamer &Streamer;
2619 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2620 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2621 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2623 // Symbols with no order assigned should be placed at the end.
2624 // (e.g. section end labels)
2626 IA = (unsigned)(-1);
2628 IB = (unsigned)(-1);
2633 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2634 return (A->getUniqueID() < B->getUniqueID());
2638 const MCSymbol *Start, *End;
2641 // Emit a debug aranges section, containing a CU lookup for any
2642 // address we can tie back to a CU.
2643 void DwarfDebug::emitDebugARanges() {
2644 // Start the dwarf aranges section.
2645 Asm->OutStreamer.SwitchSection(
2646 Asm->getObjFileLowering().getDwarfARangesSection());
2648 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2652 // Build a list of sections used.
2653 std::vector<const MCSection *> Sections;
2654 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2656 const MCSection *Section = it->first;
2657 Sections.push_back(Section);
2660 // Sort the sections into order.
2661 // This is only done to ensure consistent output order across different runs.
2662 std::sort(Sections.begin(), Sections.end(), SectionSort);
2664 // Build a set of address spans, sorted by CU.
2665 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2666 const MCSection *Section = Sections[SecIdx];
2667 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2668 if (List.size() < 2)
2671 // Sort the symbols by offset within the section.
2672 SymbolCUSorter sorter(Asm->OutStreamer);
2673 std::sort(List.begin(), List.end(), sorter);
2675 // If we have no section (e.g. common), just write out
2676 // individual spans for each symbol.
2677 if (Section == NULL) {
2678 for (size_t n = 0; n < List.size(); n++) {
2679 const SymbolCU &Cur = List[n];
2682 Span.Start = Cur.Sym;
2685 Spans[Cur.CU].push_back(Span);
2688 // Build spans between each label.
2689 const MCSymbol *StartSym = List[0].Sym;
2690 for (size_t n = 1; n < List.size(); n++) {
2691 const SymbolCU &Prev = List[n - 1];
2692 const SymbolCU &Cur = List[n];
2694 // Try and build the longest span we can within the same CU.
2695 if (Cur.CU != Prev.CU) {
2697 Span.Start = StartSym;
2699 Spans[Prev.CU].push_back(Span);
2706 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2708 // Build a list of CUs used.
2709 std::vector<DwarfCompileUnit *> CUs;
2710 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2711 DwarfCompileUnit *CU = it->first;
2715 // Sort the CU list (again, to ensure consistent output order).
2716 std::sort(CUs.begin(), CUs.end(), CUSort);
2718 // Emit an arange table for each CU we used.
2719 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2720 DwarfCompileUnit *CU = CUs[CUIdx];
2721 std::vector<ArangeSpan> &List = Spans[CU];
2723 // Emit size of content not including length itself.
2724 unsigned ContentSize =
2725 sizeof(int16_t) + // DWARF ARange version number
2726 sizeof(int32_t) + // Offset of CU in the .debug_info section
2727 sizeof(int8_t) + // Pointer Size (in bytes)
2728 sizeof(int8_t); // Segment Size (in bytes)
2730 unsigned TupleSize = PtrSize * 2;
2732 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2734 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2736 ContentSize += Padding;
2737 ContentSize += (List.size() + 1) * TupleSize;
2739 // For each compile unit, write the list of spans it covers.
2740 Asm->OutStreamer.AddComment("Length of ARange Set");
2741 Asm->EmitInt32(ContentSize);
2742 Asm->OutStreamer.AddComment("DWARF Arange version number");
2743 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2744 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2745 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2746 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2747 Asm->EmitInt8(PtrSize);
2748 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2751 Asm->OutStreamer.EmitFill(Padding, 0xff);
2753 for (unsigned n = 0; n < List.size(); n++) {
2754 const ArangeSpan &Span = List[n];
2755 Asm->EmitLabelReference(Span.Start, PtrSize);
2757 // Calculate the size as being from the span start to it's end.
2759 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2761 // For symbols without an end marker (e.g. common), we
2762 // write a single arange entry containing just that one symbol.
2763 uint64_t Size = SymSize[Span.Start];
2767 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2771 Asm->OutStreamer.AddComment("ARange terminator");
2772 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2773 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2777 // Emit visible names into a debug ranges section.
2778 void DwarfDebug::emitDebugRanges() {
2779 // Start the dwarf ranges section.
2780 Asm->OutStreamer.SwitchSection(
2781 Asm->getObjFileLowering().getDwarfRangesSection());
2783 // Size for our labels.
2784 unsigned char Size = Asm->getDataLayout().getPointerSize();
2786 // Grab the specific ranges for the compile units in the module.
2787 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2791 DwarfCompileUnit *TheCU = I->second;
2793 // Emit a symbol so we can find the beginning of our ranges.
2794 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2796 // Iterate over the misc ranges for the compile units in the module.
2797 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2798 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2799 E = RangeLists.end();
2801 const RangeSpanList &List = *I;
2803 // Emit our symbol so we can find the beginning of the range.
2804 Asm->OutStreamer.EmitLabel(List.getSym());
2806 for (SmallVectorImpl<RangeSpan>::const_iterator
2807 RI = List.getRanges().begin(),
2808 RE = List.getRanges().end();
2810 const RangeSpan &Range = *RI;
2811 const MCSymbol *Begin = Range.getStart();
2812 const MCSymbol *End = Range.getEnd();
2813 assert(Begin && "Range without a begin symbol?");
2814 assert(End && "Range without an end symbol?");
2815 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2816 Asm->OutStreamer.EmitSymbolValue(End, Size);
2819 // And terminate the list with two 0 values.
2820 Asm->OutStreamer.EmitIntValue(0, Size);
2821 Asm->OutStreamer.EmitIntValue(0, Size);
2824 // Now emit a range for the CU itself.
2825 if (useCURanges() && TheCU->getRanges().size()) {
2826 Asm->OutStreamer.EmitLabel(
2827 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2828 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2829 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2830 RangeSpan Range = Ranges[i];
2831 const MCSymbol *Begin = Range.getStart();
2832 const MCSymbol *End = Range.getEnd();
2833 assert(Begin && "Range without a begin symbol?");
2834 assert(End && "Range without an end symbol?");
2835 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2836 Asm->OutStreamer.EmitSymbolValue(End, Size);
2838 // And terminate the list with two 0 values.
2839 Asm->OutStreamer.EmitIntValue(0, Size);
2840 Asm->OutStreamer.EmitIntValue(0, Size);
2845 // DWARF5 Experimental Separate Dwarf emitters.
2847 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2849 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2850 U->getCUNode().getSplitDebugFilename());
2852 // Relocate to the beginning of the addr_base section, else 0 for the
2853 // beginning of the one for this compile unit.
2854 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2855 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2857 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2859 if (!CompilationDir.empty())
2860 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2862 addGnuPubAttributes(NewU, Die);
2864 SkeletonHolder.addUnit(NewU);
2867 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2868 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2869 // DW_AT_ranges_base, DW_AT_addr_base.
2870 // TODO: Implement DW_AT_ranges_base.
2871 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2873 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2874 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2875 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2876 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2877 DwarfInfoSectionSym);
2879 NewCU->initStmtList(DwarfLineSectionSym);
2881 initSkeletonUnit(CU, Die, NewCU);
2886 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2888 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2889 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2890 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2892 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2893 DwarfTypeUnit *NewTU =
2894 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2895 NewTU->setTypeSignature(TU->getTypeSignature());
2896 NewTU->setType(NULL);
2898 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2899 CU.applyStmtList(*Die);
2901 initSkeletonUnit(TU, Die, NewTU);
2905 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2906 // compile units that would normally be in debug_info.
2907 void DwarfDebug::emitDebugInfoDWO() {
2908 assert(useSplitDwarf() && "No split dwarf debug info?");
2909 InfoHolder.emitUnits(this,
2910 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2911 DwarfAbbrevDWOSectionSym);
2914 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2915 // abbreviations for the .debug_info.dwo section.
2916 void DwarfDebug::emitDebugAbbrevDWO() {
2917 assert(useSplitDwarf() && "No split dwarf?");
2918 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2921 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2922 // string section and is identical in format to traditional .debug_str
2924 void DwarfDebug::emitDebugStrDWO() {
2925 assert(useSplitDwarf() && "No split dwarf?");
2926 const MCSection *OffSec =
2927 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2928 const MCSymbol *StrSym = DwarfStrSectionSym;
2929 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2933 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2934 StringRef Identifier, DIE *RefDie,
2935 DICompositeType CTy) {
2936 // Flag the type unit reference as a declaration so that if it contains
2937 // members (implicit special members, static data member definitions, member
2938 // declarations for definitions in this CU, etc) consumers don't get confused
2939 // and think this is a full definition.
2940 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2942 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2944 CU.addDIETypeSignature(RefDie, *TU);
2948 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2949 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2950 UnitDie, CU, Asm, this, &InfoHolder);
2952 InfoHolder.addUnit(NewTU);
2954 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2958 Hash.update(Identifier);
2959 // ... take the least significant 8 bytes and return those. Our MD5
2960 // implementation always returns its results in little endian, swap bytes
2962 MD5::MD5Result Result;
2964 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2965 NewTU->setTypeSignature(Signature);
2966 if (useSplitDwarf())
2967 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2969 CU.applyStmtList(*UnitDie);
2971 NewTU->setType(NewTU->createTypeDIE(CTy));
2975 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2976 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2978 CU.addDIETypeSignature(RefDie, *NewTU);