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 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
417 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
418 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
419 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
421 // Add name to the name table, we do this here because we're guaranteed
422 // to have concrete versions of our DW_TAG_subprogram nodes.
423 addSubprogramNames(SPCU, SP, SPDie);
428 /// Check whether we should create a DIE for the given Scope, return true
429 /// if we don't create a DIE (the corresponding DIE is null).
430 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
431 if (Scope->isAbstractScope())
434 // We don't create a DIE if there is no Range.
435 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
439 if (Ranges.size() > 1)
442 // We don't create a DIE if we have a single Range and the end label
444 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
445 MCSymbol *End = getLabelAfterInsn(RI->second);
449 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
450 dwarf::Attribute A, const MCSymbol *L,
451 const MCSymbol *Sec) {
452 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
453 U->addSectionLabel(D, A, L);
455 U->addSectionDelta(D, A, L, Sec);
458 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
459 const SmallVectorImpl<InsnRange> &Range) {
460 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
461 // emitting it appropriately.
462 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
463 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
464 DwarfDebugRangeSectionSym);
466 RangeSpanList List(RangeSym);
467 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
470 RangeSpan Span(getLabelBeforeInsn(RI->first),
471 getLabelAfterInsn(RI->second));
472 List.addRange(std::move(Span));
475 // Add the range list to the set of ranges to be emitted.
476 TheCU->addRangeList(std::move(List));
479 // Construct new DW_TAG_lexical_block for this scope and attach
480 // DW_AT_low_pc/DW_AT_high_pc labels.
481 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
482 LexicalScope *Scope) {
483 if (isLexicalScopeDIENull(Scope))
486 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
487 if (Scope->isAbstractScope())
490 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
492 // If we have multiple ranges, emit them into the range section.
493 if (ScopeRanges.size() > 1) {
494 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
498 // Construct the address range for this DIE.
499 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
500 MCSymbol *Start = getLabelBeforeInsn(RI->first);
501 MCSymbol *End = getLabelAfterInsn(RI->second);
502 assert(End && "End label should not be null!");
504 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
505 assert(End->isDefined() && "Invalid end label for an inlined scope!");
507 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
508 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
513 // This scope represents inlined body of a function. Construct DIE to
514 // represent this concrete inlined copy of the function.
515 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
516 LexicalScope *Scope) {
517 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
518 assert(!ScopeRanges.empty() &&
519 "LexicalScope does not have instruction markers!");
521 if (!Scope->getScopeNode())
523 DIScope DS(Scope->getScopeNode());
524 DISubprogram InlinedSP = getDISubprogram(DS);
525 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
527 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
531 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
532 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
534 // If we have multiple ranges, emit them into the range section.
535 if (ScopeRanges.size() > 1)
536 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
538 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
539 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
540 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
542 if (StartLabel == 0 || EndLabel == 0)
543 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
545 assert(StartLabel->isDefined() &&
546 "Invalid starting label for an inlined scope!");
547 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
549 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
550 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
553 InlinedSubprogramDIEs.insert(OriginDIE);
555 // Add the call site information to the DIE.
556 DILocation DL(Scope->getInlinedAt());
557 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
558 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
559 TheCU->getUniqueID()));
560 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
562 // Add name to the name table, we do this here because we're guaranteed
563 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
564 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
569 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
571 SmallVectorImpl<DIE *> &Children) {
572 DIE *ObjectPointer = NULL;
574 // Collect arguments for current function.
575 if (LScopes.isCurrentFunctionScope(Scope)) {
576 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
577 if (DbgVariable *ArgDV = CurrentFnArguments[i])
579 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
580 Children.push_back(Arg);
581 if (ArgDV->isObjectPointer())
585 // If this is a variadic function, add an unspecified parameter.
586 DISubprogram SP(Scope->getScopeNode());
587 DIArray FnArgs = SP.getType().getTypeArray();
588 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
589 .isUnspecifiedParameter()) {
590 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
591 Children.push_back(Ellipsis);
595 // Collect lexical scope children first.
596 const SmallVectorImpl<DbgVariable *> &Variables =
597 ScopeVariables.lookup(Scope);
598 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
599 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
600 Scope->isAbstractScope())) {
601 Children.push_back(Variable);
602 if (Variables[i]->isObjectPointer())
603 ObjectPointer = Variable;
605 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
606 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
607 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
608 Children.push_back(Nested);
609 return ObjectPointer;
612 // Construct a DIE for this scope.
613 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
614 LexicalScope *Scope) {
615 if (!Scope || !Scope->getScopeNode())
618 DIScope DS(Scope->getScopeNode());
620 SmallVector<DIE *, 8> Children;
621 DIE *ObjectPointer = NULL;
622 bool ChildrenCreated = false;
624 // We try to create the scope DIE first, then the children DIEs. This will
625 // avoid creating un-used children then removing them later when we find out
626 // the scope DIE is null.
627 DIE *ScopeDIE = NULL;
628 if (Scope->getInlinedAt())
629 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
630 else if (DS.isSubprogram()) {
631 ProcessedSPNodes.insert(DS);
632 if (Scope->isAbstractScope()) {
633 ScopeDIE = TheCU->getDIE(DS);
634 // Note down abstract DIE.
636 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
638 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
640 // Early exit when we know the scope DIE is going to be null.
641 if (isLexicalScopeDIENull(Scope))
644 // We create children here when we know the scope DIE is not going to be
645 // null and the children will be added to the scope DIE.
646 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
647 ChildrenCreated = true;
649 // There is no need to emit empty lexical block DIE.
650 std::pair<ImportedEntityMap::const_iterator,
651 ImportedEntityMap::const_iterator> Range =
653 ScopesWithImportedEntities.begin(),
654 ScopesWithImportedEntities.end(),
655 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
657 if (Children.empty() && Range.first == Range.second)
659 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
660 assert(ScopeDIE && "Scope DIE should not be null.");
661 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
663 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
667 assert(Children.empty() &&
668 "We create children only when the scope DIE is not null.");
671 if (!ChildrenCreated)
672 // We create children when the scope DIE is not null.
673 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
676 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
679 ScopeDIE->addChild(*I);
681 if (DS.isSubprogram() && ObjectPointer != NULL)
682 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
687 // Look up the source id with the given directory and source file names.
688 // If none currently exists, create a new id and insert it in the
689 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
691 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
693 // If we print assembly, we can't separate .file entries according to
694 // compile units. Thus all files will belong to the default compile unit.
696 // FIXME: add a better feature test than hasRawTextSupport. Even better,
697 // extend .file to support this.
698 if (Asm->OutStreamer.hasRawTextSupport())
701 // If FE did not provide a file name, then assume stdin.
702 if (FileName.empty())
703 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
705 // TODO: this might not belong here. See if we can factor this better.
706 if (DirName == CompilationDir)
709 // FileIDCUMap stores the current ID for the given compile unit.
710 unsigned SrcId = FileIDCUMap[CUID] + 1;
712 // We look up the CUID/file/dir by concatenating them with a zero byte.
713 SmallString<128> NamePair;
714 NamePair += utostr(CUID);
717 NamePair += '\0'; // Zero bytes are not allowed in paths.
718 NamePair += FileName;
720 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
721 if (Ent.getValue() != SrcId)
722 return Ent.getValue();
724 FileIDCUMap[CUID] = SrcId;
725 // Print out a .file directive to specify files for .loc directives.
726 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
731 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
732 if (!GenerateGnuPubSections)
735 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
738 // Create new DwarfCompileUnit for the given metadata node with tag
739 // DW_TAG_compile_unit.
740 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
741 StringRef FN = DIUnit.getFilename();
742 CompilationDir = DIUnit.getDirectory();
744 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
745 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
746 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
747 InfoHolder.addUnit(NewCU);
749 FileIDCUMap[NewCU->getUniqueID()] = 0;
751 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
752 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
753 DIUnit.getLanguage());
754 NewCU->addString(Die, dwarf::DW_AT_name, FN);
756 if (!useSplitDwarf()) {
757 NewCU->initStmtList(DwarfLineSectionSym);
759 // If we're using split dwarf the compilation dir is going to be in the
760 // skeleton CU and so we don't need to duplicate it here.
761 if (!CompilationDir.empty())
762 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
764 addGnuPubAttributes(NewCU, Die);
767 if (DIUnit.isOptimized())
768 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
770 StringRef Flags = DIUnit.getFlags();
772 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
774 if (unsigned RVer = DIUnit.getRunTimeVersion())
775 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
776 dwarf::DW_FORM_data1, RVer);
781 if (useSplitDwarf()) {
782 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
783 DwarfInfoDWOSectionSym);
784 NewCU->setSkeleton(constructSkeletonCU(NewCU));
786 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
787 DwarfInfoSectionSym);
789 CUMap.insert(std::make_pair(DIUnit, NewCU));
790 CUDieMap.insert(std::make_pair(Die, NewCU));
794 // Construct subprogram DIE.
795 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
797 // FIXME: We should only call this routine once, however, during LTO if a
798 // program is defined in multiple CUs we could end up calling it out of
799 // beginModule as we walk the CUs.
801 DwarfCompileUnit *&CURef = SPMap[N];
807 if (!SP.isDefinition())
808 // This is a method declaration which will be handled while constructing
812 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
814 // Expose as a global name.
815 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
818 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
820 DIImportedEntity Module(N);
821 assert(Module.Verify());
822 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
823 constructImportedEntityDIE(TheCU, Module, D);
826 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
827 const MDNode *N, DIE *Context) {
828 DIImportedEntity Module(N);
829 assert(Module.Verify());
830 return constructImportedEntityDIE(TheCU, Module, Context);
833 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
834 const DIImportedEntity &Module,
836 assert(Module.Verify() &&
837 "Use one of the MDNode * overloads to handle invalid metadata");
838 assert(Context && "Should always have a context for an imported_module");
839 DIE *IMDie = new DIE(Module.getTag());
840 TheCU->insertDIE(Module, IMDie);
842 DIDescriptor Entity = Module.getEntity();
843 if (Entity.isNameSpace())
844 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
845 else if (Entity.isSubprogram())
846 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
847 else if (Entity.isType())
848 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
850 EntityDie = TheCU->getDIE(Entity);
851 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
852 Module.getContext().getDirectory(),
853 TheCU->getUniqueID());
854 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
855 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
856 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
857 StringRef Name = Module.getName();
859 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
860 Context->addChild(IMDie);
863 // Emit all Dwarf sections that should come prior to the content. Create
864 // global DIEs and emit initial debug info sections. This is invoked by
865 // the target AsmPrinter.
866 void DwarfDebug::beginModule() {
867 if (DisableDebugInfoPrinting)
870 const Module *M = MMI->getModule();
872 // If module has named metadata anchors then use them, otherwise scan the
873 // module using debug info finder to collect debug info.
874 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
877 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
879 // Emit initial sections so we can reference labels later.
882 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
883 DICompileUnit CUNode(CU_Nodes->getOperand(i));
884 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
885 DIArray ImportedEntities = CUNode.getImportedEntities();
886 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
887 ScopesWithImportedEntities.push_back(std::make_pair(
888 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
889 ImportedEntities.getElement(i)));
890 std::sort(ScopesWithImportedEntities.begin(),
891 ScopesWithImportedEntities.end(), less_first());
892 DIArray GVs = CUNode.getGlobalVariables();
893 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
894 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
895 DIArray SPs = CUNode.getSubprograms();
896 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
897 constructSubprogramDIE(CU, SPs.getElement(i));
898 DIArray EnumTypes = CUNode.getEnumTypes();
899 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
900 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
901 DIArray RetainedTypes = CUNode.getRetainedTypes();
902 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
903 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
904 // Emit imported_modules last so that the relevant context is already
906 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
907 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
910 // Tell MMI that we have debug info.
911 MMI->setDebugInfoAvailability(true);
913 // Prime section data.
914 SectionMap[Asm->getObjFileLowering().getTextSection()];
917 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
918 void DwarfDebug::computeInlinedDIEs() {
919 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
920 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
921 AE = InlinedSubprogramDIEs.end();
924 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
926 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
927 AE = AbstractSPDies.end();
929 DIE *ISP = AI->second;
930 if (InlinedSubprogramDIEs.count(ISP))
932 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
936 // Collect info for variables that were optimized out.
937 void DwarfDebug::collectDeadVariables() {
938 const Module *M = MMI->getModule();
940 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
941 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
942 DICompileUnit TheCU(CU_Nodes->getOperand(i));
943 DIArray Subprograms = TheCU.getSubprograms();
944 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
945 DISubprogram SP(Subprograms.getElement(i));
946 if (ProcessedSPNodes.count(SP) != 0)
948 if (!SP.isSubprogram())
950 if (!SP.isDefinition())
952 DIArray Variables = SP.getVariables();
953 if (Variables.getNumElements() == 0)
956 // Construct subprogram DIE and add variables DIEs.
957 DwarfCompileUnit *SPCU =
958 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
959 assert(SPCU && "Unable to find Compile Unit!");
960 // FIXME: See the comment in constructSubprogramDIE about duplicate
962 constructSubprogramDIE(SPCU, SP);
963 DIE *SPDIE = SPCU->getDIE(SP);
964 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
965 DIVariable DV(Variables.getElement(vi));
966 if (!DV.isVariable())
968 DbgVariable NewVar(DV, NULL, this);
969 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
970 SPDIE->addChild(VariableDIE);
977 void DwarfDebug::finalizeModuleInfo() {
978 // Collect info for variables that were optimized out.
979 collectDeadVariables();
981 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
982 computeInlinedDIEs();
984 // Handle anything that needs to be done on a per-unit basis after
985 // all other generation.
986 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
987 E = getUnits().end();
989 DwarfUnit *TheU = *I;
990 // Emit DW_AT_containing_type attribute to connect types with their
991 // vtable holding type.
992 TheU->constructContainingTypeDIEs();
994 // Add CU specific attributes if we need to add any.
995 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
996 // If we're splitting the dwarf out now that we've got the entire
997 // CU then add the dwo id to it.
998 DwarfCompileUnit *SkCU =
999 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1000 if (useSplitDwarf()) {
1001 // This should be a unique identifier when we want to build .dwp files.
1003 if (GenerateCUHash) {
1004 DIEHash CUHash(Asm);
1005 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1007 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1008 dwarf::DW_FORM_data8, ID);
1009 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1010 dwarf::DW_FORM_data8, ID);
1013 // If we have code split among multiple sections or we've requested
1014 // it then emit a DW_AT_ranges attribute on the unit that will remain
1015 // in the .o file, otherwise add a DW_AT_low_pc.
1016 // FIXME: Also add a high pc if we can.
1017 // FIXME: We should use ranges if we have multiple compile units or
1018 // allow reordering of code ala .subsections_via_symbols in mach-o.
1019 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1020 if (useCURanges() && TheU->getRanges().size()) {
1021 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1022 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1023 DwarfDebugRangeSectionSym);
1025 // A DW_AT_low_pc attribute may also be specified in combination with
1026 // DW_AT_ranges to specify the default base address for use in location
1027 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1028 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1031 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1036 // Compute DIE offsets and sizes.
1037 InfoHolder.computeSizeAndOffsets();
1038 if (useSplitDwarf())
1039 SkeletonHolder.computeSizeAndOffsets();
1042 void DwarfDebug::endSections() {
1043 // Filter labels by section.
1044 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1045 const SymbolCU &SCU = ArangeLabels[n];
1046 if (SCU.Sym->isInSection()) {
1047 // Make a note of this symbol and it's section.
1048 const MCSection *Section = &SCU.Sym->getSection();
1049 if (!Section->getKind().isMetadata())
1050 SectionMap[Section].push_back(SCU);
1052 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1053 // appear in the output. This sucks as we rely on sections to build
1054 // arange spans. We can do it without, but it's icky.
1055 SectionMap[NULL].push_back(SCU);
1059 // Build a list of sections used.
1060 std::vector<const MCSection *> Sections;
1061 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1063 const MCSection *Section = it->first;
1064 Sections.push_back(Section);
1067 // Sort the sections into order.
1068 // This is only done to ensure consistent output order across different runs.
1069 std::sort(Sections.begin(), Sections.end(), SectionSort);
1071 // Add terminating symbols for each section.
1072 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1073 const MCSection *Section = Sections[ID];
1074 MCSymbol *Sym = NULL;
1077 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1078 // if we know the section name up-front. For user-created sections, the
1079 // resulting label may not be valid to use as a label. (section names can
1080 // use a greater set of characters on some systems)
1081 Sym = Asm->GetTempSymbol("debug_end", ID);
1082 Asm->OutStreamer.SwitchSection(Section);
1083 Asm->OutStreamer.EmitLabel(Sym);
1086 // Insert a final terminator.
1087 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1090 // For now only turn on CU ranges if we've explicitly asked for it,
1091 // we have -ffunction-sections enabled, we've emitted a function
1092 // into a unique section, or we're using LTO. If we're using LTO then
1093 // we can't know that any particular function in the module is correlated
1094 // to a particular CU and so we need to be conservative. At this point all
1095 // sections should be finalized except for dwarf sections.
1096 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1097 TargetMachine::getFunctionSections();
1100 // Emit all Dwarf sections that should come after the content.
1101 void DwarfDebug::endModule() {
1108 // End any existing sections.
1109 // TODO: Does this need to happen?
1112 // Finalize the debug info for the module.
1113 finalizeModuleInfo();
1117 // Emit all the DIEs into a debug info section.
1120 // Corresponding abbreviations into a abbrev section.
1121 emitAbbreviations();
1123 // Emit info into a debug loc section.
1126 // Emit info into a debug aranges section.
1127 if (GenerateARangeSection)
1130 // Emit info into a debug ranges section.
1133 if (useSplitDwarf()) {
1136 emitDebugAbbrevDWO();
1137 // Emit DWO addresses.
1138 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1141 // Emit info into the dwarf accelerator table sections.
1142 if (useDwarfAccelTables()) {
1145 emitAccelNamespaces();
1149 // Emit the pubnames and pubtypes sections if requested.
1150 if (HasDwarfPubSections) {
1151 emitDebugPubNames(GenerateGnuPubSections);
1152 emitDebugPubTypes(GenerateGnuPubSections);
1158 // Reset these for the next Module if we have one.
1162 // Find abstract variable, if any, associated with Var.
1163 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1164 DebugLoc ScopeLoc) {
1165 LLVMContext &Ctx = DV->getContext();
1166 // More then one inlined variable corresponds to one abstract variable.
1167 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1168 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1170 return AbsDbgVariable;
1172 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1176 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1177 addScopeVariable(Scope, AbsDbgVariable);
1178 AbstractVariables[Var] = AbsDbgVariable;
1179 return AbsDbgVariable;
1182 // If Var is a current function argument then add it to CurrentFnArguments list.
1183 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1184 if (!LScopes.isCurrentFunctionScope(Scope))
1186 DIVariable DV = Var->getVariable();
1187 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1189 unsigned ArgNo = DV.getArgNumber();
1193 size_t Size = CurrentFnArguments.size();
1195 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1196 // llvm::Function argument size is not good indicator of how many
1197 // arguments does the function have at source level.
1199 CurrentFnArguments.resize(ArgNo * 2);
1200 CurrentFnArguments[ArgNo - 1] = Var;
1204 // Collect variable information from side table maintained by MMI.
1205 void DwarfDebug::collectVariableInfoFromMMITable(
1206 SmallPtrSet<const MDNode *, 16> &Processed) {
1207 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1208 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1211 const MDNode *Var = VI->first;
1214 Processed.insert(Var);
1216 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1218 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1220 // If variable scope is not found then skip this variable.
1224 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1225 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1226 RegVar->setFrameIndex(VP.first);
1227 if (!addCurrentFnArgument(RegVar, Scope))
1228 addScopeVariable(Scope, RegVar);
1230 AbsDbgVariable->setFrameIndex(VP.first);
1234 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1236 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1237 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1238 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1239 MI->getOperand(0).getReg() &&
1240 (MI->getOperand(1).isImm() ||
1241 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1244 // Get .debug_loc entry for the instruction range starting at MI.
1245 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1246 const MCSymbol *FLabel,
1247 const MCSymbol *SLabel,
1248 const MachineInstr *MI) {
1249 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1251 assert(MI->getNumOperands() == 3);
1252 if (MI->getOperand(0).isReg()) {
1253 MachineLocation MLoc;
1254 // If the second operand is an immediate, this is a
1255 // register-indirect address.
1256 if (!MI->getOperand(1).isImm())
1257 MLoc.set(MI->getOperand(0).getReg());
1259 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1260 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1262 if (MI->getOperand(0).isImm())
1263 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1264 if (MI->getOperand(0).isFPImm())
1265 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1266 if (MI->getOperand(0).isCImm())
1267 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1269 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1272 // Find variables for each lexical scope.
1274 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1276 // Grab the variable info that was squirreled away in the MMI side-table.
1277 collectVariableInfoFromMMITable(Processed);
1279 for (SmallVectorImpl<const MDNode *>::const_iterator
1280 UVI = UserVariables.begin(),
1281 UVE = UserVariables.end();
1282 UVI != UVE; ++UVI) {
1283 const MDNode *Var = *UVI;
1284 if (Processed.count(Var))
1287 // History contains relevant DBG_VALUE instructions for Var and instructions
1289 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1290 if (History.empty())
1292 const MachineInstr *MInsn = History.front();
1295 LexicalScope *Scope = NULL;
1296 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1297 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1298 Scope = LScopes.getCurrentFunctionScope();
1299 else if (MDNode *IA = DV.getInlinedAt())
1300 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1302 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1303 // If variable scope is not found then skip this variable.
1307 Processed.insert(DV);
1308 assert(MInsn->isDebugValue() && "History must begin with debug value");
1309 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1310 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1311 if (!addCurrentFnArgument(RegVar, Scope))
1312 addScopeVariable(Scope, RegVar);
1314 AbsVar->setMInsn(MInsn);
1316 // Simplify ranges that are fully coalesced.
1317 if (History.size() <= 1 ||
1318 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1319 RegVar->setMInsn(MInsn);
1323 // Handle multiple DBG_VALUE instructions describing one variable.
1324 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1326 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1327 HI = History.begin(),
1330 const MachineInstr *Begin = *HI;
1331 assert(Begin->isDebugValue() && "Invalid History entry");
1333 // Check if DBG_VALUE is truncating a range.
1334 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1335 !Begin->getOperand(0).getReg())
1338 // Compute the range for a register location.
1339 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1340 const MCSymbol *SLabel = 0;
1343 // If Begin is the last instruction in History then its value is valid
1344 // until the end of the function.
1345 SLabel = FunctionEndSym;
1347 const MachineInstr *End = HI[1];
1348 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1349 << "\t" << *Begin << "\t" << *End << "\n");
1350 if (End->isDebugValue())
1351 SLabel = getLabelBeforeInsn(End);
1353 // End is a normal instruction clobbering the range.
1354 SLabel = getLabelAfterInsn(End);
1355 assert(SLabel && "Forgot label after clobber instruction");
1360 // The value is valid until the next DBG_VALUE or clobber.
1361 DotDebugLocEntries.push_back(
1362 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1364 DotDebugLocEntries.push_back(DotDebugLocEntry());
1367 // Collect info for variables that were optimized out.
1368 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1369 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1370 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1371 DIVariable DV(Variables.getElement(i));
1372 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1374 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1375 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1379 // Return Label preceding the instruction.
1380 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1381 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1382 assert(Label && "Didn't insert label before instruction");
1386 // Return Label immediately following the instruction.
1387 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1388 return LabelsAfterInsn.lookup(MI);
1391 // Process beginning of an instruction.
1392 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1395 // Check if source location changes, but ignore DBG_VALUE locations.
1396 if (!MI->isDebugValue()) {
1397 DebugLoc DL = MI->getDebugLoc();
1398 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1401 if (DL == PrologEndLoc) {
1402 Flags |= DWARF2_FLAG_PROLOGUE_END;
1403 PrologEndLoc = DebugLoc();
1405 if (PrologEndLoc.isUnknown())
1406 Flags |= DWARF2_FLAG_IS_STMT;
1408 if (!DL.isUnknown()) {
1409 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1410 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1412 recordSourceLine(0, 0, 0, 0);
1416 // Insert labels where requested.
1417 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1418 LabelsBeforeInsn.find(MI);
1421 if (I == LabelsBeforeInsn.end())
1424 // Label already assigned.
1429 PrevLabel = MMI->getContext().CreateTempSymbol();
1430 Asm->OutStreamer.EmitLabel(PrevLabel);
1432 I->second = PrevLabel;
1435 // Process end of an instruction.
1436 void DwarfDebug::endInstruction() {
1438 // Don't create a new label after DBG_VALUE instructions.
1439 // They don't generate code.
1440 if (!CurMI->isDebugValue())
1443 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1444 LabelsAfterInsn.find(CurMI);
1448 if (I == LabelsAfterInsn.end())
1451 // Label already assigned.
1455 // We need a label after this instruction.
1457 PrevLabel = MMI->getContext().CreateTempSymbol();
1458 Asm->OutStreamer.EmitLabel(PrevLabel);
1460 I->second = PrevLabel;
1463 // Each LexicalScope has first instruction and last instruction to mark
1464 // beginning and end of a scope respectively. Create an inverse map that list
1465 // scopes starts (and ends) with an instruction. One instruction may start (or
1466 // end) multiple scopes. Ignore scopes that are not reachable.
1467 void DwarfDebug::identifyScopeMarkers() {
1468 SmallVector<LexicalScope *, 4> WorkList;
1469 WorkList.push_back(LScopes.getCurrentFunctionScope());
1470 while (!WorkList.empty()) {
1471 LexicalScope *S = WorkList.pop_back_val();
1473 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1474 if (!Children.empty())
1475 for (SmallVectorImpl<LexicalScope *>::const_iterator
1476 SI = Children.begin(),
1477 SE = Children.end();
1479 WorkList.push_back(*SI);
1481 if (S->isAbstractScope())
1484 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1487 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1490 assert(RI->first && "InsnRange does not have first instruction!");
1491 assert(RI->second && "InsnRange does not have second instruction!");
1492 requestLabelBeforeInsn(RI->first);
1493 requestLabelAfterInsn(RI->second);
1498 // Gather pre-function debug information. Assumes being called immediately
1499 // after the function entry point has been emitted.
1500 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1503 // If there's no debug info for the function we're not going to do anything.
1504 if (!MMI->hasDebugInfo())
1507 // Grab the lexical scopes for the function, if we don't have any of those
1508 // then we're not going to be able to do anything.
1509 LScopes.initialize(*MF);
1510 if (LScopes.empty())
1513 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1515 // Make sure that each lexical scope will have a begin/end label.
1516 identifyScopeMarkers();
1518 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1519 // belongs to so that we add to the correct per-cu line table in the
1521 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1522 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1523 assert(TheCU && "Unable to find compile unit!");
1524 if (Asm->OutStreamer.hasRawTextSupport())
1525 // Use a single line table if we are generating assembly.
1526 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1528 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1530 // Check the current section against the standard text section. If different
1531 // keep track so that we will know when we're emitting functions into multiple
1533 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1534 UsedNonDefaultText = true;
1536 // Emit a label for the function so that we have a beginning address.
1537 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1538 // Assumes in correct section after the entry point.
1539 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1541 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1542 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1543 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1545 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1547 bool AtBlockEntry = true;
1548 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1550 const MachineInstr *MI = II;
1552 if (MI->isDebugValue()) {
1553 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1555 // Keep track of user variables.
1557 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1559 // Variable is in a register, we need to check for clobbers.
1560 if (isDbgValueInDefinedReg(MI))
1561 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1563 // Check the history of this variable.
1564 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1565 if (History.empty()) {
1566 UserVariables.push_back(Var);
1567 // The first mention of a function argument gets the FunctionBeginSym
1568 // label, so arguments are visible when breaking at function entry.
1570 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1571 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1572 LabelsBeforeInsn[MI] = FunctionBeginSym;
1574 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1575 const MachineInstr *Prev = History.back();
1576 if (Prev->isDebugValue()) {
1577 // Coalesce identical entries at the end of History.
1578 if (History.size() >= 2 &&
1579 Prev->isIdenticalTo(History[History.size() - 2])) {
1580 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1581 << "\t" << *Prev << "\t"
1582 << *History[History.size() - 2] << "\n");
1586 // Terminate old register assignments that don't reach MI;
1587 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1588 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1589 isDbgValueInDefinedReg(Prev)) {
1590 // Previous register assignment needs to terminate at the end of
1592 MachineBasicBlock::const_iterator LastMI =
1593 PrevMBB->getLastNonDebugInstr();
1594 if (LastMI == PrevMBB->end()) {
1595 // Drop DBG_VALUE for empty range.
1596 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1597 << "\t" << *Prev << "\n");
1599 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1600 // Terminate after LastMI.
1601 History.push_back(LastMI);
1605 History.push_back(MI);
1607 // Not a DBG_VALUE instruction.
1608 if (!MI->isPosition())
1609 AtBlockEntry = false;
1611 // First known non-DBG_VALUE and non-frame setup location marks
1612 // the beginning of the function body.
1613 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1614 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1615 PrologEndLoc = MI->getDebugLoc();
1617 // Check if the instruction clobbers any registers with debug vars.
1618 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1619 MOE = MI->operands_end();
1620 MOI != MOE; ++MOI) {
1621 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1623 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1626 const MDNode *Var = LiveUserVar[Reg];
1629 // Reg is now clobbered.
1630 LiveUserVar[Reg] = 0;
1632 // Was MD last defined by a DBG_VALUE referring to Reg?
1633 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1634 if (HistI == DbgValues.end())
1636 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1637 if (History.empty())
1639 const MachineInstr *Prev = History.back();
1640 // Sanity-check: Register assignments are terminated at the end of
1642 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1644 // Is the variable still in Reg?
1645 if (!isDbgValueInDefinedReg(Prev) ||
1646 Prev->getOperand(0).getReg() != Reg)
1648 // Var is clobbered. Make sure the next instruction gets a label.
1649 History.push_back(MI);
1656 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1658 SmallVectorImpl<const MachineInstr *> &History = I->second;
1659 if (History.empty())
1662 // Make sure the final register assignments are terminated.
1663 const MachineInstr *Prev = History.back();
1664 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1665 const MachineBasicBlock *PrevMBB = Prev->getParent();
1666 MachineBasicBlock::const_iterator LastMI =
1667 PrevMBB->getLastNonDebugInstr();
1668 if (LastMI == PrevMBB->end())
1669 // Drop DBG_VALUE for empty range.
1671 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1672 // Terminate after LastMI.
1673 History.push_back(LastMI);
1676 // Request labels for the full history.
1677 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1678 const MachineInstr *MI = History[i];
1679 if (MI->isDebugValue())
1680 requestLabelBeforeInsn(MI);
1682 requestLabelAfterInsn(MI);
1686 PrevInstLoc = DebugLoc();
1687 PrevLabel = FunctionBeginSym;
1689 // Record beginning of function.
1690 if (!PrologEndLoc.isUnknown()) {
1691 DebugLoc FnStartDL =
1692 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1694 FnStartDL.getLine(), FnStartDL.getCol(),
1695 FnStartDL.getScope(MF->getFunction()->getContext()),
1696 // We'd like to list the prologue as "not statements" but GDB behaves
1697 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1698 DWARF2_FLAG_IS_STMT);
1702 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1703 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1704 DIVariable DV = Var->getVariable();
1705 // Variables with positive arg numbers are parameters.
1706 if (unsigned ArgNum = DV.getArgNumber()) {
1707 // Keep all parameters in order at the start of the variable list to ensure
1708 // function types are correct (no out-of-order parameters)
1710 // This could be improved by only doing it for optimized builds (unoptimized
1711 // builds have the right order to begin with), searching from the back (this
1712 // would catch the unoptimized case quickly), or doing a binary search
1713 // rather than linear search.
1714 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1715 while (I != Vars.end()) {
1716 unsigned CurNum = (*I)->getVariable().getArgNumber();
1717 // A local (non-parameter) variable has been found, insert immediately
1721 // A later indexed parameter has been found, insert immediately before it.
1722 if (CurNum > ArgNum)
1726 Vars.insert(I, Var);
1730 Vars.push_back(Var);
1733 // Gather and emit post-function debug information.
1734 void DwarfDebug::endFunction(const MachineFunction *MF) {
1735 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1736 // though the beginFunction may not be called at all.
1737 // We should handle both cases.
1741 assert(CurFn == MF);
1744 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1749 // Define end label for subprogram.
1750 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1751 // Assumes in correct section after the entry point.
1752 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1754 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1755 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1757 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1758 collectVariableInfo(ProcessedVars);
1760 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1761 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1762 assert(TheCU && "Unable to find compile unit!");
1764 // Construct abstract scopes.
1765 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1766 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1767 LexicalScope *AScope = AList[i];
1768 DISubprogram SP(AScope->getScopeNode());
1769 if (SP.isSubprogram()) {
1770 // Collect info for variables that were optimized out.
1771 DIArray Variables = SP.getVariables();
1772 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1773 DIVariable DV(Variables.getElement(i));
1774 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1776 // Check that DbgVariable for DV wasn't created earlier, when
1777 // findAbstractVariable() was called for inlined instance of DV.
1778 LLVMContext &Ctx = DV->getContext();
1779 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1780 if (AbstractVariables.lookup(CleanDV))
1782 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1783 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1786 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1787 constructScopeDIE(TheCU, AScope);
1790 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1791 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1792 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1794 // Add the range of this function to the list of ranges for the CU.
1795 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1796 TheCU->addRange(std::move(Span));
1799 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1800 E = ScopeVariables.end();
1802 DeleteContainerPointers(I->second);
1803 ScopeVariables.clear();
1804 DeleteContainerPointers(CurrentFnArguments);
1805 UserVariables.clear();
1807 AbstractVariables.clear();
1808 LabelsBeforeInsn.clear();
1809 LabelsAfterInsn.clear();
1814 // Register a source line with debug info. Returns the unique label that was
1815 // emitted and which provides correspondence to the source line list.
1816 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1821 unsigned Discriminator = 0;
1823 DIDescriptor Scope(S);
1825 if (Scope.isCompileUnit()) {
1826 DICompileUnit CU(S);
1827 Fn = CU.getFilename();
1828 Dir = CU.getDirectory();
1829 } else if (Scope.isFile()) {
1831 Fn = F.getFilename();
1832 Dir = F.getDirectory();
1833 } else if (Scope.isSubprogram()) {
1835 Fn = SP.getFilename();
1836 Dir = SP.getDirectory();
1837 } else if (Scope.isLexicalBlockFile()) {
1838 DILexicalBlockFile DBF(S);
1839 Fn = DBF.getFilename();
1840 Dir = DBF.getDirectory();
1841 } else if (Scope.isLexicalBlock()) {
1842 DILexicalBlock DB(S);
1843 Fn = DB.getFilename();
1844 Dir = DB.getDirectory();
1845 Discriminator = DB.getDiscriminator();
1847 llvm_unreachable("Unexpected scope info");
1849 Src = getOrCreateSourceID(
1850 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1852 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1856 //===----------------------------------------------------------------------===//
1858 //===----------------------------------------------------------------------===//
1860 // Compute the size and offset of a DIE. The offset is relative to start of the
1861 // CU. It returns the offset after laying out the DIE.
1862 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1863 // Get the children.
1864 const std::vector<DIE *> &Children = Die->getChildren();
1866 // Record the abbreviation.
1867 assignAbbrevNumber(Die->getAbbrev());
1869 // Get the abbreviation for this DIE.
1870 const DIEAbbrev &Abbrev = Die->getAbbrev();
1873 Die->setOffset(Offset);
1875 // Start the size with the size of abbreviation code.
1876 Offset += getULEB128Size(Die->getAbbrevNumber());
1878 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1879 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1881 // Size the DIE attribute values.
1882 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1883 // Size attribute value.
1884 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1886 // Size the DIE children if any.
1887 if (!Children.empty()) {
1888 assert(Abbrev.hasChildren() && "Children flag not set");
1890 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1891 Offset = computeSizeAndOffset(Children[j], Offset);
1893 // End of children marker.
1894 Offset += sizeof(int8_t);
1897 Die->setSize(Offset - Die->getOffset());
1901 // Compute the size and offset for each DIE.
1902 void DwarfFile::computeSizeAndOffsets() {
1903 // Offset from the first CU in the debug info section is 0 initially.
1904 unsigned SecOffset = 0;
1906 // Iterate over each compile unit and set the size and offsets for each
1907 // DIE within each compile unit. All offsets are CU relative.
1908 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1911 (*I)->setDebugInfoOffset(SecOffset);
1913 // CU-relative offset is reset to 0 here.
1914 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1915 (*I)->getHeaderSize(); // Unit-specific headers
1917 // EndOffset here is CU-relative, after laying out
1918 // all of the CU DIE.
1919 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1920 SecOffset += EndOffset;
1924 // Emit initial Dwarf sections with a label at the start of each one.
1925 void DwarfDebug::emitSectionLabels() {
1926 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1928 // Dwarf sections base addresses.
1929 DwarfInfoSectionSym =
1930 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1931 if (useSplitDwarf())
1932 DwarfInfoDWOSectionSym =
1933 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1934 DwarfAbbrevSectionSym =
1935 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1936 if (useSplitDwarf())
1937 DwarfAbbrevDWOSectionSym = emitSectionSym(
1938 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1939 if (GenerateARangeSection)
1940 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1942 DwarfLineSectionSym =
1943 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1944 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1945 if (GenerateGnuPubSections) {
1946 DwarfGnuPubNamesSectionSym =
1947 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1948 DwarfGnuPubTypesSectionSym =
1949 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1950 } else if (HasDwarfPubSections) {
1951 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1952 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1955 DwarfStrSectionSym =
1956 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1957 if (useSplitDwarf()) {
1958 DwarfStrDWOSectionSym =
1959 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1960 DwarfAddrSectionSym =
1961 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1963 DwarfDebugRangeSectionSym =
1964 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1966 DwarfDebugLocSectionSym =
1967 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1970 // Recursively emits a debug information entry.
1971 void DwarfDebug::emitDIE(DIE *Die) {
1972 // Get the abbreviation for this DIE.
1973 const DIEAbbrev &Abbrev = Die->getAbbrev();
1975 // Emit the code (index) for the abbreviation.
1976 if (Asm->isVerbose())
1977 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1978 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1979 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1980 dwarf::TagString(Abbrev.getTag()));
1981 Asm->EmitULEB128(Abbrev.getNumber());
1983 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1984 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1986 // Emit the DIE attribute values.
1987 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1988 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1989 dwarf::Form Form = AbbrevData[i].getForm();
1990 assert(Form && "Too many attributes for DIE (check abbreviation)");
1992 if (Asm->isVerbose()) {
1993 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1994 if (Attr == dwarf::DW_AT_accessibility)
1995 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1996 cast<DIEInteger>(Values[i])->getValue()));
1999 // Emit an attribute using the defined form.
2000 Values[i]->EmitValue(Asm, Form);
2003 // Emit the DIE children if any.
2004 if (Abbrev.hasChildren()) {
2005 const std::vector<DIE *> &Children = Die->getChildren();
2007 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2008 emitDIE(Children[j]);
2010 Asm->OutStreamer.AddComment("End Of Children Mark");
2015 // Emit the various dwarf units to the unit section USection with
2016 // the abbreviations going into ASection.
2017 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2018 const MCSymbol *ASectionSym) {
2019 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2021 DwarfUnit *TheU = *I;
2022 DIE *Die = TheU->getUnitDie();
2023 const MCSection *USection = TheU->getSection();
2024 Asm->OutStreamer.SwitchSection(USection);
2026 // Emit the compile units header.
2027 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2029 // Emit size of content not including length itself
2030 Asm->OutStreamer.AddComment("Length of Unit");
2031 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2033 TheU->emitHeader(ASection, ASectionSym);
2036 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2040 // Emit the debug info section.
2041 void DwarfDebug::emitDebugInfo() {
2042 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2044 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2045 DwarfAbbrevSectionSym);
2048 // Emit the abbreviation section.
2049 void DwarfDebug::emitAbbreviations() {
2050 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2052 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2055 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2056 // Check to see if it is worth the effort.
2057 if (!Abbreviations.empty()) {
2058 // Start the debug abbrev section.
2059 Asm->OutStreamer.SwitchSection(Section);
2061 // For each abbrevation.
2062 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2063 // Get abbreviation data
2064 const DIEAbbrev *Abbrev = Abbreviations[i];
2066 // Emit the abbrevations code (base 1 index.)
2067 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2069 // Emit the abbreviations data.
2073 // Mark end of abbreviations.
2074 Asm->EmitULEB128(0, "EOM(3)");
2078 // Emit the last address of the section and the end of the line matrix.
2079 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2080 // Define last address of section.
2081 Asm->OutStreamer.AddComment("Extended Op");
2084 Asm->OutStreamer.AddComment("Op size");
2085 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2086 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2087 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2089 Asm->OutStreamer.AddComment("Section end label");
2091 Asm->OutStreamer.EmitSymbolValue(
2092 Asm->GetTempSymbol("section_end", SectionEnd),
2093 Asm->getDataLayout().getPointerSize());
2095 // Mark end of matrix.
2096 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2102 // Emit visible names into a hashed accelerator table section.
2103 void DwarfDebug::emitAccelNames() {
2105 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2106 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2107 E = getUnits().end();
2109 DwarfUnit *TheU = *I;
2110 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2111 for (StringMap<std::vector<const DIE *> >::const_iterator
2115 StringRef Name = GI->getKey();
2116 const std::vector<const DIE *> &Entities = GI->second;
2117 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2118 DE = Entities.end();
2120 AT.AddName(Name, *DI);
2124 AT.FinalizeTable(Asm, "Names");
2125 Asm->OutStreamer.SwitchSection(
2126 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2127 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2128 Asm->OutStreamer.EmitLabel(SectionBegin);
2130 // Emit the full data.
2131 AT.Emit(Asm, SectionBegin, &InfoHolder);
2134 // Emit objective C classes and categories into a hashed accelerator table
2136 void DwarfDebug::emitAccelObjC() {
2138 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2139 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2140 E = getUnits().end();
2142 DwarfUnit *TheU = *I;
2143 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2144 for (StringMap<std::vector<const DIE *> >::const_iterator
2148 StringRef Name = GI->getKey();
2149 const std::vector<const DIE *> &Entities = GI->second;
2150 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2151 DE = Entities.end();
2153 AT.AddName(Name, *DI);
2157 AT.FinalizeTable(Asm, "ObjC");
2158 Asm->OutStreamer.SwitchSection(
2159 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2160 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2161 Asm->OutStreamer.EmitLabel(SectionBegin);
2163 // Emit the full data.
2164 AT.Emit(Asm, SectionBegin, &InfoHolder);
2167 // Emit namespace dies into a hashed accelerator table.
2168 void DwarfDebug::emitAccelNamespaces() {
2170 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2171 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2172 E = getUnits().end();
2174 DwarfUnit *TheU = *I;
2175 const StringMap<std::vector<const DIE *> > &Names =
2176 TheU->getAccelNamespace();
2177 for (StringMap<std::vector<const DIE *> >::const_iterator
2181 StringRef Name = GI->getKey();
2182 const std::vector<const DIE *> &Entities = GI->second;
2183 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2184 DE = Entities.end();
2186 AT.AddName(Name, *DI);
2190 AT.FinalizeTable(Asm, "namespac");
2191 Asm->OutStreamer.SwitchSection(
2192 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2193 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2194 Asm->OutStreamer.EmitLabel(SectionBegin);
2196 // Emit the full data.
2197 AT.Emit(Asm, SectionBegin, &InfoHolder);
2200 // Emit type dies into a hashed accelerator table.
2201 void DwarfDebug::emitAccelTypes() {
2202 std::vector<DwarfAccelTable::Atom> Atoms;
2204 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2206 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2208 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2209 DwarfAccelTable AT(Atoms);
2210 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2211 E = getUnits().end();
2213 DwarfUnit *TheU = *I;
2214 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2215 TheU->getAccelTypes();
2217 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2221 StringRef Name = GI->getKey();
2222 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2224 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2225 DI = Entities.begin(),
2226 DE = Entities.end();
2228 AT.AddName(Name, DI->first, DI->second);
2232 AT.FinalizeTable(Asm, "types");
2233 Asm->OutStreamer.SwitchSection(
2234 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2235 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2236 Asm->OutStreamer.EmitLabel(SectionBegin);
2238 // Emit the full data.
2239 AT.Emit(Asm, SectionBegin, &InfoHolder);
2242 // Public name handling.
2243 // The format for the various pubnames:
2245 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2246 // for the DIE that is named.
2248 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2249 // into the CU and the index value is computed according to the type of value
2250 // for the DIE that is named.
2252 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2253 // it's the offset within the debug_info/debug_types dwo section, however, the
2254 // reference in the pubname header doesn't change.
2256 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2257 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2259 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2261 // We could have a specification DIE that has our most of our knowledge,
2262 // look for that now.
2263 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2265 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2266 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2267 Linkage = dwarf::GIEL_EXTERNAL;
2268 } else if (Die->findAttribute(dwarf::DW_AT_external))
2269 Linkage = dwarf::GIEL_EXTERNAL;
2271 switch (Die->getTag()) {
2272 case dwarf::DW_TAG_class_type:
2273 case dwarf::DW_TAG_structure_type:
2274 case dwarf::DW_TAG_union_type:
2275 case dwarf::DW_TAG_enumeration_type:
2276 return dwarf::PubIndexEntryDescriptor(
2277 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2278 ? dwarf::GIEL_STATIC
2279 : dwarf::GIEL_EXTERNAL);
2280 case dwarf::DW_TAG_typedef:
2281 case dwarf::DW_TAG_base_type:
2282 case dwarf::DW_TAG_subrange_type:
2283 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2284 case dwarf::DW_TAG_namespace:
2285 return dwarf::GIEK_TYPE;
2286 case dwarf::DW_TAG_subprogram:
2287 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2288 case dwarf::DW_TAG_constant:
2289 case dwarf::DW_TAG_variable:
2290 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2291 case dwarf::DW_TAG_enumerator:
2292 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2293 dwarf::GIEL_STATIC);
2295 return dwarf::GIEK_NONE;
2299 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2301 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2302 const MCSection *PSec =
2303 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2304 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2306 for (const auto &NU : CUMap) {
2307 DwarfCompileUnit *TheU = NU.second;
2308 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2310 unsigned ID = TheU->getUniqueID();
2312 // Start the dwarf pubnames section.
2313 Asm->OutStreamer.SwitchSection(PSec);
2315 // Emit a label so we can reference the beginning of this pubname section.
2317 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2320 Asm->OutStreamer.AddComment("Length of Public Names Info");
2321 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2322 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2323 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2325 Asm->OutStreamer.EmitLabel(BeginLabel);
2327 Asm->OutStreamer.AddComment("DWARF Version");
2328 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2330 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2331 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2333 Asm->OutStreamer.AddComment("Compilation Unit Length");
2334 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2336 // Emit the pubnames for this compilation unit.
2337 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2338 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2341 const char *Name = GI->getKeyData();
2342 const DIE *Entity = GI->second;
2344 Asm->OutStreamer.AddComment("DIE offset");
2345 Asm->EmitInt32(Entity->getOffset());
2348 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2349 Asm->OutStreamer.AddComment(
2350 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2351 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2352 Asm->EmitInt8(Desc.toBits());
2355 Asm->OutStreamer.AddComment("External Name");
2356 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2359 Asm->OutStreamer.AddComment("End Mark");
2361 Asm->OutStreamer.EmitLabel(EndLabel);
2365 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2366 const MCSection *PSec =
2367 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2368 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2370 for (const auto &NU : CUMap) {
2371 DwarfCompileUnit *TheU = NU.second;
2372 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2374 unsigned ID = TheU->getUniqueID();
2376 // Start the dwarf pubtypes section.
2377 Asm->OutStreamer.SwitchSection(PSec);
2379 // Emit a label so we can reference the beginning of this pubtype section.
2381 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2384 Asm->OutStreamer.AddComment("Length of Public Types Info");
2385 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2386 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2387 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2389 Asm->OutStreamer.EmitLabel(BeginLabel);
2391 Asm->OutStreamer.AddComment("DWARF Version");
2392 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2394 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2395 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2397 Asm->OutStreamer.AddComment("Compilation Unit Length");
2398 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2400 // Emit the pubtypes.
2401 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2402 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2405 const char *Name = GI->getKeyData();
2406 const DIE *Entity = GI->second;
2408 Asm->OutStreamer.AddComment("DIE offset");
2409 Asm->EmitInt32(Entity->getOffset());
2412 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2413 Asm->OutStreamer.AddComment(
2414 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2415 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2416 Asm->EmitInt8(Desc.toBits());
2419 Asm->OutStreamer.AddComment("External Name");
2421 // Emit the name with a terminating null byte.
2422 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2425 Asm->OutStreamer.AddComment("End Mark");
2427 Asm->OutStreamer.EmitLabel(EndLabel);
2431 // Emit strings into a string section.
2432 void DwarfFile::emitStrings(const MCSection *StrSection,
2433 const MCSection *OffsetSection = NULL,
2434 const MCSymbol *StrSecSym = NULL) {
2436 if (StringPool.empty())
2439 // Start the dwarf str section.
2440 Asm->OutStreamer.SwitchSection(StrSection);
2442 // Get all of the string pool entries and put them in an array by their ID so
2443 // we can sort them.
2445 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2448 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2449 I = StringPool.begin(),
2450 E = StringPool.end();
2452 Entries.push_back(std::make_pair(I->second.second, &*I));
2454 array_pod_sort(Entries.begin(), Entries.end());
2456 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2457 // Emit a label for reference from debug information entries.
2458 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2460 // Emit the string itself with a terminating null byte.
2461 Asm->OutStreamer.EmitBytes(
2462 StringRef(Entries[i].second->getKeyData(),
2463 Entries[i].second->getKeyLength() + 1));
2466 // If we've got an offset section go ahead and emit that now as well.
2467 if (OffsetSection) {
2468 Asm->OutStreamer.SwitchSection(OffsetSection);
2469 unsigned offset = 0;
2470 unsigned size = 4; // FIXME: DWARF64 is 8.
2471 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2472 Asm->OutStreamer.EmitIntValue(offset, size);
2473 offset += Entries[i].second->getKeyLength() + 1;
2478 // Emit addresses into the section given.
2479 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2481 if (AddressPool.empty())
2484 // Start the dwarf addr section.
2485 Asm->OutStreamer.SwitchSection(AddrSection);
2487 // Order the address pool entries by ID
2488 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2490 for (AddrPool::iterator I = AddressPool.begin(), E = AddressPool.end();
2492 Entries[I->second.Number] =
2494 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I->first)
2495 : MCSymbolRefExpr::Create(I->first, Asm->OutContext);
2497 for (unsigned i = 0, e = Entries.size(); i != e; ++i)
2498 Asm->OutStreamer.EmitValue(Entries[i],
2499 Asm->getDataLayout().getPointerSize());
2502 // Emit visible names into a debug str section.
2503 void DwarfDebug::emitDebugStr() {
2504 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2505 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2508 // Emit locations into the debug loc section.
2509 void DwarfDebug::emitDebugLoc() {
2510 if (DotDebugLocEntries.empty())
2513 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2514 I = DotDebugLocEntries.begin(),
2515 E = DotDebugLocEntries.end();
2517 DotDebugLocEntry &Entry = *I;
2518 if (I + 1 != DotDebugLocEntries.end())
2522 // Start the dwarf loc section.
2523 Asm->OutStreamer.SwitchSection(
2524 Asm->getObjFileLowering().getDwarfLocSection());
2525 unsigned char Size = Asm->getDataLayout().getPointerSize();
2526 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2528 for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2529 I = DotDebugLocEntries.begin(),
2530 E = DotDebugLocEntries.end();
2531 I != E; ++I, ++index) {
2532 const DotDebugLocEntry &Entry = *I;
2533 if (Entry.isMerged())
2535 if (Entry.isEmpty()) {
2536 Asm->OutStreamer.EmitIntValue(0, Size);
2537 Asm->OutStreamer.EmitIntValue(0, Size);
2538 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2540 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2541 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2542 DIVariable DV(Entry.getVariable());
2543 Asm->OutStreamer.AddComment("Loc expr size");
2544 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2545 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2546 Asm->EmitLabelDifference(end, begin, 2);
2547 Asm->OutStreamer.EmitLabel(begin);
2548 if (Entry.isInt()) {
2549 DIBasicType BTy(DV.getType());
2550 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2551 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2552 Asm->OutStreamer.AddComment("DW_OP_consts");
2553 Asm->EmitInt8(dwarf::DW_OP_consts);
2554 Asm->EmitSLEB128(Entry.getInt());
2556 Asm->OutStreamer.AddComment("DW_OP_constu");
2557 Asm->EmitInt8(dwarf::DW_OP_constu);
2558 Asm->EmitULEB128(Entry.getInt());
2560 } else if (Entry.isLocation()) {
2561 MachineLocation Loc = Entry.getLoc();
2562 if (!DV.hasComplexAddress())
2564 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2566 // Complex address entry.
2567 unsigned N = DV.getNumAddrElements();
2569 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2570 if (Loc.getOffset()) {
2572 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2573 Asm->OutStreamer.AddComment("DW_OP_deref");
2574 Asm->EmitInt8(dwarf::DW_OP_deref);
2575 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2576 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2577 Asm->EmitSLEB128(DV.getAddrElement(1));
2579 // If first address element is OpPlus then emit
2580 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2581 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2582 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2586 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2589 // Emit remaining complex address elements.
2590 for (; i < N; ++i) {
2591 uint64_t Element = DV.getAddrElement(i);
2592 if (Element == DIBuilder::OpPlus) {
2593 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2594 Asm->EmitULEB128(DV.getAddrElement(++i));
2595 } else if (Element == DIBuilder::OpDeref) {
2597 Asm->EmitInt8(dwarf::DW_OP_deref);
2599 llvm_unreachable("unknown Opcode found in complex address");
2603 // else ... ignore constant fp. There is not any good way to
2604 // to represent them here in dwarf.
2605 Asm->OutStreamer.EmitLabel(end);
2610 struct SymbolCUSorter {
2611 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2612 const MCStreamer &Streamer;
2614 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2615 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2616 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2618 // Symbols with no order assigned should be placed at the end.
2619 // (e.g. section end labels)
2621 IA = (unsigned)(-1);
2623 IB = (unsigned)(-1);
2628 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2629 return (A->getUniqueID() < B->getUniqueID());
2633 const MCSymbol *Start, *End;
2636 // Emit a debug aranges section, containing a CU lookup for any
2637 // address we can tie back to a CU.
2638 void DwarfDebug::emitDebugARanges() {
2639 // Start the dwarf aranges section.
2640 Asm->OutStreamer.SwitchSection(
2641 Asm->getObjFileLowering().getDwarfARangesSection());
2643 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2647 // Build a list of sections used.
2648 std::vector<const MCSection *> Sections;
2649 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2651 const MCSection *Section = it->first;
2652 Sections.push_back(Section);
2655 // Sort the sections into order.
2656 // This is only done to ensure consistent output order across different runs.
2657 std::sort(Sections.begin(), Sections.end(), SectionSort);
2659 // Build a set of address spans, sorted by CU.
2660 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2661 const MCSection *Section = Sections[SecIdx];
2662 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2663 if (List.size() < 2)
2666 // Sort the symbols by offset within the section.
2667 SymbolCUSorter sorter(Asm->OutStreamer);
2668 std::sort(List.begin(), List.end(), sorter);
2670 // If we have no section (e.g. common), just write out
2671 // individual spans for each symbol.
2672 if (Section == NULL) {
2673 for (size_t n = 0; n < List.size(); n++) {
2674 const SymbolCU &Cur = List[n];
2677 Span.Start = Cur.Sym;
2680 Spans[Cur.CU].push_back(Span);
2683 // Build spans between each label.
2684 const MCSymbol *StartSym = List[0].Sym;
2685 for (size_t n = 1; n < List.size(); n++) {
2686 const SymbolCU &Prev = List[n - 1];
2687 const SymbolCU &Cur = List[n];
2689 // Try and build the longest span we can within the same CU.
2690 if (Cur.CU != Prev.CU) {
2692 Span.Start = StartSym;
2694 Spans[Prev.CU].push_back(Span);
2701 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2703 // Build a list of CUs used.
2704 std::vector<DwarfCompileUnit *> CUs;
2705 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2706 DwarfCompileUnit *CU = it->first;
2710 // Sort the CU list (again, to ensure consistent output order).
2711 std::sort(CUs.begin(), CUs.end(), CUSort);
2713 // Emit an arange table for each CU we used.
2714 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2715 DwarfCompileUnit *CU = CUs[CUIdx];
2716 std::vector<ArangeSpan> &List = Spans[CU];
2718 // Emit size of content not including length itself.
2719 unsigned ContentSize =
2720 sizeof(int16_t) + // DWARF ARange version number
2721 sizeof(int32_t) + // Offset of CU in the .debug_info section
2722 sizeof(int8_t) + // Pointer Size (in bytes)
2723 sizeof(int8_t); // Segment Size (in bytes)
2725 unsigned TupleSize = PtrSize * 2;
2727 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2729 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2731 ContentSize += Padding;
2732 ContentSize += (List.size() + 1) * TupleSize;
2734 // For each compile unit, write the list of spans it covers.
2735 Asm->OutStreamer.AddComment("Length of ARange Set");
2736 Asm->EmitInt32(ContentSize);
2737 Asm->OutStreamer.AddComment("DWARF Arange version number");
2738 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2739 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2740 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2741 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2742 Asm->EmitInt8(PtrSize);
2743 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2746 Asm->OutStreamer.EmitFill(Padding, 0xff);
2748 for (unsigned n = 0; n < List.size(); n++) {
2749 const ArangeSpan &Span = List[n];
2750 Asm->EmitLabelReference(Span.Start, PtrSize);
2752 // Calculate the size as being from the span start to it's end.
2754 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2756 // For symbols without an end marker (e.g. common), we
2757 // write a single arange entry containing just that one symbol.
2758 uint64_t Size = SymSize[Span.Start];
2762 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2766 Asm->OutStreamer.AddComment("ARange terminator");
2767 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2768 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2772 // Emit visible names into a debug ranges section.
2773 void DwarfDebug::emitDebugRanges() {
2774 // Start the dwarf ranges section.
2775 Asm->OutStreamer.SwitchSection(
2776 Asm->getObjFileLowering().getDwarfRangesSection());
2778 // Size for our labels.
2779 unsigned char Size = Asm->getDataLayout().getPointerSize();
2781 // Grab the specific ranges for the compile units in the module.
2782 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2786 DwarfCompileUnit *TheCU = I->second;
2788 // Emit a symbol so we can find the beginning of our ranges.
2789 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2791 // Iterate over the misc ranges for the compile units in the module.
2792 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2793 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2794 E = RangeLists.end();
2796 const RangeSpanList &List = *I;
2798 // Emit our symbol so we can find the beginning of the range.
2799 Asm->OutStreamer.EmitLabel(List.getSym());
2801 for (SmallVectorImpl<RangeSpan>::const_iterator
2802 RI = List.getRanges().begin(),
2803 RE = List.getRanges().end();
2805 const RangeSpan &Range = *RI;
2806 const MCSymbol *Begin = Range.getStart();
2807 const MCSymbol *End = Range.getEnd();
2808 assert(Begin && "Range without a begin symbol?");
2809 assert(End && "Range without an end symbol?");
2810 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2811 Asm->OutStreamer.EmitSymbolValue(End, Size);
2814 // And terminate the list with two 0 values.
2815 Asm->OutStreamer.EmitIntValue(0, Size);
2816 Asm->OutStreamer.EmitIntValue(0, Size);
2819 // Now emit a range for the CU itself.
2820 if (useCURanges() && TheCU->getRanges().size()) {
2821 Asm->OutStreamer.EmitLabel(
2822 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2823 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2824 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2825 RangeSpan Range = Ranges[i];
2826 const MCSymbol *Begin = Range.getStart();
2827 const MCSymbol *End = Range.getEnd();
2828 assert(Begin && "Range without a begin symbol?");
2829 assert(End && "Range without an end symbol?");
2830 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2831 Asm->OutStreamer.EmitSymbolValue(End, Size);
2833 // And terminate the list with two 0 values.
2834 Asm->OutStreamer.EmitIntValue(0, Size);
2835 Asm->OutStreamer.EmitIntValue(0, Size);
2840 // DWARF5 Experimental Separate Dwarf emitters.
2842 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2844 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2845 U->getCUNode().getSplitDebugFilename());
2847 // Relocate to the beginning of the addr_base section, else 0 for the
2848 // beginning of the one for this compile unit.
2849 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2850 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2852 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2854 if (!CompilationDir.empty())
2855 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2857 addGnuPubAttributes(NewU, Die);
2859 SkeletonHolder.addUnit(NewU);
2862 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2863 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2864 // DW_AT_ranges_base, DW_AT_addr_base.
2865 // TODO: Implement DW_AT_ranges_base.
2866 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2868 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2869 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2870 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2871 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2872 DwarfInfoSectionSym);
2874 NewCU->initStmtList(DwarfLineSectionSym);
2876 initSkeletonUnit(CU, Die, NewCU);
2881 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2883 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2884 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2885 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2887 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2888 DwarfTypeUnit *NewTU =
2889 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2890 NewTU->setTypeSignature(TU->getTypeSignature());
2891 NewTU->setType(NULL);
2893 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2894 CU.applyStmtList(*Die);
2896 initSkeletonUnit(TU, Die, NewTU);
2900 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2901 // compile units that would normally be in debug_info.
2902 void DwarfDebug::emitDebugInfoDWO() {
2903 assert(useSplitDwarf() && "No split dwarf debug info?");
2904 InfoHolder.emitUnits(this,
2905 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2906 DwarfAbbrevDWOSectionSym);
2909 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2910 // abbreviations for the .debug_info.dwo section.
2911 void DwarfDebug::emitDebugAbbrevDWO() {
2912 assert(useSplitDwarf() && "No split dwarf?");
2913 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2916 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2917 // string section and is identical in format to traditional .debug_str
2919 void DwarfDebug::emitDebugStrDWO() {
2920 assert(useSplitDwarf() && "No split dwarf?");
2921 const MCSection *OffSec =
2922 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2923 const MCSymbol *StrSym = DwarfStrSectionSym;
2924 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2928 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2929 StringRef Identifier, DIE *RefDie,
2930 DICompositeType CTy) {
2931 // Flag the type unit reference as a declaration so that if it contains
2932 // members (implicit special members, static data member definitions, member
2933 // declarations for definitions in this CU, etc) consumers don't get confused
2934 // and think this is a full definition.
2935 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2937 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2939 CU.addDIETypeSignature(RefDie, *TU);
2943 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2944 DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2945 UnitDie, CU, Asm, this, &InfoHolder);
2947 InfoHolder.addUnit(NewTU);
2949 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2953 Hash.update(Identifier);
2954 // ... take the least significant 8 bytes and return those. Our MD5
2955 // implementation always returns its results in little endian, swap bytes
2957 MD5::MD5Result Result;
2959 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2960 NewTU->setTypeSignature(Signature);
2961 if (useSplitDwarf())
2962 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2964 CU.applyStmtList(*UnitDie);
2966 NewTU->setType(NewTU->createTypeDIE(CTy));
2970 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2971 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2973 CU.addDIETypeSignature(RefDie, *NewTU);
2976 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2977 MCSymbol *Begin, MCSymbol *End) {
2978 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2979 if (DwarfVersion < 4 || Triple(Asm->getTargetTriple()).isOSDarwin())
2980 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2982 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);