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/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
66 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
67 cl::desc("Add the CU hash as the dwo_id."),
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72 cl::desc("Generate GNU-style pubnames and pubtypes"),
83 static cl::opt<DefaultOnOff>
84 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
85 cl::desc("Output prototype dwarf accelerator tables."),
86 cl::values(clEnumVal(Default, "Default for platform"),
87 clEnumVal(Enable, "Enabled"),
88 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 static cl::opt<DefaultOnOff>
92 SplitDwarf("split-dwarf", cl::Hidden,
93 cl::desc("Output prototype dwarf split debug info."),
94 cl::values(clEnumVal(Default, "Default for platform"),
95 clEnumVal(Enable, "Enabled"),
96 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 static cl::opt<DefaultOnOff>
100 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
101 cl::desc("Generate DWARF pubnames and pubtypes sections"),
102 cl::values(clEnumVal(Default, "Default for platform"),
103 clEnumVal(Enable, "Enabled"),
104 clEnumVal(Disable, "Disabled"), clEnumValEnd),
107 static cl::opt<unsigned>
108 DwarfVersionNumber("dwarf-version", cl::Hidden,
109 cl::desc("Generate DWARF for dwarf version."),
112 static const char *const DWARFGroupName = "DWARF Emission";
113 static const char *const DbgTimerName = "DWARF Debug Writer";
115 //===----------------------------------------------------------------------===//
117 // Configuration values for initial hash set sizes (log2).
119 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
123 /// resolve - Look in the DwarfDebug map for the MDNode that
124 /// corresponds to the reference.
125 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
126 return DD->resolve(Ref);
129 DIType DbgVariable::getType() const {
130 DIType Ty = Var.getType();
131 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
132 // addresses instead.
133 if (Var.isBlockByrefVariable()) {
134 /* Byref variables, in Blocks, are declared by the programmer as
135 "SomeType VarName;", but the compiler creates a
136 __Block_byref_x_VarName struct, and gives the variable VarName
137 either the struct, or a pointer to the struct, as its type. This
138 is necessary for various behind-the-scenes things the compiler
139 needs to do with by-reference variables in blocks.
141 However, as far as the original *programmer* is concerned, the
142 variable should still have type 'SomeType', as originally declared.
144 The following function dives into the __Block_byref_x_VarName
145 struct to find the original type of the variable. This will be
146 passed back to the code generating the type for the Debug
147 Information Entry for the variable 'VarName'. 'VarName' will then
148 have the original type 'SomeType' in its debug information.
150 The original type 'SomeType' will be the type of the field named
151 'VarName' inside the __Block_byref_x_VarName struct.
153 NOTE: In order for this to not completely fail on the debugger
154 side, the Debug Information Entry for the variable VarName needs to
155 have a DW_AT_location that tells the debugger how to unwind through
156 the pointers and __Block_byref_x_VarName struct to find the actual
157 value of the variable. The function addBlockByrefType does this. */
159 uint16_t tag = Ty.getTag();
161 if (tag == dwarf::DW_TAG_pointer_type)
162 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
164 DIArray Elements = DICompositeType(subType).getTypeArray();
165 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
166 DIDerivedType DT(Elements.getElement(i));
167 if (getName() == DT.getName())
168 return (resolve(DT.getTypeDerivedFrom()));
174 } // end llvm namespace
176 /// Return Dwarf Version by checking module flags.
177 static unsigned getDwarfVersionFromModule(const Module *M) {
178 Value *Val = M->getModuleFlag("Dwarf Version");
180 return dwarf::DWARF_VERSION;
181 return cast<ConstantInt>(Val)->getZExtValue();
184 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
185 : Asm(A), MMI(Asm->MMI), FirstCU(0),
186 AbbreviationsSet(InitAbbreviationsSetSize),
187 SourceIdMap(DIEValueAllocator), PrevLabel(NULL), GlobalCUIndexCount(0),
188 GlobalRangeCount(0), InfoHolder(A, &AbbreviationsSet, Abbreviations,
189 "info_string", DIEValueAllocator),
190 SkeletonAbbrevSet(InitAbbreviationsSetSize),
191 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
194 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
195 DwarfStrSectionSym = TextSectionSym = 0;
196 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
197 DwarfAddrSectionSym = 0;
198 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
199 FunctionBeginSym = FunctionEndSym = 0;
201 // Turn on accelerator tables for Darwin by default, pubnames by
202 // default for non-Darwin, and handle split dwarf.
203 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
205 if (DwarfAccelTables == Default)
206 HasDwarfAccelTables = IsDarwin;
208 HasDwarfAccelTables = DwarfAccelTables == Enable;
210 if (SplitDwarf == Default)
211 HasSplitDwarf = false;
213 HasSplitDwarf = SplitDwarf == Enable;
215 if (DwarfPubSections == Default)
216 HasDwarfPubSections = !IsDarwin;
218 HasDwarfPubSections = DwarfPubSections == Enable;
220 DwarfVersion = DwarfVersionNumber
222 : getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
230 // Switch to the specified MCSection and emit an assembler
231 // temporary label to it if SymbolStem is specified.
232 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
233 const char *SymbolStem = 0) {
234 Asm->OutStreamer.SwitchSection(Section);
238 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
239 Asm->OutStreamer.EmitLabel(TmpSym);
243 DwarfUnits::~DwarfUnits() {
244 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
249 MCSymbol *DwarfUnits::getStringPoolSym() {
250 return Asm->GetTempSymbol(StringPref);
253 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
254 std::pair<MCSymbol *, unsigned> &Entry =
255 StringPool.GetOrCreateValue(Str).getValue();
259 Entry.second = NextStringPoolNumber++;
260 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
263 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
264 std::pair<MCSymbol *, unsigned> &Entry =
265 StringPool.GetOrCreateValue(Str).getValue();
269 Entry.second = NextStringPoolNumber++;
270 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
274 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
275 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
278 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
279 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
280 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
282 ++NextAddrPoolNumber;
283 return P.first->second;
286 // Define a unique number for the abbreviation.
288 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
289 // Check the set for priors.
290 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
292 // If it's newly added.
293 if (InSet == &Abbrev) {
294 // Add to abbreviation list.
295 Abbreviations.push_back(&Abbrev);
297 // Assign the vector position + 1 as its number.
298 Abbrev.setNumber(Abbreviations.size());
300 // Assign existing abbreviation number.
301 Abbrev.setNumber(InSet->getNumber());
305 static bool isObjCClass(StringRef Name) {
306 return Name.startswith("+") || Name.startswith("-");
309 static bool hasObjCCategory(StringRef Name) {
310 if (!isObjCClass(Name))
313 return Name.find(") ") != StringRef::npos;
316 static void getObjCClassCategory(StringRef In, StringRef &Class,
317 StringRef &Category) {
318 if (!hasObjCCategory(In)) {
319 Class = In.slice(In.find('[') + 1, In.find(' '));
324 Class = In.slice(In.find('[') + 1, In.find('('));
325 Category = In.slice(In.find('[') + 1, In.find(' '));
329 static StringRef getObjCMethodName(StringRef In) {
330 return In.slice(In.find(' ') + 1, In.find(']'));
333 // Helper for sorting sections into a stable output order.
334 static bool SectionSort(const MCSection *A, const MCSection *B) {
335 std::string LA = (A ? A->getLabelBeginName() : "");
336 std::string LB = (B ? B->getLabelBeginName() : "");
340 // Add the various names to the Dwarf accelerator table names.
341 // TODO: Determine whether or not we should add names for programs
342 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
343 // is only slightly different than the lookup of non-standard ObjC names.
344 static void addSubprogramNames(Unit *TheU, DISubprogram SP, DIE *Die) {
345 if (!SP.isDefinition())
347 TheU->addAccelName(SP.getName(), Die);
349 // If the linkage name is different than the name, go ahead and output
350 // that as well into the name table.
351 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
352 TheU->addAccelName(SP.getLinkageName(), Die);
354 // If this is an Objective-C selector name add it to the ObjC accelerator
356 if (isObjCClass(SP.getName())) {
357 StringRef Class, Category;
358 getObjCClassCategory(SP.getName(), Class, Category);
359 TheU->addAccelObjC(Class, Die);
361 TheU->addAccelObjC(Category, Die);
362 // Also add the base method name to the name table.
363 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
367 /// isSubprogramContext - Return true if Context is either a subprogram
368 /// or another context nested inside a subprogram.
369 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
372 DIDescriptor D(Context);
373 if (D.isSubprogram())
376 return isSubprogramContext(resolve(DIType(Context).getContext()));
380 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
381 // and DW_AT_high_pc attributes. If there are global variables in this
382 // scope then create and insert DIEs for these variables.
383 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
384 DIE *SPDie = SPCU->getDIE(SP);
386 assert(SPDie && "Unable to find subprogram DIE!");
388 // If we're updating an abstract DIE, then we will be adding the children and
389 // object pointer later on. But what we don't want to do is process the
390 // concrete DIE twice.
391 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
392 // Pick up abstract subprogram DIE.
394 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
395 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
397 DISubprogram SPDecl = SP.getFunctionDeclaration();
398 if (!SPDecl.isSubprogram()) {
399 // There is not any need to generate specification DIE for a function
400 // defined at compile unit level. If a function is defined inside another
401 // function then gdb prefers the definition at top level and but does not
402 // expect specification DIE in parent function. So avoid creating
403 // specification DIE for a function defined inside a function.
404 DIScope SPContext = resolve(SP.getContext());
405 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
406 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
407 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
410 DICompositeType SPTy = SP.getType();
411 DIArray Args = SPTy.getTypeArray();
412 uint16_t SPTag = SPTy.getTag();
413 if (SPTag == dwarf::DW_TAG_subroutine_type)
414 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
416 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
417 DIType ATy(Args.getElement(i));
418 SPCU->addType(Arg, ATy);
419 if (ATy.isArtificial())
420 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
421 if (ATy.isObjectPointer())
422 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
424 DIE *SPDeclDie = SPDie;
425 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
426 *SPCU->getUnitDie());
427 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
432 MCSymbol *FuncBegin =
433 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
434 MCSymbol *FuncEnd = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
435 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FuncBegin);
436 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FuncEnd);
438 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
439 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
440 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
442 // Add name to the name table, we do this here because we're guaranteed
443 // to have concrete versions of our DW_TAG_subprogram nodes.
444 addSubprogramNames(SPCU, SP, SPDie);
449 /// Check whether we should create a DIE for the given Scope, return true
450 /// if we don't create a DIE (the corresponding DIE is null).
451 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
452 if (Scope->isAbstractScope())
455 // We don't create a DIE if there is no Range.
456 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
460 if (Ranges.size() > 1)
463 // We don't create a DIE if we have a single Range and the end label
465 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
466 MCSymbol *End = getLabelAfterInsn(RI->second);
470 void DwarfDebug::addScopeRangeList(CompileUnit *TheCU, DIE *ScopeDIE,
471 const SmallVectorImpl<InsnRange> &Range) {
472 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
473 // emitting it appropriately.
474 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
475 Asm->GetTempSymbol("debug_ranges", GlobalRangeCount));
476 RangeSpanList *List = new RangeSpanList(GlobalRangeCount++);
477 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
480 RangeSpan Span(getLabelBeforeInsn(RI->first),
481 getLabelAfterInsn(RI->second));
482 List->addRange(Span);
485 // Add the range list to the set of ranges to be emitted.
486 TheCU->addRangeList(List);
489 // Construct new DW_TAG_lexical_block for this scope and attach
490 // DW_AT_low_pc/DW_AT_high_pc labels.
491 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
492 LexicalScope *Scope) {
493 if (isLexicalScopeDIENull(Scope))
496 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
497 if (Scope->isAbstractScope())
500 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
502 // If we have multiple ranges, emit them into the range section.
503 if (ScopeRanges.size() > 1) {
504 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
508 // Construct the address range for this DIE.
509 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
510 MCSymbol *Start = getLabelBeforeInsn(RI->first);
511 MCSymbol *End = getLabelAfterInsn(RI->second);
512 assert(End && "End label should not be null!");
514 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
515 assert(End->isDefined() && "Invalid end label for an inlined scope!");
517 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
518 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
523 // This scope represents inlined body of a function. Construct DIE to
524 // represent this concrete inlined copy of the function.
525 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
526 LexicalScope *Scope) {
527 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
528 assert(ScopeRanges.empty() == false &&
529 "LexicalScope does not have instruction markers!");
531 if (!Scope->getScopeNode())
533 DIScope DS(Scope->getScopeNode());
534 DISubprogram InlinedSP = getDISubprogram(DS);
535 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
537 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
541 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
542 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
544 // If we have multiple ranges, emit them into the range section.
545 if (ScopeRanges.size() > 1)
546 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
548 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
549 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
550 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
552 if (StartLabel == 0 || EndLabel == 0)
553 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
555 assert(StartLabel->isDefined() &&
556 "Invalid starting label for an inlined scope!");
557 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
559 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
560 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
563 InlinedSubprogramDIEs.insert(OriginDIE);
565 // Add the call site information to the DIE.
566 DILocation DL(Scope->getInlinedAt());
567 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
568 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
569 TheCU->getUniqueID()));
570 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
572 // Add name to the name table, we do this here because we're guaranteed
573 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
574 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
579 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
580 SmallVectorImpl<DIE *> &Children) {
581 DIE *ObjectPointer = NULL;
583 // Collect arguments for current function.
584 if (LScopes.isCurrentFunctionScope(Scope))
585 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
586 if (DbgVariable *ArgDV = CurrentFnArguments[i])
588 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
589 Children.push_back(Arg);
590 if (ArgDV->isObjectPointer())
594 // Collect lexical scope children first.
595 const SmallVectorImpl<DbgVariable *> &Variables =
596 ScopeVariables.lookup(Scope);
597 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
598 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
599 Scope->isAbstractScope())) {
600 Children.push_back(Variable);
601 if (Variables[i]->isObjectPointer())
602 ObjectPointer = Variable;
604 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
605 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
606 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
607 Children.push_back(Nested);
608 return ObjectPointer;
611 // Construct a DIE for this scope.
612 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
613 if (!Scope || !Scope->getScopeNode())
616 DIScope DS(Scope->getScopeNode());
618 SmallVector<DIE *, 8> Children;
619 DIE *ObjectPointer = NULL;
620 bool ChildrenCreated = false;
622 // We try to create the scope DIE first, then the children DIEs. This will
623 // avoid creating un-used children then removing them later when we find out
624 // the scope DIE is null.
625 DIE *ScopeDIE = NULL;
626 if (Scope->getInlinedAt())
627 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
628 else if (DS.isSubprogram()) {
629 ProcessedSPNodes.insert(DS);
630 if (Scope->isAbstractScope()) {
631 ScopeDIE = TheCU->getDIE(DS);
632 // Note down abstract DIE.
634 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
636 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
638 // Early exit when we know the scope DIE is going to be null.
639 if (isLexicalScopeDIENull(Scope))
642 // We create children here when we know the scope DIE is not going to be
643 // null and the children will be added to the scope DIE.
644 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
645 ChildrenCreated = true;
647 // There is no need to emit empty lexical block DIE.
648 std::pair<ImportedEntityMap::const_iterator,
649 ImportedEntityMap::const_iterator> Range =
651 ScopesWithImportedEntities.begin(),
652 ScopesWithImportedEntities.end(),
653 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
655 if (Children.empty() && Range.first == Range.second)
657 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
658 assert(ScopeDIE && "Scope DIE should not be null.");
659 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
661 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
665 assert(Children.empty() &&
666 "We create children only when the scope DIE is not null.");
669 if (!ChildrenCreated)
670 // We create children when the scope DIE is not null.
671 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
674 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
677 ScopeDIE->addChild(*I);
679 if (DS.isSubprogram() && ObjectPointer != NULL)
680 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
685 // Look up the source id with the given directory and source file names.
686 // If none currently exists, create a new id and insert it in the
687 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
689 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
691 // If we use .loc in assembly, we can't separate .file entries according to
692 // compile units. Thus all files will belong to the default compile unit.
694 // FIXME: add a better feature test than hasRawTextSupport. Even better,
695 // extend .file to support this.
696 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
699 // If FE did not provide a file name, then assume stdin.
700 if (FileName.empty())
701 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
703 // TODO: this might not belong here. See if we can factor this better.
704 if (DirName == CompilationDir)
707 // FileIDCUMap stores the current ID for the given compile unit.
708 unsigned SrcId = FileIDCUMap[CUID] + 1;
710 // We look up the CUID/file/dir by concatenating them with a zero byte.
711 SmallString<128> NamePair;
712 NamePair += utostr(CUID);
715 NamePair += '\0'; // Zero bytes are not allowed in paths.
716 NamePair += FileName;
718 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
719 if (Ent.getValue() != SrcId)
720 return Ent.getValue();
722 FileIDCUMap[CUID] = SrcId;
723 // Print out a .file directive to specify files for .loc directives.
724 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
729 // Create new CompileUnit for the given metadata node with tag
730 // DW_TAG_compile_unit.
731 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
732 StringRef FN = DIUnit.getFilename();
733 CompilationDir = DIUnit.getDirectory();
735 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
736 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
739 FileIDCUMap[NewCU->getUniqueID()] = 0;
740 // Call this to emit a .file directive if it wasn't emitted for the source
741 // file this CU comes from yet.
742 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
744 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
745 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
746 DIUnit.getLanguage());
747 NewCU->addString(Die, dwarf::DW_AT_name, FN);
749 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
750 // into an entity. We're using 0 (or a NULL label) for this. For
751 // split dwarf it's in the skeleton CU so omit it here.
752 if (!useSplitDwarf())
753 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
755 // Define start line table label for each Compile Unit.
756 MCSymbol *LineTableStartSym =
757 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
758 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
759 NewCU->getUniqueID());
761 // Use a single line table if we are using .loc and generating assembly.
763 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
764 (NewCU->getUniqueID() == 0);
766 if (!useSplitDwarf()) {
767 // DW_AT_stmt_list is a offset of line number information for this
768 // compile unit in debug_line section. For split dwarf this is
769 // left in the skeleton CU and so not included.
770 // The line table entries are not always emitted in assembly, so it
771 // is not okay to use line_table_start here.
772 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
773 NewCU->addSectionLabel(
774 Die, dwarf::DW_AT_stmt_list,
775 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
776 : LineTableStartSym);
777 else if (UseTheFirstCU)
778 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
780 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
781 LineTableStartSym, DwarfLineSectionSym);
783 // If we're using split dwarf the compilation dir is going to be in the
784 // skeleton CU and so we don't need to duplicate it here.
785 if (!CompilationDir.empty())
786 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
788 // Flags to let the linker know we have emitted new style pubnames. Only
789 // emit it here if we don't have a skeleton CU for split dwarf.
790 if (GenerateGnuPubSections) {
791 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
792 NewCU->addSectionLabel(
793 Die, dwarf::DW_AT_GNU_pubnames,
794 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
796 NewCU->addSectionDelta(
797 Die, dwarf::DW_AT_GNU_pubnames,
798 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
799 DwarfGnuPubNamesSectionSym);
801 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
802 NewCU->addSectionLabel(
803 Die, dwarf::DW_AT_GNU_pubtypes,
804 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
806 NewCU->addSectionDelta(
807 Die, dwarf::DW_AT_GNU_pubtypes,
808 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
809 DwarfGnuPubTypesSectionSym);
813 if (DIUnit.isOptimized())
814 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
816 StringRef Flags = DIUnit.getFlags();
818 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
820 if (unsigned RVer = DIUnit.getRunTimeVersion())
821 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
822 dwarf::DW_FORM_data1, RVer);
827 InfoHolder.addUnit(NewCU);
829 CUMap.insert(std::make_pair(DIUnit, NewCU));
830 CUDieMap.insert(std::make_pair(Die, NewCU));
834 // Construct subprogram DIE.
835 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
836 // FIXME: We should only call this routine once, however, during LTO if a
837 // program is defined in multiple CUs we could end up calling it out of
838 // beginModule as we walk the CUs.
840 CompileUnit *&CURef = SPMap[N];
846 if (!SP.isDefinition())
847 // This is a method declaration which will be handled while constructing
851 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
853 // Expose as a global name.
854 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
857 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
859 DIImportedEntity Module(N);
860 if (!Module.Verify())
862 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
863 constructImportedEntityDIE(TheCU, Module, D);
866 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
868 DIImportedEntity Module(N);
869 if (!Module.Verify())
871 return constructImportedEntityDIE(TheCU, Module, Context);
874 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
875 const DIImportedEntity &Module,
877 assert(Module.Verify() &&
878 "Use one of the MDNode * overloads to handle invalid metadata");
879 assert(Context && "Should always have a context for an imported_module");
880 DIE *IMDie = new DIE(Module.getTag());
881 TheCU->insertDIE(Module, IMDie);
883 DIDescriptor Entity = Module.getEntity();
884 if (Entity.isNameSpace())
885 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
886 else if (Entity.isSubprogram())
887 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
888 else if (Entity.isType())
889 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
891 EntityDie = TheCU->getDIE(Entity);
892 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
893 Module.getContext().getDirectory(),
894 TheCU->getUniqueID());
895 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
896 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
897 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
898 StringRef Name = Module.getName();
900 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
901 Context->addChild(IMDie);
904 // Emit all Dwarf sections that should come prior to the content. Create
905 // global DIEs and emit initial debug info sections. This is invoked by
906 // the target AsmPrinter.
907 void DwarfDebug::beginModule() {
908 if (DisableDebugInfoPrinting)
911 const Module *M = MMI->getModule();
913 // If module has named metadata anchors then use them, otherwise scan the
914 // module using debug info finder to collect debug info.
915 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
918 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
920 // Emit initial sections so we can reference labels later.
923 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
924 DICompileUnit CUNode(CU_Nodes->getOperand(i));
925 CompileUnit *CU = constructCompileUnit(CUNode);
926 DIArray ImportedEntities = CUNode.getImportedEntities();
927 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
928 ScopesWithImportedEntities.push_back(std::make_pair(
929 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
930 ImportedEntities.getElement(i)));
931 std::sort(ScopesWithImportedEntities.begin(),
932 ScopesWithImportedEntities.end(), less_first());
933 DIArray GVs = CUNode.getGlobalVariables();
934 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
935 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
936 DIArray SPs = CUNode.getSubprograms();
937 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
938 constructSubprogramDIE(CU, SPs.getElement(i));
939 DIArray EnumTypes = CUNode.getEnumTypes();
940 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
941 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
942 DIArray RetainedTypes = CUNode.getRetainedTypes();
943 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
944 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
945 // Emit imported_modules last so that the relevant context is already
947 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
948 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
951 // Tell MMI that we have debug info.
952 MMI->setDebugInfoAvailability(true);
954 // Prime section data.
955 SectionMap[Asm->getObjFileLowering().getTextSection()];
958 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
959 void DwarfDebug::computeInlinedDIEs() {
960 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
961 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
962 AE = InlinedSubprogramDIEs.end();
965 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
967 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
968 AE = AbstractSPDies.end();
970 DIE *ISP = AI->second;
971 if (InlinedSubprogramDIEs.count(ISP))
973 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
977 // Collect info for variables that were optimized out.
978 void DwarfDebug::collectDeadVariables() {
979 const Module *M = MMI->getModule();
981 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
982 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
983 DICompileUnit TheCU(CU_Nodes->getOperand(i));
984 DIArray Subprograms = TheCU.getSubprograms();
985 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
986 DISubprogram SP(Subprograms.getElement(i));
987 if (ProcessedSPNodes.count(SP) != 0)
989 if (!SP.isSubprogram())
991 if (!SP.isDefinition())
993 DIArray Variables = SP.getVariables();
994 if (Variables.getNumElements() == 0)
997 // Construct subprogram DIE and add variables DIEs.
998 CompileUnit *SPCU = static_cast<CompileUnit *>(CUMap.lookup(TheCU));
999 assert(SPCU && "Unable to find Compile Unit!");
1000 // FIXME: See the comment in constructSubprogramDIE about duplicate
1002 constructSubprogramDIE(SPCU, SP);
1003 DIE *SPDIE = SPCU->getDIE(SP);
1004 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1005 DIVariable DV(Variables.getElement(vi));
1006 if (!DV.isVariable())
1008 DbgVariable NewVar(DV, NULL, this);
1009 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1010 SPDIE->addChild(VariableDIE);
1017 // Type Signature [7.27] and ODR Hash code.
1019 /// \brief Grabs the string in whichever attribute is passed in and returns
1020 /// a reference to it. Returns "" if the attribute doesn't exist.
1021 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1022 DIEValue *V = Die->findAttribute(Attr);
1024 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1025 return S->getString();
1027 return StringRef("");
1030 /// Return true if the current DIE is contained within an anonymous namespace.
1031 static bool isContainedInAnonNamespace(DIE *Die) {
1032 DIE *Parent = Die->getParent();
1035 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1036 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1038 Parent = Parent->getParent();
1044 /// Test if the current CU language is C++ and that we have
1045 /// a named type that is not contained in an anonymous namespace.
1046 static bool shouldAddODRHash(TypeUnit *CU, DIE *Die) {
1047 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1048 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1049 !isContainedInAnonNamespace(Die);
1052 void DwarfDebug::finalizeModuleInfo() {
1053 // Collect info for variables that were optimized out.
1054 collectDeadVariables();
1056 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1057 computeInlinedDIEs();
1059 // Handle anything that needs to be done on a per-cu basis.
1060 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
1061 E = getUnits().end();
1064 // Emit DW_AT_containing_type attribute to connect types with their
1065 // vtable holding type.
1066 TheU->constructContainingTypeDIEs();
1068 // If we're splitting the dwarf out now that we've got the entire
1069 // CU then construct a skeleton CU based upon it.
1070 if (useSplitDwarf() &&
1071 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1073 if (GenerateCUHash) {
1075 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1077 // This should be a unique identifier when we want to build .dwp files.
1078 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1079 dwarf::DW_FORM_data8, ID);
1080 // Now construct the skeleton CU associated.
1081 CompileUnit *SkCU = constructSkeletonCU(static_cast<CompileUnit *>(TheU));
1082 // This should be a unique identifier when we want to build .dwp files.
1083 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1084 dwarf::DW_FORM_data8, ID);
1088 // Compute DIE offsets and sizes.
1089 InfoHolder.computeSizeAndOffsets();
1090 if (useSplitDwarf())
1091 SkeletonHolder.computeSizeAndOffsets();
1094 void DwarfDebug::endSections() {
1095 // Filter labels by section.
1096 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1097 const SymbolCU &SCU = ArangeLabels[n];
1098 if (SCU.Sym->isInSection()) {
1099 // Make a note of this symbol and it's section.
1100 const MCSection *Section = &SCU.Sym->getSection();
1101 if (!Section->getKind().isMetadata())
1102 SectionMap[Section].push_back(SCU);
1104 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1105 // appear in the output. This sucks as we rely on sections to build
1106 // arange spans. We can do it without, but it's icky.
1107 SectionMap[NULL].push_back(SCU);
1111 // Build a list of sections used.
1112 std::vector<const MCSection *> Sections;
1113 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1115 const MCSection *Section = it->first;
1116 Sections.push_back(Section);
1119 // Sort the sections into order.
1120 // This is only done to ensure consistent output order across different runs.
1121 std::sort(Sections.begin(), Sections.end(), SectionSort);
1123 // Add terminating symbols for each section.
1124 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1125 const MCSection *Section = Sections[ID];
1126 MCSymbol *Sym = NULL;
1129 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1130 // if we know the section name up-front. For user-created sections, the
1132 // label may not be valid to use as a label. (section names can use a
1134 // set of characters on some systems)
1135 Sym = Asm->GetTempSymbol("debug_end", ID);
1136 Asm->OutStreamer.SwitchSection(Section);
1137 Asm->OutStreamer.EmitLabel(Sym);
1140 // Insert a final terminator.
1141 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1145 // Emit all Dwarf sections that should come after the content.
1146 void DwarfDebug::endModule() {
1151 // End any existing sections.
1152 // TODO: Does this need to happen?
1155 // Finalize the debug info for the module.
1156 finalizeModuleInfo();
1160 // Emit all the DIEs into a debug info section.
1163 // Corresponding abbreviations into a abbrev section.
1164 emitAbbreviations();
1166 // Emit info into a debug loc section.
1169 // Emit info into a debug aranges section.
1172 // Emit info into a debug ranges section.
1175 // Emit info into a debug macinfo section.
1178 if (useSplitDwarf()) {
1181 emitDebugAbbrevDWO();
1182 // Emit DWO addresses.
1183 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1186 // Emit info into the dwarf accelerator table sections.
1187 if (useDwarfAccelTables()) {
1190 emitAccelNamespaces();
1194 // Emit the pubnames and pubtypes sections if requested.
1195 if (HasDwarfPubSections) {
1196 emitDebugPubNames(GenerateGnuPubSections);
1197 emitDebugPubTypes(GenerateGnuPubSections);
1203 // Reset these for the next Module if we have one.
1207 // Find abstract variable, if any, associated with Var.
1208 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1209 DebugLoc ScopeLoc) {
1210 LLVMContext &Ctx = DV->getContext();
1211 // More then one inlined variable corresponds to one abstract variable.
1212 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1213 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1215 return AbsDbgVariable;
1217 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1221 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1222 addScopeVariable(Scope, AbsDbgVariable);
1223 AbstractVariables[Var] = AbsDbgVariable;
1224 return AbsDbgVariable;
1227 // If Var is a current function argument then add it to CurrentFnArguments list.
1228 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1229 DbgVariable *Var, LexicalScope *Scope) {
1230 if (!LScopes.isCurrentFunctionScope(Scope))
1232 DIVariable DV = Var->getVariable();
1233 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1235 unsigned ArgNo = DV.getArgNumber();
1239 size_t Size = CurrentFnArguments.size();
1241 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1242 // llvm::Function argument size is not good indicator of how many
1243 // arguments does the function have at source level.
1245 CurrentFnArguments.resize(ArgNo * 2);
1246 CurrentFnArguments[ArgNo - 1] = Var;
1250 // Collect variable information from side table maintained by MMI.
1251 void DwarfDebug::collectVariableInfoFromMMITable(
1252 const MachineFunction *MF, SmallPtrSet<const MDNode *, 16> &Processed) {
1253 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1254 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1257 const MDNode *Var = VI->first;
1260 Processed.insert(Var);
1262 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1264 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1266 // If variable scope is not found then skip this variable.
1270 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1271 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1272 RegVar->setFrameIndex(VP.first);
1273 if (!addCurrentFnArgument(MF, RegVar, Scope))
1274 addScopeVariable(Scope, RegVar);
1276 AbsDbgVariable->setFrameIndex(VP.first);
1280 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1282 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1283 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1284 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1285 MI->getOperand(0).getReg() &&
1286 (MI->getOperand(1).isImm() ||
1287 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1290 // Get .debug_loc entry for the instruction range starting at MI.
1291 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1292 const MCSymbol *FLabel,
1293 const MCSymbol *SLabel,
1294 const MachineInstr *MI) {
1295 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1297 assert(MI->getNumOperands() == 3);
1298 if (MI->getOperand(0).isReg()) {
1299 MachineLocation MLoc;
1300 // If the second operand is an immediate, this is a
1301 // register-indirect address.
1302 if (!MI->getOperand(1).isImm())
1303 MLoc.set(MI->getOperand(0).getReg());
1305 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1306 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1308 if (MI->getOperand(0).isImm())
1309 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1310 if (MI->getOperand(0).isFPImm())
1311 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1312 if (MI->getOperand(0).isCImm())
1313 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1315 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1318 // Find variables for each lexical scope.
1320 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1321 SmallPtrSet<const MDNode *, 16> &Processed) {
1323 // Grab the variable info that was squirreled away in the MMI side-table.
1324 collectVariableInfoFromMMITable(MF, Processed);
1326 for (SmallVectorImpl<const MDNode *>::const_iterator
1327 UVI = UserVariables.begin(),
1328 UVE = UserVariables.end();
1329 UVI != UVE; ++UVI) {
1330 const MDNode *Var = *UVI;
1331 if (Processed.count(Var))
1334 // History contains relevant DBG_VALUE instructions for Var and instructions
1336 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1337 if (History.empty())
1339 const MachineInstr *MInsn = History.front();
1342 LexicalScope *Scope = NULL;
1343 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1344 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1345 Scope = LScopes.getCurrentFunctionScope();
1346 else if (MDNode *IA = DV.getInlinedAt())
1347 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1349 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1350 // If variable scope is not found then skip this variable.
1354 Processed.insert(DV);
1355 assert(MInsn->isDebugValue() && "History must begin with debug value");
1356 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1357 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1358 if (!addCurrentFnArgument(MF, RegVar, Scope))
1359 addScopeVariable(Scope, RegVar);
1361 AbsVar->setMInsn(MInsn);
1363 // Simplify ranges that are fully coalesced.
1364 if (History.size() <= 1 ||
1365 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1366 RegVar->setMInsn(MInsn);
1370 // Handle multiple DBG_VALUE instructions describing one variable.
1371 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1373 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1374 HI = History.begin(),
1377 const MachineInstr *Begin = *HI;
1378 assert(Begin->isDebugValue() && "Invalid History entry");
1380 // Check if DBG_VALUE is truncating a range.
1381 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1382 !Begin->getOperand(0).getReg())
1385 // Compute the range for a register location.
1386 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1387 const MCSymbol *SLabel = 0;
1390 // If Begin is the last instruction in History then its value is valid
1391 // until the end of the function.
1392 SLabel = FunctionEndSym;
1394 const MachineInstr *End = HI[1];
1395 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1396 << "\t" << *Begin << "\t" << *End << "\n");
1397 if (End->isDebugValue())
1398 SLabel = getLabelBeforeInsn(End);
1400 // End is a normal instruction clobbering the range.
1401 SLabel = getLabelAfterInsn(End);
1402 assert(SLabel && "Forgot label after clobber instruction");
1407 // The value is valid until the next DBG_VALUE or clobber.
1408 DotDebugLocEntries.push_back(
1409 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1411 DotDebugLocEntries.push_back(DotDebugLocEntry());
1414 // Collect info for variables that were optimized out.
1415 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1416 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1417 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1418 DIVariable DV(Variables.getElement(i));
1419 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1421 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1422 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1426 // Return Label preceding the instruction.
1427 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1428 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1429 assert(Label && "Didn't insert label before instruction");
1433 // Return Label immediately following the instruction.
1434 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1435 return LabelsAfterInsn.lookup(MI);
1438 // Process beginning of an instruction.
1439 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1440 // Check if source location changes, but ignore DBG_VALUE locations.
1441 if (!MI->isDebugValue()) {
1442 DebugLoc DL = MI->getDebugLoc();
1443 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1446 if (DL == PrologEndLoc) {
1447 Flags |= DWARF2_FLAG_PROLOGUE_END;
1448 PrologEndLoc = DebugLoc();
1450 if (PrologEndLoc.isUnknown())
1451 Flags |= DWARF2_FLAG_IS_STMT;
1453 if (!DL.isUnknown()) {
1454 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1455 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1457 recordSourceLine(0, 0, 0, 0);
1461 // Insert labels where requested.
1462 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1463 LabelsBeforeInsn.find(MI);
1466 if (I == LabelsBeforeInsn.end())
1469 // Label already assigned.
1474 PrevLabel = MMI->getContext().CreateTempSymbol();
1475 Asm->OutStreamer.EmitLabel(PrevLabel);
1477 I->second = PrevLabel;
1480 // Process end of an instruction.
1481 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1482 // Don't create a new label after DBG_VALUE instructions.
1483 // They don't generate code.
1484 if (!MI->isDebugValue())
1487 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1488 LabelsAfterInsn.find(MI);
1491 if (I == LabelsAfterInsn.end())
1494 // Label already assigned.
1498 // We need a label after this instruction.
1500 PrevLabel = MMI->getContext().CreateTempSymbol();
1501 Asm->OutStreamer.EmitLabel(PrevLabel);
1503 I->second = PrevLabel;
1506 // Each LexicalScope has first instruction and last instruction to mark
1507 // beginning and end of a scope respectively. Create an inverse map that list
1508 // scopes starts (and ends) with an instruction. One instruction may start (or
1509 // end) multiple scopes. Ignore scopes that are not reachable.
1510 void DwarfDebug::identifyScopeMarkers() {
1511 SmallVector<LexicalScope *, 4> WorkList;
1512 WorkList.push_back(LScopes.getCurrentFunctionScope());
1513 while (!WorkList.empty()) {
1514 LexicalScope *S = WorkList.pop_back_val();
1516 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1517 if (!Children.empty())
1518 for (SmallVectorImpl<LexicalScope *>::const_iterator
1519 SI = Children.begin(),
1520 SE = Children.end();
1522 WorkList.push_back(*SI);
1524 if (S->isAbstractScope())
1527 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1530 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1533 assert(RI->first && "InsnRange does not have first instruction!");
1534 assert(RI->second && "InsnRange does not have second instruction!");
1535 requestLabelBeforeInsn(RI->first);
1536 requestLabelAfterInsn(RI->second);
1541 // Get MDNode for DebugLoc's scope.
1542 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1543 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1544 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1545 return DL.getScope(Ctx);
1548 // Walk up the scope chain of given debug loc and find line number info
1549 // for the function.
1550 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1551 const MDNode *Scope = getScopeNode(DL, Ctx);
1552 DISubprogram SP = getDISubprogram(Scope);
1553 if (SP.isSubprogram()) {
1554 // Check for number of operands since the compatibility is
1556 if (SP->getNumOperands() > 19)
1557 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1559 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1565 // Gather pre-function debug information. Assumes being called immediately
1566 // after the function entry point has been emitted.
1567 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1569 // If there's no debug info for the function we're not going to do anything.
1570 if (!MMI->hasDebugInfo())
1573 // Grab the lexical scopes for the function, if we don't have any of those
1574 // then we're not going to be able to do anything.
1575 LScopes.initialize(*MF);
1576 if (LScopes.empty())
1579 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1581 // Make sure that each lexical scope will have a begin/end label.
1582 identifyScopeMarkers();
1584 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1585 // belongs to so that we add to the correct per-cu line table in the
1587 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1588 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1589 assert(TheCU && "Unable to find compile unit!");
1590 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1591 // Use a single line table if we are using .loc and generating assembly.
1592 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1594 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1596 // Emit a label for the function so that we have a beginning address.
1597 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1598 // Assumes in correct section after the entry point.
1599 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1601 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1602 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1603 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1605 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1607 bool AtBlockEntry = true;
1608 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1610 const MachineInstr *MI = II;
1612 if (MI->isDebugValue()) {
1613 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1615 // Keep track of user variables.
1617 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1619 // Variable is in a register, we need to check for clobbers.
1620 if (isDbgValueInDefinedReg(MI))
1621 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1623 // Check the history of this variable.
1624 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1625 if (History.empty()) {
1626 UserVariables.push_back(Var);
1627 // The first mention of a function argument gets the FunctionBeginSym
1628 // label, so arguments are visible when breaking at function entry.
1630 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1631 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1632 LabelsBeforeInsn[MI] = FunctionBeginSym;
1634 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1635 const MachineInstr *Prev = History.back();
1636 if (Prev->isDebugValue()) {
1637 // Coalesce identical entries at the end of History.
1638 if (History.size() >= 2 &&
1639 Prev->isIdenticalTo(History[History.size() - 2])) {
1640 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1641 << "\t" << *Prev << "\t"
1642 << *History[History.size() - 2] << "\n");
1646 // Terminate old register assignments that don't reach MI;
1647 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1648 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1649 isDbgValueInDefinedReg(Prev)) {
1650 // Previous register assignment needs to terminate at the end of
1652 MachineBasicBlock::const_iterator LastMI =
1653 PrevMBB->getLastNonDebugInstr();
1654 if (LastMI == PrevMBB->end()) {
1655 // Drop DBG_VALUE for empty range.
1656 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1657 << "\t" << *Prev << "\n");
1659 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1660 // Terminate after LastMI.
1661 History.push_back(LastMI);
1665 History.push_back(MI);
1667 // Not a DBG_VALUE instruction.
1669 AtBlockEntry = false;
1671 // First known non-DBG_VALUE and non-frame setup location marks
1672 // the beginning of the function body.
1673 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1674 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1675 PrologEndLoc = MI->getDebugLoc();
1677 // Check if the instruction clobbers any registers with debug vars.
1678 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1679 MOE = MI->operands_end();
1680 MOI != MOE; ++MOI) {
1681 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1683 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1686 const MDNode *Var = LiveUserVar[Reg];
1689 // Reg is now clobbered.
1690 LiveUserVar[Reg] = 0;
1692 // Was MD last defined by a DBG_VALUE referring to Reg?
1693 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1694 if (HistI == DbgValues.end())
1696 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1697 if (History.empty())
1699 const MachineInstr *Prev = History.back();
1700 // Sanity-check: Register assignments are terminated at the end of
1702 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1704 // Is the variable still in Reg?
1705 if (!isDbgValueInDefinedReg(Prev) ||
1706 Prev->getOperand(0).getReg() != Reg)
1708 // Var is clobbered. Make sure the next instruction gets a label.
1709 History.push_back(MI);
1716 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1718 SmallVectorImpl<const MachineInstr *> &History = I->second;
1719 if (History.empty())
1722 // Make sure the final register assignments are terminated.
1723 const MachineInstr *Prev = History.back();
1724 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1725 const MachineBasicBlock *PrevMBB = Prev->getParent();
1726 MachineBasicBlock::const_iterator LastMI =
1727 PrevMBB->getLastNonDebugInstr();
1728 if (LastMI == PrevMBB->end())
1729 // Drop DBG_VALUE for empty range.
1731 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1732 // Terminate after LastMI.
1733 History.push_back(LastMI);
1736 // Request labels for the full history.
1737 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1738 const MachineInstr *MI = History[i];
1739 if (MI->isDebugValue())
1740 requestLabelBeforeInsn(MI);
1742 requestLabelAfterInsn(MI);
1746 PrevInstLoc = DebugLoc();
1747 PrevLabel = FunctionBeginSym;
1749 // Record beginning of function.
1750 if (!PrologEndLoc.isUnknown()) {
1751 DebugLoc FnStartDL =
1752 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1754 FnStartDL.getLine(), FnStartDL.getCol(),
1755 FnStartDL.getScope(MF->getFunction()->getContext()),
1756 // We'd like to list the prologue as "not statements" but GDB behaves
1757 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1758 DWARF2_FLAG_IS_STMT);
1762 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1763 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1764 DIVariable DV = Var->getVariable();
1765 // Variables with positive arg numbers are parameters.
1766 if (unsigned ArgNum = DV.getArgNumber()) {
1767 // Keep all parameters in order at the start of the variable list to ensure
1768 // function types are correct (no out-of-order parameters)
1770 // This could be improved by only doing it for optimized builds (unoptimized
1771 // builds have the right order to begin with), searching from the back (this
1772 // would catch the unoptimized case quickly), or doing a binary search
1773 // rather than linear search.
1774 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1775 while (I != Vars.end()) {
1776 unsigned CurNum = (*I)->getVariable().getArgNumber();
1777 // A local (non-parameter) variable has been found, insert immediately
1781 // A later indexed parameter has been found, insert immediately before it.
1782 if (CurNum > ArgNum)
1786 Vars.insert(I, Var);
1790 Vars.push_back(Var);
1793 // Gather and emit post-function debug information.
1794 void DwarfDebug::endFunction(const MachineFunction *MF) {
1795 if (!MMI->hasDebugInfo() || LScopes.empty())
1798 // Define end label for subprogram.
1799 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1800 // Assumes in correct section after the entry point.
1801 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1802 // Set DwarfCompileUnitID in MCContext to default value.
1803 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1805 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1806 collectVariableInfo(MF, ProcessedVars);
1808 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1809 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1810 assert(TheCU && "Unable to find compile unit!");
1812 // Construct abstract scopes.
1813 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1814 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1815 LexicalScope *AScope = AList[i];
1816 DISubprogram SP(AScope->getScopeNode());
1817 if (SP.isSubprogram()) {
1818 // Collect info for variables that were optimized out.
1819 DIArray Variables = SP.getVariables();
1820 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1821 DIVariable DV(Variables.getElement(i));
1822 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1824 // Check that DbgVariable for DV wasn't created earlier, when
1825 // findAbstractVariable() was called for inlined instance of DV.
1826 LLVMContext &Ctx = DV->getContext();
1827 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1828 if (AbstractVariables.lookup(CleanDV))
1830 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1831 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1834 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1835 constructScopeDIE(TheCU, AScope);
1838 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1840 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1841 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1844 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1845 E = ScopeVariables.end();
1847 DeleteContainerPointers(I->second);
1848 ScopeVariables.clear();
1849 DeleteContainerPointers(CurrentFnArguments);
1850 UserVariables.clear();
1852 AbstractVariables.clear();
1853 LabelsBeforeInsn.clear();
1854 LabelsAfterInsn.clear();
1858 // Register a source line with debug info. Returns the unique label that was
1859 // emitted and which provides correspondence to the source line list.
1860 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1866 DIDescriptor Scope(S);
1868 if (Scope.isCompileUnit()) {
1869 DICompileUnit CU(S);
1870 Fn = CU.getFilename();
1871 Dir = CU.getDirectory();
1872 } else if (Scope.isFile()) {
1874 Fn = F.getFilename();
1875 Dir = F.getDirectory();
1876 } else if (Scope.isSubprogram()) {
1878 Fn = SP.getFilename();
1879 Dir = SP.getDirectory();
1880 } else if (Scope.isLexicalBlockFile()) {
1881 DILexicalBlockFile DBF(S);
1882 Fn = DBF.getFilename();
1883 Dir = DBF.getDirectory();
1884 } else if (Scope.isLexicalBlock()) {
1885 DILexicalBlock DB(S);
1886 Fn = DB.getFilename();
1887 Dir = DB.getDirectory();
1889 llvm_unreachable("Unexpected scope info");
1891 Src = getOrCreateSourceID(
1892 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1894 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1897 //===----------------------------------------------------------------------===//
1899 //===----------------------------------------------------------------------===//
1901 // Compute the size and offset of a DIE. The offset is relative to start of the
1902 // CU. It returns the offset after laying out the DIE.
1903 unsigned DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1904 // Get the children.
1905 const std::vector<DIE *> &Children = Die->getChildren();
1907 // Record the abbreviation.
1908 assignAbbrevNumber(Die->getAbbrev());
1910 // Get the abbreviation for this DIE.
1911 unsigned AbbrevNumber = Die->getAbbrevNumber();
1912 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1915 Die->setOffset(Offset);
1917 // Start the size with the size of abbreviation code.
1918 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1920 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1921 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1923 // Size the DIE attribute values.
1924 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1925 // Size attribute value.
1926 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1928 // Size the DIE children if any.
1929 if (!Children.empty()) {
1930 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1931 "Children flag not set");
1933 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1934 Offset = computeSizeAndOffset(Children[j], Offset);
1936 // End of children marker.
1937 Offset += sizeof(int8_t);
1940 Die->setSize(Offset - Die->getOffset());
1944 // Compute the size and offset for each DIE.
1945 void DwarfUnits::computeSizeAndOffsets() {
1946 // Offset from the first CU in the debug info section is 0 initially.
1947 unsigned SecOffset = 0;
1949 // Iterate over each compile unit and set the size and offsets for each
1950 // DIE within each compile unit. All offsets are CU relative.
1951 for (SmallVectorImpl<Unit *>::const_iterator I = CUs.begin(), E = CUs.end();
1953 (*I)->setDebugInfoOffset(SecOffset);
1955 // CU-relative offset is reset to 0 here.
1956 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1957 (*I)->getHeaderSize(); // Unit-specific headers
1959 // EndOffset here is CU-relative, after laying out
1960 // all of the CU DIE.
1961 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1962 SecOffset += EndOffset;
1966 // Emit initial Dwarf sections with a label at the start of each one.
1967 void DwarfDebug::emitSectionLabels() {
1968 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1970 // Dwarf sections base addresses.
1971 DwarfInfoSectionSym =
1972 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1973 DwarfAbbrevSectionSym =
1974 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1975 if (useSplitDwarf())
1976 DwarfAbbrevDWOSectionSym = emitSectionSym(
1977 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1978 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1980 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1981 emitSectionSym(Asm, MacroInfo);
1983 DwarfLineSectionSym =
1984 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1985 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1986 if (GenerateGnuPubSections) {
1987 DwarfGnuPubNamesSectionSym =
1988 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1989 DwarfGnuPubTypesSectionSym =
1990 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1991 } else if (HasDwarfPubSections) {
1992 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1993 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1996 DwarfStrSectionSym =
1997 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1998 if (useSplitDwarf()) {
1999 DwarfStrDWOSectionSym =
2000 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2001 DwarfAddrSectionSym =
2002 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2004 DwarfDebugRangeSectionSym =
2005 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2007 DwarfDebugLocSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2010 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2011 emitSectionSym(Asm, TLOF.getDataSection());
2014 // Recursively emits a debug information entry.
2015 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2016 // Get the abbreviation for this DIE.
2017 unsigned AbbrevNumber = Die->getAbbrevNumber();
2018 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2020 // Emit the code (index) for the abbreviation.
2021 if (Asm->isVerbose())
2022 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2023 Twine::utohexstr(Die->getOffset()) + ":0x" +
2024 Twine::utohexstr(Die->getSize()) + " " +
2025 dwarf::TagString(Abbrev->getTag()));
2026 Asm->EmitULEB128(AbbrevNumber);
2028 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2029 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2031 // Emit the DIE attribute values.
2032 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2033 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2034 dwarf::Form Form = AbbrevData[i].getForm();
2035 assert(Form && "Too many attributes for DIE (check abbreviation)");
2037 if (Asm->isVerbose())
2038 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2041 case dwarf::DW_AT_abstract_origin:
2042 case dwarf::DW_AT_type:
2043 case dwarf::DW_AT_friend:
2044 case dwarf::DW_AT_specification:
2045 case dwarf::DW_AT_import:
2046 case dwarf::DW_AT_containing_type: {
2047 DIEEntry *E = cast<DIEEntry>(Values[i]);
2048 DIE *Origin = E->getEntry();
2049 unsigned Addr = Origin->getOffset();
2050 if (Form == dwarf::DW_FORM_ref_addr) {
2051 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2052 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2053 // section. Origin->getOffset() returns the offset from start of the
2055 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2056 assert(CU && "CUDie should belong to a CU.");
2057 Addr += CU->getDebugInfoOffset();
2058 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2059 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2060 DIEEntry::getRefAddrSize(Asm));
2062 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2063 DwarfInfoSectionSym,
2064 DIEEntry::getRefAddrSize(Asm));
2066 // Make sure Origin belong to the same CU.
2067 assert(Die->getUnit() == Origin->getUnit() &&
2068 "The referenced DIE should belong to the same CU in ref4");
2069 Asm->EmitInt32(Addr);
2073 case dwarf::DW_AT_ranges: {
2074 // DW_AT_range Value encodes offset in debug_range section.
2075 DIELabel *V = cast<DIELabel>(Values[i]);
2077 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2078 Asm->EmitSectionOffset(V->getValue(), DwarfDebugRangeSectionSym);
2080 Asm->EmitLabelDifference(V->getValue(), DwarfDebugRangeSectionSym, 4);
2083 case dwarf::DW_AT_location: {
2084 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2085 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2086 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2088 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2090 Values[i]->EmitValue(Asm, Form);
2094 case dwarf::DW_AT_accessibility: {
2095 if (Asm->isVerbose()) {
2096 DIEInteger *V = cast<DIEInteger>(Values[i]);
2097 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2099 Values[i]->EmitValue(Asm, Form);
2103 // Emit an attribute using the defined form.
2104 Values[i]->EmitValue(Asm, Form);
2109 // Emit the DIE children if any.
2110 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2111 const std::vector<DIE *> &Children = Die->getChildren();
2113 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2114 emitDIE(Children[j], Abbrevs);
2116 if (Asm->isVerbose())
2117 Asm->OutStreamer.AddComment("End Of Children Mark");
2122 // Emit the various dwarf units to the unit section USection with
2123 // the abbreviations going into ASection.
2124 void DwarfUnits::emitUnits(DwarfDebug *DD, const MCSection *USection,
2125 const MCSection *ASection,
2126 const MCSymbol *ASectionSym) {
2127 Asm->OutStreamer.SwitchSection(USection);
2128 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
2131 DIE *Die = TheU->getUnitDie();
2133 // Emit the compile units header.
2134 Asm->OutStreamer.EmitLabel(
2135 Asm->GetTempSymbol(USection->getLabelBeginName(), TheU->getUniqueID()));
2137 // Emit size of content not including length itself
2138 Asm->OutStreamer.AddComment("Length of Unit");
2139 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2141 TheU->emitHeader(ASection, ASectionSym);
2143 DD->emitDIE(Die, Abbreviations);
2144 Asm->OutStreamer.EmitLabel(
2145 Asm->GetTempSymbol(USection->getLabelEndName(), TheU->getUniqueID()));
2149 // Emit the debug info section.
2150 void DwarfDebug::emitDebugInfo() {
2151 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2153 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2154 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2155 DwarfAbbrevSectionSym);
2158 // Emit the abbreviation section.
2159 void DwarfDebug::emitAbbreviations() {
2160 if (!useSplitDwarf())
2161 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2164 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2167 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2168 std::vector<DIEAbbrev *> *Abbrevs) {
2169 // Check to see if it is worth the effort.
2170 if (!Abbrevs->empty()) {
2171 // Start the debug abbrev section.
2172 Asm->OutStreamer.SwitchSection(Section);
2174 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2175 Asm->OutStreamer.EmitLabel(Begin);
2177 // For each abbrevation.
2178 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2179 // Get abbreviation data
2180 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2182 // Emit the abbrevations code (base 1 index.)
2183 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2185 // Emit the abbreviations data.
2189 // Mark end of abbreviations.
2190 Asm->EmitULEB128(0, "EOM(3)");
2192 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2193 Asm->OutStreamer.EmitLabel(End);
2197 // Emit the last address of the section and the end of the line matrix.
2198 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2199 // Define last address of section.
2200 Asm->OutStreamer.AddComment("Extended Op");
2203 Asm->OutStreamer.AddComment("Op size");
2204 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2205 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2206 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2208 Asm->OutStreamer.AddComment("Section end label");
2210 Asm->OutStreamer.EmitSymbolValue(
2211 Asm->GetTempSymbol("section_end", SectionEnd),
2212 Asm->getDataLayout().getPointerSize());
2214 // Mark end of matrix.
2215 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2221 // Emit visible names into a hashed accelerator table section.
2222 void DwarfDebug::emitAccelNames() {
2224 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2225 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2226 E = getUnits().end();
2229 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2230 for (StringMap<std::vector<const DIE *> >::const_iterator
2234 StringRef Name = GI->getKey();
2235 const std::vector<const DIE *> &Entities = GI->second;
2236 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2237 DE = Entities.end();
2239 AT.AddName(Name, *DI);
2243 AT.FinalizeTable(Asm, "Names");
2244 Asm->OutStreamer.SwitchSection(
2245 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2246 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2247 Asm->OutStreamer.EmitLabel(SectionBegin);
2249 // Emit the full data.
2250 AT.Emit(Asm, SectionBegin, &InfoHolder);
2253 // Emit objective C classes and categories into a hashed accelerator table
2255 void DwarfDebug::emitAccelObjC() {
2257 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2258 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2259 E = getUnits().end();
2262 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2263 for (StringMap<std::vector<const DIE *> >::const_iterator
2267 StringRef Name = GI->getKey();
2268 const std::vector<const DIE *> &Entities = GI->second;
2269 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2270 DE = Entities.end();
2272 AT.AddName(Name, *DI);
2276 AT.FinalizeTable(Asm, "ObjC");
2277 Asm->OutStreamer.SwitchSection(
2278 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2279 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2280 Asm->OutStreamer.EmitLabel(SectionBegin);
2282 // Emit the full data.
2283 AT.Emit(Asm, SectionBegin, &InfoHolder);
2286 // Emit namespace dies into a hashed accelerator table.
2287 void DwarfDebug::emitAccelNamespaces() {
2289 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2290 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2291 E = getUnits().end();
2294 const StringMap<std::vector<const DIE *> > &Names =
2295 TheU->getAccelNamespace();
2296 for (StringMap<std::vector<const DIE *> >::const_iterator
2300 StringRef Name = GI->getKey();
2301 const std::vector<const DIE *> &Entities = GI->second;
2302 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2303 DE = Entities.end();
2305 AT.AddName(Name, *DI);
2309 AT.FinalizeTable(Asm, "namespac");
2310 Asm->OutStreamer.SwitchSection(
2311 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2312 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2313 Asm->OutStreamer.EmitLabel(SectionBegin);
2315 // Emit the full data.
2316 AT.Emit(Asm, SectionBegin, &InfoHolder);
2319 // Emit type dies into a hashed accelerator table.
2320 void DwarfDebug::emitAccelTypes() {
2321 std::vector<DwarfAccelTable::Atom> Atoms;
2323 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2325 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2327 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2328 DwarfAccelTable AT(Atoms);
2329 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2330 E = getUnits().end();
2333 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2334 TheU->getAccelTypes();
2336 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2340 StringRef Name = GI->getKey();
2341 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2343 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2344 DI = Entities.begin(),
2345 DE = Entities.end();
2347 AT.AddName(Name, DI->first, DI->second);
2351 AT.FinalizeTable(Asm, "types");
2352 Asm->OutStreamer.SwitchSection(
2353 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2354 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2355 Asm->OutStreamer.EmitLabel(SectionBegin);
2357 // Emit the full data.
2358 AT.Emit(Asm, SectionBegin, &InfoHolder);
2361 // Public name handling.
2362 // The format for the various pubnames:
2364 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2365 // for the DIE that is named.
2367 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2368 // into the CU and the index value is computed according to the type of value
2369 // for the DIE that is named.
2371 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2372 // it's the offset within the debug_info/debug_types dwo section, however, the
2373 // reference in the pubname header doesn't change.
2375 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2376 static dwarf::PubIndexEntryDescriptor computeIndexValue(Unit *CU,
2378 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2380 // We could have a specification DIE that has our most of our knowledge,
2381 // look for that now.
2382 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2384 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2385 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2386 Linkage = dwarf::GIEL_EXTERNAL;
2387 } else if (Die->findAttribute(dwarf::DW_AT_external))
2388 Linkage = dwarf::GIEL_EXTERNAL;
2390 switch (Die->getTag()) {
2391 case dwarf::DW_TAG_class_type:
2392 case dwarf::DW_TAG_structure_type:
2393 case dwarf::DW_TAG_union_type:
2394 case dwarf::DW_TAG_enumeration_type:
2395 return dwarf::PubIndexEntryDescriptor(
2396 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2397 ? dwarf::GIEL_STATIC
2398 : dwarf::GIEL_EXTERNAL);
2399 case dwarf::DW_TAG_typedef:
2400 case dwarf::DW_TAG_base_type:
2401 case dwarf::DW_TAG_subrange_type:
2402 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2403 case dwarf::DW_TAG_namespace:
2404 return dwarf::GIEK_TYPE;
2405 case dwarf::DW_TAG_subprogram:
2406 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2407 case dwarf::DW_TAG_constant:
2408 case dwarf::DW_TAG_variable:
2409 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2410 case dwarf::DW_TAG_enumerator:
2411 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2412 dwarf::GIEL_STATIC);
2414 return dwarf::GIEK_NONE;
2418 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2420 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2421 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2422 const MCSection *PSec =
2423 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2424 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2426 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2427 E = getUnits().end();
2430 unsigned ID = TheU->getUniqueID();
2432 // Start the dwarf pubnames section.
2433 Asm->OutStreamer.SwitchSection(PSec);
2435 // Emit a label so we can reference the beginning of this pubname section.
2437 Asm->OutStreamer.EmitLabel(
2438 Asm->GetTempSymbol("gnu_pubnames", TheU->getUniqueID()));
2441 Asm->OutStreamer.AddComment("Length of Public Names Info");
2442 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2443 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2445 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2447 Asm->OutStreamer.AddComment("DWARF Version");
2448 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2450 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2451 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2452 DwarfInfoSectionSym);
2454 Asm->OutStreamer.AddComment("Compilation Unit Length");
2455 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2456 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2459 // Emit the pubnames for this compilation unit.
2460 const StringMap<const DIE *> &Globals = TheU->getGlobalNames();
2461 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2464 const char *Name = GI->getKeyData();
2465 const DIE *Entity = GI->second;
2467 Asm->OutStreamer.AddComment("DIE offset");
2468 Asm->EmitInt32(Entity->getOffset());
2471 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2472 Asm->OutStreamer.AddComment(
2473 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2474 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2475 Asm->EmitInt8(Desc.toBits());
2478 if (Asm->isVerbose())
2479 Asm->OutStreamer.AddComment("External Name");
2480 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2483 Asm->OutStreamer.AddComment("End Mark");
2485 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2489 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2490 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2491 const MCSection *PSec =
2492 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2493 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2495 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2496 E = getUnits().end();
2499 // Start the dwarf pubtypes section.
2500 Asm->OutStreamer.SwitchSection(PSec);
2502 // Emit a label so we can reference the beginning of this pubtype section.
2504 Asm->OutStreamer.EmitLabel(
2505 Asm->GetTempSymbol("gnu_pubtypes", TheU->getUniqueID()));
2508 Asm->OutStreamer.AddComment("Length of Public Types Info");
2509 Asm->EmitLabelDifference(
2510 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()),
2511 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()), 4);
2513 Asm->OutStreamer.EmitLabel(
2514 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()));
2516 if (Asm->isVerbose())
2517 Asm->OutStreamer.AddComment("DWARF Version");
2518 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2520 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2521 Asm->EmitSectionOffset(
2522 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()),
2523 DwarfInfoSectionSym);
2525 Asm->OutStreamer.AddComment("Compilation Unit Length");
2526 Asm->EmitLabelDifference(
2527 Asm->GetTempSymbol(ISec->getLabelEndName(), TheU->getUniqueID()),
2528 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()), 4);
2530 // Emit the pubtypes.
2531 const StringMap<const DIE *> &Globals = TheU->getGlobalTypes();
2532 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2535 const char *Name = GI->getKeyData();
2536 const DIE *Entity = GI->second;
2538 if (Asm->isVerbose())
2539 Asm->OutStreamer.AddComment("DIE offset");
2540 Asm->EmitInt32(Entity->getOffset());
2543 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2544 Asm->OutStreamer.AddComment(
2545 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2546 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2547 Asm->EmitInt8(Desc.toBits());
2550 if (Asm->isVerbose())
2551 Asm->OutStreamer.AddComment("External Name");
2553 // Emit the name with a terminating null byte.
2554 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2557 Asm->OutStreamer.AddComment("End Mark");
2559 Asm->OutStreamer.EmitLabel(
2560 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()));
2564 // Emit strings into a string section.
2565 void DwarfUnits::emitStrings(const MCSection *StrSection,
2566 const MCSection *OffsetSection = NULL,
2567 const MCSymbol *StrSecSym = NULL) {
2569 if (StringPool.empty())
2572 // Start the dwarf str section.
2573 Asm->OutStreamer.SwitchSection(StrSection);
2575 // Get all of the string pool entries and put them in an array by their ID so
2576 // we can sort them.
2578 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2581 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2582 I = StringPool.begin(),
2583 E = StringPool.end();
2585 Entries.push_back(std::make_pair(I->second.second, &*I));
2587 array_pod_sort(Entries.begin(), Entries.end());
2589 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2590 // Emit a label for reference from debug information entries.
2591 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2593 // Emit the string itself with a terminating null byte.
2594 Asm->OutStreamer.EmitBytes(
2595 StringRef(Entries[i].second->getKeyData(),
2596 Entries[i].second->getKeyLength() + 1));
2599 // If we've got an offset section go ahead and emit that now as well.
2600 if (OffsetSection) {
2601 Asm->OutStreamer.SwitchSection(OffsetSection);
2602 unsigned offset = 0;
2603 unsigned size = 4; // FIXME: DWARF64 is 8.
2604 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2605 Asm->OutStreamer.EmitIntValue(offset, size);
2606 offset += Entries[i].second->getKeyLength() + 1;
2612 // Emit addresses into the section given.
2613 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2615 if (AddressPool.empty())
2618 // Start the dwarf addr section.
2619 Asm->OutStreamer.SwitchSection(AddrSection);
2621 // Order the address pool entries by ID
2622 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2624 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2625 E = AddressPool.end();
2627 Entries[I->second] = I->first;
2629 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2630 // Emit an expression for reference from debug information entries.
2631 if (const MCExpr *Expr = Entries[i])
2632 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2634 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2638 // Emit visible names into a debug str section.
2639 void DwarfDebug::emitDebugStr() {
2640 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2641 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2644 // Emit locations into the debug loc section.
2645 void DwarfDebug::emitDebugLoc() {
2646 if (DotDebugLocEntries.empty())
2649 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2650 I = DotDebugLocEntries.begin(),
2651 E = DotDebugLocEntries.end();
2653 DotDebugLocEntry &Entry = *I;
2654 if (I + 1 != DotDebugLocEntries.end())
2658 // Start the dwarf loc section.
2659 Asm->OutStreamer.SwitchSection(
2660 Asm->getObjFileLowering().getDwarfLocSection());
2661 unsigned char Size = Asm->getDataLayout().getPointerSize();
2662 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2664 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2665 I = DotDebugLocEntries.begin(),
2666 E = DotDebugLocEntries.end();
2667 I != E; ++I, ++index) {
2668 DotDebugLocEntry &Entry = *I;
2669 if (Entry.isMerged())
2671 if (Entry.isEmpty()) {
2672 Asm->OutStreamer.EmitIntValue(0, Size);
2673 Asm->OutStreamer.EmitIntValue(0, Size);
2674 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2676 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2677 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2678 DIVariable DV(Entry.getVariable());
2679 Asm->OutStreamer.AddComment("Loc expr size");
2680 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2681 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2682 Asm->EmitLabelDifference(end, begin, 2);
2683 Asm->OutStreamer.EmitLabel(begin);
2684 if (Entry.isInt()) {
2685 DIBasicType BTy(DV.getType());
2686 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2687 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2688 Asm->OutStreamer.AddComment("DW_OP_consts");
2689 Asm->EmitInt8(dwarf::DW_OP_consts);
2690 Asm->EmitSLEB128(Entry.getInt());
2692 Asm->OutStreamer.AddComment("DW_OP_constu");
2693 Asm->EmitInt8(dwarf::DW_OP_constu);
2694 Asm->EmitULEB128(Entry.getInt());
2696 } else if (Entry.isLocation()) {
2697 MachineLocation Loc = Entry.getLoc();
2698 if (!DV.hasComplexAddress())
2700 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2702 // Complex address entry.
2703 unsigned N = DV.getNumAddrElements();
2705 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2706 if (Loc.getOffset()) {
2708 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2709 Asm->OutStreamer.AddComment("DW_OP_deref");
2710 Asm->EmitInt8(dwarf::DW_OP_deref);
2711 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2712 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2713 Asm->EmitSLEB128(DV.getAddrElement(1));
2715 // If first address element is OpPlus then emit
2716 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2717 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2718 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2722 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2725 // Emit remaining complex address elements.
2726 for (; i < N; ++i) {
2727 uint64_t Element = DV.getAddrElement(i);
2728 if (Element == DIBuilder::OpPlus) {
2729 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2730 Asm->EmitULEB128(DV.getAddrElement(++i));
2731 } else if (Element == DIBuilder::OpDeref) {
2733 Asm->EmitInt8(dwarf::DW_OP_deref);
2735 llvm_unreachable("unknown Opcode found in complex address");
2739 // else ... ignore constant fp. There is not any good way to
2740 // to represent them here in dwarf.
2741 Asm->OutStreamer.EmitLabel(end);
2746 struct SymbolCUSorter {
2747 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2748 const MCStreamer &Streamer;
2750 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2751 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2752 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2754 // Symbols with no order assigned should be placed at the end.
2755 // (e.g. section end labels)
2757 IA = (unsigned)(-1);
2759 IB = (unsigned)(-1);
2764 static bool CUSort(const Unit *A, const Unit *B) {
2765 return (A->getUniqueID() < B->getUniqueID());
2769 const MCSymbol *Start, *End;
2772 // Emit a debug aranges section, containing a CU lookup for any
2773 // address we can tie back to a CU.
2774 void DwarfDebug::emitDebugARanges() {
2775 // Start the dwarf aranges section.
2776 Asm->OutStreamer.SwitchSection(
2777 Asm->getObjFileLowering().getDwarfARangesSection());
2779 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2783 // Build a list of sections used.
2784 std::vector<const MCSection *> Sections;
2785 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2787 const MCSection *Section = it->first;
2788 Sections.push_back(Section);
2791 // Sort the sections into order.
2792 // This is only done to ensure consistent output order across different runs.
2793 std::sort(Sections.begin(), Sections.end(), SectionSort);
2795 // Build a set of address spans, sorted by CU.
2796 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2797 const MCSection *Section = Sections[SecIdx];
2798 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2799 if (List.size() < 2)
2802 // Sort the symbols by offset within the section.
2803 SymbolCUSorter sorter(Asm->OutStreamer);
2804 std::sort(List.begin(), List.end(), sorter);
2806 // If we have no section (e.g. common), just write out
2807 // individual spans for each symbol.
2808 if (Section == NULL) {
2809 for (size_t n = 0; n < List.size(); n++) {
2810 const SymbolCU &Cur = List[n];
2813 Span.Start = Cur.Sym;
2816 Spans[Cur.CU].push_back(Span);
2819 // Build spans between each label.
2820 const MCSymbol *StartSym = List[0].Sym;
2821 for (size_t n = 1; n < List.size(); n++) {
2822 const SymbolCU &Prev = List[n - 1];
2823 const SymbolCU &Cur = List[n];
2825 // Try and build the longest span we can within the same CU.
2826 if (Cur.CU != Prev.CU) {
2828 Span.Start = StartSym;
2830 Spans[Prev.CU].push_back(Span);
2837 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2838 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2840 // Build a list of CUs used.
2841 std::vector<CompileUnit *> CUs;
2842 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2843 CompileUnit *CU = it->first;
2847 // Sort the CU list (again, to ensure consistent output order).
2848 std::sort(CUs.begin(), CUs.end(), CUSort);
2850 // Emit an arange table for each CU we used.
2851 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2852 CompileUnit *CU = CUs[CUIdx];
2853 std::vector<ArangeSpan> &List = Spans[CU];
2855 // Emit size of content not including length itself.
2856 unsigned ContentSize =
2857 sizeof(int16_t) + // DWARF ARange version number
2858 sizeof(int32_t) + // Offset of CU in the .debug_info section
2859 sizeof(int8_t) + // Pointer Size (in bytes)
2860 sizeof(int8_t); // Segment Size (in bytes)
2862 unsigned TupleSize = PtrSize * 2;
2864 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2865 unsigned Padding = 0;
2866 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2869 ContentSize += Padding;
2870 ContentSize += (List.size() + 1) * TupleSize;
2872 // For each compile unit, write the list of spans it covers.
2873 Asm->OutStreamer.AddComment("Length of ARange Set");
2874 Asm->EmitInt32(ContentSize);
2875 Asm->OutStreamer.AddComment("DWARF Arange version number");
2876 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2877 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2878 Asm->EmitSectionOffset(
2879 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2880 DwarfInfoSectionSym);
2881 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2882 Asm->EmitInt8(PtrSize);
2883 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2886 for (unsigned n = 0; n < Padding; n++)
2887 Asm->EmitInt8(0xff);
2889 for (unsigned n = 0; n < List.size(); n++) {
2890 const ArangeSpan &Span = List[n];
2891 Asm->EmitLabelReference(Span.Start, PtrSize);
2893 // Calculate the size as being from the span start to it's end.
2895 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2897 // For symbols without an end marker (e.g. common), we
2898 // write a single arange entry containing just that one symbol.
2899 uint64_t Size = SymSize[Span.Start];
2903 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2907 Asm->OutStreamer.AddComment("ARange terminator");
2908 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2909 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2913 // Emit visible names into a debug ranges section.
2914 void DwarfDebug::emitDebugRanges() {
2915 // Start the dwarf ranges section.
2916 Asm->OutStreamer.SwitchSection(
2917 Asm->getObjFileLowering().getDwarfRangesSection());
2919 // Size for our labels.
2920 unsigned char Size = Asm->getDataLayout().getPointerSize();
2922 // Grab the specific ranges for the compile units in the module.
2923 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2926 CompileUnit *TheCU = I->second;
2927 unsigned ID = TheCU->getUniqueID();
2929 // Emit a symbol so we can find the beginning of our ranges.
2930 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_ranges", ID));
2932 // Iterate over the misc ranges for the compile units in the module.
2933 const SmallVectorImpl<RangeSpanList *> &RangeLists = TheCU->getRangeLists();
2934 for (SmallVectorImpl<RangeSpanList *>::const_iterator
2935 I = RangeLists.begin(),
2936 E = RangeLists.end();
2938 RangeSpanList *List = *I;
2940 // Emit a symbol so we can find the beginning of the range.
2941 Asm->OutStreamer.EmitLabel(
2942 Asm->GetTempSymbol("debug_ranges", List->getIndex()));
2944 for (SmallVectorImpl<RangeSpan>::const_iterator
2945 I = List->getRanges().begin(),
2946 E = List->getRanges().end();
2948 RangeSpan Range = *I;
2949 // We occasionally have ranges without begin/end labels.
2950 // FIXME: Verify and fix.
2951 const MCSymbol *Begin = Range.getStart();
2952 const MCSymbol *End = Range.getEnd();
2953 Begin ? Asm->OutStreamer.EmitSymbolValue(Begin, Size)
2954 : Asm->OutStreamer.EmitIntValue(0, Size);
2955 End ? Asm->OutStreamer.EmitSymbolValue(End, Size)
2956 : Asm->OutStreamer.EmitIntValue(0, Size);
2959 // And terminate the list with two 0 values.
2960 Asm->OutStreamer.EmitIntValue(0, Size);
2961 Asm->OutStreamer.EmitIntValue(0, Size);
2966 // Emit visible names into a debug macinfo section.
2967 void DwarfDebug::emitDebugMacInfo() {
2968 if (const MCSection *LineInfo =
2969 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2970 // Start the dwarf macinfo section.
2971 Asm->OutStreamer.SwitchSection(LineInfo);
2975 // DWARF5 Experimental Separate Dwarf emitters.
2977 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2978 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2979 // DW_AT_ranges_base, DW_AT_addr_base.
2980 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2982 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2983 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2984 Asm, this, &SkeletonHolder);
2986 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2987 CU->getNode().getSplitDebugFilename());
2989 // Relocate to the beginning of the addr_base section, else 0 for the
2990 // beginning of the one for this compile unit.
2991 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2992 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2993 DwarfAddrSectionSym);
2995 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2997 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2998 // into an entity. We're using 0, or a NULL label for this.
2999 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
3001 // DW_AT_stmt_list is a offset of line number information for this
3002 // compile unit in debug_line section.
3003 // FIXME: Should handle multiple compile units.
3004 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3005 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
3006 DwarfLineSectionSym);
3008 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
3010 if (!CompilationDir.empty())
3011 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3013 // Flags to let the linker know we have emitted new style pubnames.
3014 if (GenerateGnuPubSections) {
3015 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3016 NewCU->addSectionLabel(
3017 Die, dwarf::DW_AT_GNU_pubnames,
3018 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
3020 NewCU->addSectionDelta(
3021 Die, dwarf::DW_AT_GNU_pubnames,
3022 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
3023 DwarfGnuPubNamesSectionSym);
3025 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3026 NewCU->addSectionLabel(
3027 Die, dwarf::DW_AT_GNU_pubtypes,
3028 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3030 NewCU->addSectionDelta(
3031 Die, dwarf::DW_AT_GNU_pubtypes,
3032 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3033 DwarfGnuPubTypesSectionSym);
3036 // Attribute if we've emitted any ranges and their location for the compile unit.
3037 if (CU->getRangeLists().size()) {
3038 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3039 NewCU->addSectionLabel(
3040 Die, dwarf::DW_AT_GNU_ranges_base,
3041 Asm->GetTempSymbol("gnu_ranges", NewCU->getUniqueID()));
3043 NewCU->addSectionDelta(
3044 Die, dwarf::DW_AT_GNU_ranges_base,
3045 Asm->GetTempSymbol("gnu_ranges", NewCU->getUniqueID()),
3046 DwarfDebugRangeSectionSym);
3049 SkeletonHolder.addUnit(NewCU);
3054 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3055 assert(useSplitDwarf() && "No split dwarf debug info?");
3056 emitAbbrevs(Section, &SkeletonAbbrevs);
3059 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3060 // compile units that would normally be in debug_info.
3061 void DwarfDebug::emitDebugInfoDWO() {
3062 assert(useSplitDwarf() && "No split dwarf debug info?");
3063 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3064 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3065 DwarfAbbrevDWOSectionSym);
3068 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3069 // abbreviations for the .debug_info.dwo section.
3070 void DwarfDebug::emitDebugAbbrevDWO() {
3071 assert(useSplitDwarf() && "No split dwarf?");
3072 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3076 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3077 // string section and is identical in format to traditional .debug_str
3079 void DwarfDebug::emitDebugStrDWO() {
3080 assert(useSplitDwarf() && "No split dwarf?");
3081 const MCSection *OffSec =
3082 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3083 const MCSymbol *StrSym = DwarfStrSectionSym;
3084 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3088 void DwarfDebug::addTypeUnitType(uint16_t Language, DIE *RefDie,
3089 DICompositeType CTy) {
3090 DenseMap<const MDNode *,
3091 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3092 TypeUnits.find(CTy);
3093 SmallVector<DIE *, 8> References;
3094 References.push_back(RefDie);
3095 if (I != TypeUnits.end()) {
3096 if (I->second.second) {
3097 I->second.second->push_back(RefDie);
3101 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3102 TypeUnit *NewTU = new TypeUnit(GlobalCUIndexCount++, UnitDie, Language, Asm,
3104 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3107 // Register the type in the TypeUnits map with a vector of references to be
3108 // populated whenever a reference is required.
3109 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3112 // Construct the type, this may, recursively, require more type units that
3113 // may in turn require this type again - in which case they will add DIEs to
3114 // the References vector.
3115 DIE *Die = NewTU->createTypeDIE(CTy);
3117 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3118 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3119 dwarf::DW_FORM_data8,
3120 DIEHash().computeDIEODRSignature(*Die));
3121 // FIXME: This won't handle circularly referential structures, as the DIE
3122 // may have references to other DIEs still under construction and missing
3123 // their signature. Hashing should walk through the signatures to their
3124 // referenced type, or possibly walk the precomputed hashes of related types
3126 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3128 // Remove the References vector and add the type hash.
3129 I->second.first = Signature;
3130 I->second.second = NULL;
3132 InfoHolder.addUnit(NewTU);
3135 // Populate all the signatures.
3136 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3137 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3138 dwarf::DW_FORM_ref_sig8, I->second.first);