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 DWARF5 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."), cl::init(0));
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
118 /// resolve - Look in the DwarfDebug map for the MDNode that
119 /// corresponds to the reference.
120 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
121 return DD->resolve(Ref);
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType();
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable()) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
181 PrevLabel(NULL), GlobalRangeCount(0),
182 InfoHolder(A, "info_string", DIEValueAllocator),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
186 DwarfStrSectionSym = TextSectionSym = 0;
187 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
188 DwarfAddrSectionSym = 0;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
190 FunctionBeginSym = FunctionEndSym = 0;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
198 if (DwarfAccelTables == Default)
199 HasDwarfAccelTables = IsDarwin;
201 HasDwarfAccelTables = DwarfAccelTables == Enable;
203 if (SplitDwarf == Default)
204 HasSplitDwarf = false;
206 HasSplitDwarf = SplitDwarf == Enable;
208 if (DwarfPubSections == Default)
209 HasDwarfPubSections = !IsDarwin;
211 HasDwarfPubSections = DwarfPubSections == Enable;
213 DwarfVersion = DwarfVersionNumber
215 : getDwarfVersionFromModule(MMI->getModule());
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Switch to the specified MCSection and emit an assembler
224 // temporary label to it if SymbolStem is specified.
225 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
226 const char *SymbolStem = 0) {
227 Asm->OutStreamer.SwitchSection(Section);
231 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
232 Asm->OutStreamer.EmitLabel(TmpSym);
236 DwarfFile::~DwarfFile() {
237 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
242 MCSymbol *DwarfFile::getStringPoolSym() {
243 return Asm->GetTempSymbol(StringPref);
246 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
247 std::pair<MCSymbol *, unsigned> &Entry =
248 StringPool.GetOrCreateValue(Str).getValue();
252 Entry.second = NextStringPoolNumber++;
253 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
257 std::pair<MCSymbol *, unsigned> &Entry =
258 StringPool.GetOrCreateValue(Str).getValue();
262 Entry.second = NextStringPoolNumber++;
263 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
267 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
268 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
271 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
272 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
273 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
275 ++NextAddrPoolNumber;
276 return P.first->second;
279 // Define a unique number for the abbreviation.
281 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations.push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations.size());
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
298 static bool isObjCClass(StringRef Name) {
299 return Name.startswith("+") || Name.startswith("-");
302 static bool hasObjCCategory(StringRef Name) {
303 if (!isObjCClass(Name))
306 return Name.find(") ") != StringRef::npos;
309 static void getObjCClassCategory(StringRef In, StringRef &Class,
310 StringRef &Category) {
311 if (!hasObjCCategory(In)) {
312 Class = In.slice(In.find('[') + 1, In.find(' '));
317 Class = In.slice(In.find('[') + 1, In.find('('));
318 Category = In.slice(In.find('[') + 1, In.find(' '));
322 static StringRef getObjCMethodName(StringRef In) {
323 return In.slice(In.find(' ') + 1, In.find(']'));
326 // Helper for sorting sections into a stable output order.
327 static bool SectionSort(const MCSection *A, const MCSection *B) {
328 std::string LA = (A ? A->getLabelBeginName() : "");
329 std::string LB = (B ? B->getLabelBeginName() : "");
333 // Add the various names to the Dwarf accelerator table names.
334 // TODO: Determine whether or not we should add names for programs
335 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
336 // is only slightly different than the lookup of non-standard ObjC names.
337 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
338 if (!SP.isDefinition())
340 TheU->addAccelName(SP.getName(), Die);
342 // If the linkage name is different than the name, go ahead and output
343 // that as well into the name table.
344 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
345 TheU->addAccelName(SP.getLinkageName(), Die);
347 // If this is an Objective-C selector name add it to the ObjC accelerator
349 if (isObjCClass(SP.getName())) {
350 StringRef Class, Category;
351 getObjCClassCategory(SP.getName(), Class, Category);
352 TheU->addAccelObjC(Class, Die);
354 TheU->addAccelObjC(Category, Die);
355 // Also add the base method name to the name table.
356 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
360 /// isSubprogramContext - Return true if Context is either a subprogram
361 /// or another context nested inside a subprogram.
362 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
365 DIDescriptor D(Context);
366 if (D.isSubprogram())
369 return isSubprogramContext(resolve(DIType(Context).getContext()));
373 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
374 // and DW_AT_high_pc attributes. If there are global variables in this
375 // scope then create and insert DIEs for these variables.
376 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
378 DIE *SPDie = SPCU->getDIE(SP);
380 assert(SPDie && "Unable to find subprogram DIE!");
382 // If we're updating an abstract DIE, then we will be adding the children and
383 // object pointer later on. But what we don't want to do is process the
384 // concrete DIE twice.
385 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
386 // Pick up abstract subprogram DIE.
388 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
391 DISubprogram SPDecl = SP.getFunctionDeclaration();
392 if (!SPDecl.isSubprogram()) {
393 // There is not any need to generate specification DIE for a function
394 // defined at compile unit level. If a function is defined inside another
395 // function then gdb prefers the definition at top level and but does not
396 // expect specification DIE in parent function. So avoid creating
397 // specification DIE for a function defined inside a function.
398 DIScope SPContext = resolve(SP.getContext());
399 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
400 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
401 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
404 DICompositeType SPTy = SP.getType();
405 DIArray Args = SPTy.getTypeArray();
406 uint16_t SPTag = SPTy.getTag();
407 if (SPTag == dwarf::DW_TAG_subroutine_type)
408 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
410 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
411 DIType ATy(Args.getElement(i));
412 SPCU->addType(Arg, ATy);
413 if (ATy.isArtificial())
414 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
415 if (ATy.isObjectPointer())
416 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
418 DIE *SPDeclDie = SPDie;
419 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
420 *SPCU->getUnitDie());
421 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
427 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
429 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
430 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
431 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
433 // Add name to the name table, we do this here because we're guaranteed
434 // to have concrete versions of our DW_TAG_subprogram nodes.
435 addSubprogramNames(SPCU, SP, SPDie);
440 /// Check whether we should create a DIE for the given Scope, return true
441 /// if we don't create a DIE (the corresponding DIE is null).
442 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
443 if (Scope->isAbstractScope())
446 // We don't create a DIE if there is no Range.
447 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
451 if (Ranges.size() > 1)
454 // We don't create a DIE if we have a single Range and the end label
456 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
457 MCSymbol *End = getLabelAfterInsn(RI->second);
461 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
462 dwarf::Attribute A, const MCSymbol *L,
463 const MCSymbol *Sec) {
464 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
465 U->addSectionLabel(D, A, L);
467 U->addSectionDelta(D, A, L, Sec);
470 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *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 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
475 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
476 DwarfDebugRangeSectionSym);
478 RangeSpanList List(RangeSym);
479 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
482 RangeSpan Span(getLabelBeforeInsn(RI->first),
483 getLabelAfterInsn(RI->second));
484 List.addRange(llvm_move(Span));
487 // Add the range list to the set of ranges to be emitted.
488 TheCU->addRangeList(llvm_move(List));
491 // Construct new DW_TAG_lexical_block for this scope and attach
492 // DW_AT_low_pc/DW_AT_high_pc labels.
493 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
494 LexicalScope *Scope) {
495 if (isLexicalScopeDIENull(Scope))
498 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
499 if (Scope->isAbstractScope())
502 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
504 // If we have multiple ranges, emit them into the range section.
505 if (ScopeRanges.size() > 1) {
506 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
510 // Construct the address range for this DIE.
511 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
512 MCSymbol *Start = getLabelBeforeInsn(RI->first);
513 MCSymbol *End = getLabelAfterInsn(RI->second);
514 assert(End && "End label should not be null!");
516 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
517 assert(End->isDefined() && "Invalid end label for an inlined scope!");
519 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
520 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
525 // This scope represents inlined body of a function. Construct DIE to
526 // represent this concrete inlined copy of the function.
527 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
528 LexicalScope *Scope) {
529 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
530 assert(!ScopeRanges.empty() &&
531 "LexicalScope does not have instruction markers!");
533 if (!Scope->getScopeNode())
535 DIScope DS(Scope->getScopeNode());
536 DISubprogram InlinedSP = getDISubprogram(DS);
537 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
539 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
543 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
544 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
546 // If we have multiple ranges, emit them into the range section.
547 if (ScopeRanges.size() > 1)
548 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
550 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
551 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
552 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
554 if (StartLabel == 0 || EndLabel == 0)
555 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
557 assert(StartLabel->isDefined() &&
558 "Invalid starting label for an inlined scope!");
559 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
561 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
562 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
565 InlinedSubprogramDIEs.insert(OriginDIE);
567 // Add the call site information to the DIE.
568 DILocation DL(Scope->getInlinedAt());
569 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
570 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
571 TheCU->getUniqueID()));
572 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
574 // Add name to the name table, we do this here because we're guaranteed
575 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
576 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
581 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
583 SmallVectorImpl<DIE *> &Children) {
584 DIE *ObjectPointer = NULL;
586 // Collect arguments for current function.
587 if (LScopes.isCurrentFunctionScope(Scope))
588 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
589 if (DbgVariable *ArgDV = CurrentFnArguments[i])
591 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
592 Children.push_back(Arg);
593 if (ArgDV->isObjectPointer())
597 // Collect lexical scope children first.
598 const SmallVectorImpl<DbgVariable *> &Variables =
599 ScopeVariables.lookup(Scope);
600 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
601 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
602 Scope->isAbstractScope())) {
603 Children.push_back(Variable);
604 if (Variables[i]->isObjectPointer())
605 ObjectPointer = Variable;
607 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
608 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
609 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
610 Children.push_back(Nested);
611 return ObjectPointer;
614 // Construct a DIE for this scope.
615 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
616 LexicalScope *Scope) {
617 if (!Scope || !Scope->getScopeNode())
620 DIScope DS(Scope->getScopeNode());
622 SmallVector<DIE *, 8> Children;
623 DIE *ObjectPointer = NULL;
624 bool ChildrenCreated = false;
626 // We try to create the scope DIE first, then the children DIEs. This will
627 // avoid creating un-used children then removing them later when we find out
628 // the scope DIE is null.
629 DIE *ScopeDIE = NULL;
630 if (Scope->getInlinedAt())
631 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
632 else if (DS.isSubprogram()) {
633 ProcessedSPNodes.insert(DS);
634 if (Scope->isAbstractScope()) {
635 ScopeDIE = TheCU->getDIE(DS);
636 // Note down abstract DIE.
638 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
640 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
642 // Early exit when we know the scope DIE is going to be null.
643 if (isLexicalScopeDIENull(Scope))
646 // We create children here when we know the scope DIE is not going to be
647 // null and the children will be added to the scope DIE.
648 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
649 ChildrenCreated = true;
651 // There is no need to emit empty lexical block DIE.
652 std::pair<ImportedEntityMap::const_iterator,
653 ImportedEntityMap::const_iterator> Range =
655 ScopesWithImportedEntities.begin(),
656 ScopesWithImportedEntities.end(),
657 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
659 if (Children.empty() && Range.first == Range.second)
661 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
662 assert(ScopeDIE && "Scope DIE should not be null.");
663 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
665 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
669 assert(Children.empty() &&
670 "We create children only when the scope DIE is not null.");
673 if (!ChildrenCreated)
674 // We create children when the scope DIE is not null.
675 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
678 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
681 ScopeDIE->addChild(*I);
683 if (DS.isSubprogram() && ObjectPointer != NULL)
684 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
689 // Look up the source id with the given directory and source file names.
690 // If none currently exists, create a new id and insert it in the
691 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
693 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
695 // If we use .loc in assembly, we can't separate .file entries according to
696 // compile units. Thus all files will belong to the default compile unit.
698 // FIXME: add a better feature test than hasRawTextSupport. Even better,
699 // extend .file to support this.
700 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
703 // If FE did not provide a file name, then assume stdin.
704 if (FileName.empty())
705 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
707 // TODO: this might not belong here. See if we can factor this better.
708 if (DirName == CompilationDir)
711 // FileIDCUMap stores the current ID for the given compile unit.
712 unsigned SrcId = FileIDCUMap[CUID] + 1;
714 // We look up the CUID/file/dir by concatenating them with a zero byte.
715 SmallString<128> NamePair;
716 NamePair += utostr(CUID);
719 NamePair += '\0'; // Zero bytes are not allowed in paths.
720 NamePair += FileName;
722 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
723 if (Ent.getValue() != SrcId)
724 return Ent.getValue();
726 FileIDCUMap[CUID] = SrcId;
727 // Print out a .file directive to specify files for .loc directives.
728 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
733 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
734 if (!GenerateGnuPubSections)
737 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
738 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
739 DwarfGnuPubNamesSectionSym);
741 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
742 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
743 DwarfGnuPubTypesSectionSym);
746 // Create new DwarfCompileUnit for the given metadata node with tag
747 // DW_TAG_compile_unit.
748 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
749 StringRef FN = DIUnit.getFilename();
750 CompilationDir = DIUnit.getDirectory();
752 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
753 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
754 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
755 InfoHolder.addUnit(NewCU);
757 FileIDCUMap[NewCU->getUniqueID()] = 0;
758 // Call this to emit a .file directive if it wasn't emitted for the source
759 // file this CU comes from yet.
760 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
762 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
763 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
764 DIUnit.getLanguage());
765 NewCU->addString(Die, dwarf::DW_AT_name, FN);
767 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
768 // into an entity. We're using 0 (or a NULL label) for this. For
769 // split dwarf it's in the skeleton CU so omit it here.
770 if (!useSplitDwarf())
771 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
773 // Define start line table label for each Compile Unit.
774 MCSymbol *LineTableStartSym =
775 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
776 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
777 NewCU->getUniqueID());
779 // Use a single line table if we are using .loc and generating assembly.
781 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
782 (NewCU->getUniqueID() == 0);
784 if (!useSplitDwarf()) {
785 // DW_AT_stmt_list is a offset of line number information for this
786 // compile unit in debug_line section. For split dwarf this is
787 // left in the skeleton CU and so not included.
788 // The line table entries are not always emitted in assembly, so it
789 // is not okay to use line_table_start here.
790 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
791 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
792 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
793 : LineTableStartSym);
794 else if (UseTheFirstCU)
795 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
797 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
798 DwarfLineSectionSym);
800 // If we're using split dwarf the compilation dir is going to be in the
801 // skeleton CU and so we don't need to duplicate it here.
802 if (!CompilationDir.empty())
803 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
805 addGnuPubAttributes(NewCU, Die);
808 if (DIUnit.isOptimized())
809 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
811 StringRef Flags = DIUnit.getFlags();
813 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
815 if (unsigned RVer = DIUnit.getRunTimeVersion())
816 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
817 dwarf::DW_FORM_data1, RVer);
823 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
824 : Asm->getObjFileLowering().getDwarfInfoSection(),
825 // FIXME: This is subtle (using the info section even when
826 // this CU is in the dwo section) and necessary for the
827 // current arange code - ideally it should iterate
828 // skeleton units, not full units, if it's going to reference skeletons
829 DwarfInfoSectionSym);
831 CUMap.insert(std::make_pair(DIUnit, NewCU));
832 CUDieMap.insert(std::make_pair(Die, NewCU));
836 // Construct subprogram DIE.
837 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
839 // FIXME: We should only call this routine once, however, during LTO if a
840 // program is defined in multiple CUs we could end up calling it out of
841 // beginModule as we walk the CUs.
843 DwarfCompileUnit *&CURef = SPMap[N];
849 if (!SP.isDefinition())
850 // This is a method declaration which will be handled while constructing
854 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
856 // Expose as a global name.
857 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
860 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
862 DIImportedEntity Module(N);
863 if (!Module.Verify())
865 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
866 constructImportedEntityDIE(TheCU, Module, D);
869 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
870 const MDNode *N, DIE *Context) {
871 DIImportedEntity Module(N);
872 if (!Module.Verify())
874 return constructImportedEntityDIE(TheCU, Module, Context);
877 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
878 const DIImportedEntity &Module,
880 assert(Module.Verify() &&
881 "Use one of the MDNode * overloads to handle invalid metadata");
882 assert(Context && "Should always have a context for an imported_module");
883 DIE *IMDie = new DIE(Module.getTag());
884 TheCU->insertDIE(Module, IMDie);
886 DIDescriptor Entity = Module.getEntity();
887 if (Entity.isNameSpace())
888 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
889 else if (Entity.isSubprogram())
890 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
891 else if (Entity.isType())
892 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
894 EntityDie = TheCU->getDIE(Entity);
895 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
896 Module.getContext().getDirectory(),
897 TheCU->getUniqueID());
898 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
899 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
900 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
901 StringRef Name = Module.getName();
903 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
904 Context->addChild(IMDie);
907 // Emit all Dwarf sections that should come prior to the content. Create
908 // global DIEs and emit initial debug info sections. This is invoked by
909 // the target AsmPrinter.
910 void DwarfDebug::beginModule() {
911 if (DisableDebugInfoPrinting)
914 const Module *M = MMI->getModule();
916 // If module has named metadata anchors then use them, otherwise scan the
917 // module using debug info finder to collect debug info.
918 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
921 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
923 // Emit initial sections so we can reference labels later.
926 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
927 DICompileUnit CUNode(CU_Nodes->getOperand(i));
928 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
929 DIArray ImportedEntities = CUNode.getImportedEntities();
930 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
931 ScopesWithImportedEntities.push_back(std::make_pair(
932 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
933 ImportedEntities.getElement(i)));
934 std::sort(ScopesWithImportedEntities.begin(),
935 ScopesWithImportedEntities.end(), less_first());
936 DIArray GVs = CUNode.getGlobalVariables();
937 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
938 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
939 DIArray SPs = CUNode.getSubprograms();
940 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
941 constructSubprogramDIE(CU, SPs.getElement(i));
942 DIArray EnumTypes = CUNode.getEnumTypes();
943 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
944 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
945 DIArray RetainedTypes = CUNode.getRetainedTypes();
946 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
947 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
948 // Emit imported_modules last so that the relevant context is already
950 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
951 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
954 // Tell MMI that we have debug info.
955 MMI->setDebugInfoAvailability(true);
957 // Prime section data.
958 SectionMap[Asm->getObjFileLowering().getTextSection()];
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 void DwarfDebug::computeInlinedDIEs() {
963 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
964 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
965 AE = InlinedSubprogramDIEs.end();
968 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
970 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
971 AE = AbstractSPDies.end();
973 DIE *ISP = AI->second;
974 if (InlinedSubprogramDIEs.count(ISP))
976 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
980 // Collect info for variables that were optimized out.
981 void DwarfDebug::collectDeadVariables() {
982 const Module *M = MMI->getModule();
984 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
985 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
986 DICompileUnit TheCU(CU_Nodes->getOperand(i));
987 DIArray Subprograms = TheCU.getSubprograms();
988 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
989 DISubprogram SP(Subprograms.getElement(i));
990 if (ProcessedSPNodes.count(SP) != 0)
992 if (!SP.isSubprogram())
994 if (!SP.isDefinition())
996 DIArray Variables = SP.getVariables();
997 if (Variables.getNumElements() == 0)
1000 // Construct subprogram DIE and add variables DIEs.
1001 DwarfCompileUnit *SPCU =
1002 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
1003 assert(SPCU && "Unable to find Compile Unit!");
1004 // FIXME: See the comment in constructSubprogramDIE about duplicate
1006 constructSubprogramDIE(SPCU, SP);
1007 DIE *SPDIE = SPCU->getDIE(SP);
1008 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1009 DIVariable DV(Variables.getElement(vi));
1010 if (!DV.isVariable())
1012 DbgVariable NewVar(DV, NULL, this);
1013 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1014 SPDIE->addChild(VariableDIE);
1021 // Type Signature [7.27] and ODR Hash code.
1023 /// \brief Grabs the string in whichever attribute is passed in and returns
1024 /// a reference to it. Returns "" if the attribute doesn't exist.
1025 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1026 DIEValue *V = Die->findAttribute(Attr);
1028 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1029 return S->getString();
1031 return StringRef("");
1034 /// Return true if the current DIE is contained within an anonymous namespace.
1035 static bool isContainedInAnonNamespace(DIE *Die) {
1036 DIE *Parent = Die->getParent();
1039 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1040 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1042 Parent = Parent->getParent();
1048 /// Test if the current CU language is C++ and that we have
1049 /// a named type that is not contained in an anonymous namespace.
1050 static bool shouldAddODRHash(DwarfTypeUnit *CU, DIE *Die) {
1051 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1052 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1053 !isContainedInAnonNamespace(Die);
1056 void DwarfDebug::finalizeModuleInfo() {
1057 // Collect info for variables that were optimized out.
1058 collectDeadVariables();
1060 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1061 computeInlinedDIEs();
1063 // Handle anything that needs to be done on a per-unit basis after
1064 // all other generation.
1065 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1066 E = getUnits().end();
1068 DwarfUnit *TheU = *I;
1069 // Emit DW_AT_containing_type attribute to connect types with their
1070 // vtable holding type.
1071 TheU->constructContainingTypeDIEs();
1073 // If we're splitting the dwarf out now that we've got the entire
1074 // CU then construct a skeleton CU based upon it.
1075 if (useSplitDwarf() &&
1076 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1078 if (GenerateCUHash) {
1080 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1082 // This should be a unique identifier when we want to build .dwp files.
1083 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1084 dwarf::DW_FORM_data8, ID);
1085 // Now construct the skeleton CU associated.
1086 DwarfCompileUnit *SkCU =
1087 constructSkeletonCU(static_cast<DwarfCompileUnit *>(TheU));
1088 // This should be a unique identifier when we want to build .dwp files.
1089 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1090 dwarf::DW_FORM_data8, ID);
1094 // Compute DIE offsets and sizes.
1095 InfoHolder.computeSizeAndOffsets();
1096 if (useSplitDwarf())
1097 SkeletonHolder.computeSizeAndOffsets();
1100 void DwarfDebug::endSections() {
1101 // Filter labels by section.
1102 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1103 const SymbolCU &SCU = ArangeLabels[n];
1104 if (SCU.Sym->isInSection()) {
1105 // Make a note of this symbol and it's section.
1106 const MCSection *Section = &SCU.Sym->getSection();
1107 if (!Section->getKind().isMetadata())
1108 SectionMap[Section].push_back(SCU);
1110 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1111 // appear in the output. This sucks as we rely on sections to build
1112 // arange spans. We can do it without, but it's icky.
1113 SectionMap[NULL].push_back(SCU);
1117 // Build a list of sections used.
1118 std::vector<const MCSection *> Sections;
1119 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1121 const MCSection *Section = it->first;
1122 Sections.push_back(Section);
1125 // Sort the sections into order.
1126 // This is only done to ensure consistent output order across different runs.
1127 std::sort(Sections.begin(), Sections.end(), SectionSort);
1129 // Add terminating symbols for each section.
1130 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1131 const MCSection *Section = Sections[ID];
1132 MCSymbol *Sym = NULL;
1135 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1136 // if we know the section name up-front. For user-created sections, the
1138 // label may not be valid to use as a label. (section names can use a
1140 // set of characters on some systems)
1141 Sym = Asm->GetTempSymbol("debug_end", ID);
1142 Asm->OutStreamer.SwitchSection(Section);
1143 Asm->OutStreamer.EmitLabel(Sym);
1146 // Insert a final terminator.
1147 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1151 // Emit all Dwarf sections that should come after the content.
1152 void DwarfDebug::endModule() {
1159 // End any existing sections.
1160 // TODO: Does this need to happen?
1163 // Finalize the debug info for the module.
1164 finalizeModuleInfo();
1168 // Emit all the DIEs into a debug info section.
1171 // Corresponding abbreviations into a abbrev section.
1172 emitAbbreviations();
1174 // Emit info into a debug loc section.
1177 // Emit info into a debug aranges section.
1180 // Emit info into a debug ranges section.
1183 // Emit info into a debug macinfo section.
1186 if (useSplitDwarf()) {
1189 emitDebugAbbrevDWO();
1190 // Emit DWO addresses.
1191 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1194 // Emit info into the dwarf accelerator table sections.
1195 if (useDwarfAccelTables()) {
1198 emitAccelNamespaces();
1202 // Emit the pubnames and pubtypes sections if requested.
1203 if (HasDwarfPubSections) {
1204 emitDebugPubNames(GenerateGnuPubSections);
1205 emitDebugPubTypes(GenerateGnuPubSections);
1211 // Reset these for the next Module if we have one.
1215 // Find abstract variable, if any, associated with Var.
1216 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1217 DebugLoc ScopeLoc) {
1218 LLVMContext &Ctx = DV->getContext();
1219 // More then one inlined variable corresponds to one abstract variable.
1220 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1221 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1223 return AbsDbgVariable;
1225 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1229 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1230 addScopeVariable(Scope, AbsDbgVariable);
1231 AbstractVariables[Var] = AbsDbgVariable;
1232 return AbsDbgVariable;
1235 // If Var is a current function argument then add it to CurrentFnArguments list.
1236 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1237 if (!LScopes.isCurrentFunctionScope(Scope))
1239 DIVariable DV = Var->getVariable();
1240 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1242 unsigned ArgNo = DV.getArgNumber();
1246 size_t Size = CurrentFnArguments.size();
1248 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1249 // llvm::Function argument size is not good indicator of how many
1250 // arguments does the function have at source level.
1252 CurrentFnArguments.resize(ArgNo * 2);
1253 CurrentFnArguments[ArgNo - 1] = Var;
1257 // Collect variable information from side table maintained by MMI.
1258 void DwarfDebug::collectVariableInfoFromMMITable(
1259 SmallPtrSet<const MDNode *, 16> &Processed) {
1260 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1261 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1264 const MDNode *Var = VI->first;
1267 Processed.insert(Var);
1269 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1271 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1273 // If variable scope is not found then skip this variable.
1277 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1278 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1279 RegVar->setFrameIndex(VP.first);
1280 if (!addCurrentFnArgument(RegVar, Scope))
1281 addScopeVariable(Scope, RegVar);
1283 AbsDbgVariable->setFrameIndex(VP.first);
1287 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1289 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1290 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1291 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1292 MI->getOperand(0).getReg() &&
1293 (MI->getOperand(1).isImm() ||
1294 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1297 // Get .debug_loc entry for the instruction range starting at MI.
1298 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1299 const MCSymbol *FLabel,
1300 const MCSymbol *SLabel,
1301 const MachineInstr *MI) {
1302 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1304 assert(MI->getNumOperands() == 3);
1305 if (MI->getOperand(0).isReg()) {
1306 MachineLocation MLoc;
1307 // If the second operand is an immediate, this is a
1308 // register-indirect address.
1309 if (!MI->getOperand(1).isImm())
1310 MLoc.set(MI->getOperand(0).getReg());
1312 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1313 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1315 if (MI->getOperand(0).isImm())
1316 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1317 if (MI->getOperand(0).isFPImm())
1318 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1319 if (MI->getOperand(0).isCImm())
1320 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1322 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1325 // Find variables for each lexical scope.
1327 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1329 // Grab the variable info that was squirreled away in the MMI side-table.
1330 collectVariableInfoFromMMITable(Processed);
1332 for (SmallVectorImpl<const MDNode *>::const_iterator
1333 UVI = UserVariables.begin(),
1334 UVE = UserVariables.end();
1335 UVI != UVE; ++UVI) {
1336 const MDNode *Var = *UVI;
1337 if (Processed.count(Var))
1340 // History contains relevant DBG_VALUE instructions for Var and instructions
1342 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1343 if (History.empty())
1345 const MachineInstr *MInsn = History.front();
1348 LexicalScope *Scope = NULL;
1349 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1350 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1351 Scope = LScopes.getCurrentFunctionScope();
1352 else if (MDNode *IA = DV.getInlinedAt())
1353 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1355 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1356 // If variable scope is not found then skip this variable.
1360 Processed.insert(DV);
1361 assert(MInsn->isDebugValue() && "History must begin with debug value");
1362 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1363 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1364 if (!addCurrentFnArgument(RegVar, Scope))
1365 addScopeVariable(Scope, RegVar);
1367 AbsVar->setMInsn(MInsn);
1369 // Simplify ranges that are fully coalesced.
1370 if (History.size() <= 1 ||
1371 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1372 RegVar->setMInsn(MInsn);
1376 // Handle multiple DBG_VALUE instructions describing one variable.
1377 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1379 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1380 HI = History.begin(),
1383 const MachineInstr *Begin = *HI;
1384 assert(Begin->isDebugValue() && "Invalid History entry");
1386 // Check if DBG_VALUE is truncating a range.
1387 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1388 !Begin->getOperand(0).getReg())
1391 // Compute the range for a register location.
1392 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1393 const MCSymbol *SLabel = 0;
1396 // If Begin is the last instruction in History then its value is valid
1397 // until the end of the function.
1398 SLabel = FunctionEndSym;
1400 const MachineInstr *End = HI[1];
1401 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1402 << "\t" << *Begin << "\t" << *End << "\n");
1403 if (End->isDebugValue())
1404 SLabel = getLabelBeforeInsn(End);
1406 // End is a normal instruction clobbering the range.
1407 SLabel = getLabelAfterInsn(End);
1408 assert(SLabel && "Forgot label after clobber instruction");
1413 // The value is valid until the next DBG_VALUE or clobber.
1414 DotDebugLocEntries.push_back(
1415 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1417 DotDebugLocEntries.push_back(DotDebugLocEntry());
1420 // Collect info for variables that were optimized out.
1421 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1422 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1423 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1424 DIVariable DV(Variables.getElement(i));
1425 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1427 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1428 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1432 // Return Label preceding the instruction.
1433 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1434 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1435 assert(Label && "Didn't insert label before instruction");
1439 // Return Label immediately following the instruction.
1440 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1441 return LabelsAfterInsn.lookup(MI);
1444 // Process beginning of an instruction.
1445 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1448 // Check if source location changes, but ignore DBG_VALUE locations.
1449 if (!MI->isDebugValue()) {
1450 DebugLoc DL = MI->getDebugLoc();
1451 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1454 if (DL == PrologEndLoc) {
1455 Flags |= DWARF2_FLAG_PROLOGUE_END;
1456 PrologEndLoc = DebugLoc();
1458 if (PrologEndLoc.isUnknown())
1459 Flags |= DWARF2_FLAG_IS_STMT;
1461 if (!DL.isUnknown()) {
1462 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1463 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1465 recordSourceLine(0, 0, 0, 0);
1469 // Insert labels where requested.
1470 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1471 LabelsBeforeInsn.find(MI);
1474 if (I == LabelsBeforeInsn.end())
1477 // Label already assigned.
1482 PrevLabel = MMI->getContext().CreateTempSymbol();
1483 Asm->OutStreamer.EmitLabel(PrevLabel);
1485 I->second = PrevLabel;
1488 // Process end of an instruction.
1489 void DwarfDebug::endInstruction() {
1491 // Don't create a new label after DBG_VALUE instructions.
1492 // They don't generate code.
1493 if (!CurMI->isDebugValue())
1496 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1497 LabelsAfterInsn.find(CurMI);
1501 if (I == LabelsAfterInsn.end())
1504 // Label already assigned.
1508 // We need a label after this instruction.
1510 PrevLabel = MMI->getContext().CreateTempSymbol();
1511 Asm->OutStreamer.EmitLabel(PrevLabel);
1513 I->second = PrevLabel;
1516 // Each LexicalScope has first instruction and last instruction to mark
1517 // beginning and end of a scope respectively. Create an inverse map that list
1518 // scopes starts (and ends) with an instruction. One instruction may start (or
1519 // end) multiple scopes. Ignore scopes that are not reachable.
1520 void DwarfDebug::identifyScopeMarkers() {
1521 SmallVector<LexicalScope *, 4> WorkList;
1522 WorkList.push_back(LScopes.getCurrentFunctionScope());
1523 while (!WorkList.empty()) {
1524 LexicalScope *S = WorkList.pop_back_val();
1526 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1527 if (!Children.empty())
1528 for (SmallVectorImpl<LexicalScope *>::const_iterator
1529 SI = Children.begin(),
1530 SE = Children.end();
1532 WorkList.push_back(*SI);
1534 if (S->isAbstractScope())
1537 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1540 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1543 assert(RI->first && "InsnRange does not have first instruction!");
1544 assert(RI->second && "InsnRange does not have second instruction!");
1545 requestLabelBeforeInsn(RI->first);
1546 requestLabelAfterInsn(RI->second);
1551 // Get MDNode for DebugLoc's scope.
1552 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1553 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1554 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1555 return DL.getScope(Ctx);
1558 // Walk up the scope chain of given debug loc and find line number info
1559 // for the function.
1560 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1561 const MDNode *Scope = getScopeNode(DL, Ctx);
1562 DISubprogram SP = getDISubprogram(Scope);
1563 if (SP.isSubprogram()) {
1564 // Check for number of operands since the compatibility is
1566 if (SP->getNumOperands() > 19)
1567 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1569 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1575 // Gather pre-function debug information. Assumes being called immediately
1576 // after the function entry point has been emitted.
1577 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1580 // If there's no debug info for the function we're not going to do anything.
1581 if (!MMI->hasDebugInfo())
1584 // Grab the lexical scopes for the function, if we don't have any of those
1585 // then we're not going to be able to do anything.
1586 LScopes.initialize(*MF);
1587 if (LScopes.empty())
1590 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1592 // Make sure that each lexical scope will have a begin/end label.
1593 identifyScopeMarkers();
1595 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1596 // belongs to so that we add to the correct per-cu line table in the
1598 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1599 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1600 assert(TheCU && "Unable to find compile unit!");
1601 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1602 // Use a single line table if we are using .loc and generating assembly.
1603 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1605 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1607 // Emit a label for the function so that we have a beginning address.
1608 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1609 // Assumes in correct section after the entry point.
1610 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1612 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1613 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1614 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1616 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1618 bool AtBlockEntry = true;
1619 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1621 const MachineInstr *MI = II;
1623 if (MI->isDebugValue()) {
1624 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1626 // Keep track of user variables.
1628 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1630 // Variable is in a register, we need to check for clobbers.
1631 if (isDbgValueInDefinedReg(MI))
1632 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1634 // Check the history of this variable.
1635 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1636 if (History.empty()) {
1637 UserVariables.push_back(Var);
1638 // The first mention of a function argument gets the FunctionBeginSym
1639 // label, so arguments are visible when breaking at function entry.
1641 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1642 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1643 LabelsBeforeInsn[MI] = FunctionBeginSym;
1645 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1646 const MachineInstr *Prev = History.back();
1647 if (Prev->isDebugValue()) {
1648 // Coalesce identical entries at the end of History.
1649 if (History.size() >= 2 &&
1650 Prev->isIdenticalTo(History[History.size() - 2])) {
1651 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1652 << "\t" << *Prev << "\t"
1653 << *History[History.size() - 2] << "\n");
1657 // Terminate old register assignments that don't reach MI;
1658 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1659 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1660 isDbgValueInDefinedReg(Prev)) {
1661 // Previous register assignment needs to terminate at the end of
1663 MachineBasicBlock::const_iterator LastMI =
1664 PrevMBB->getLastNonDebugInstr();
1665 if (LastMI == PrevMBB->end()) {
1666 // Drop DBG_VALUE for empty range.
1667 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1668 << "\t" << *Prev << "\n");
1670 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1671 // Terminate after LastMI.
1672 History.push_back(LastMI);
1676 History.push_back(MI);
1678 // Not a DBG_VALUE instruction.
1680 AtBlockEntry = false;
1682 // First known non-DBG_VALUE and non-frame setup location marks
1683 // the beginning of the function body.
1684 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1685 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1686 PrologEndLoc = MI->getDebugLoc();
1688 // Check if the instruction clobbers any registers with debug vars.
1689 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1690 MOE = MI->operands_end();
1691 MOI != MOE; ++MOI) {
1692 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1694 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1697 const MDNode *Var = LiveUserVar[Reg];
1700 // Reg is now clobbered.
1701 LiveUserVar[Reg] = 0;
1703 // Was MD last defined by a DBG_VALUE referring to Reg?
1704 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1705 if (HistI == DbgValues.end())
1707 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1708 if (History.empty())
1710 const MachineInstr *Prev = History.back();
1711 // Sanity-check: Register assignments are terminated at the end of
1713 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1715 // Is the variable still in Reg?
1716 if (!isDbgValueInDefinedReg(Prev) ||
1717 Prev->getOperand(0).getReg() != Reg)
1719 // Var is clobbered. Make sure the next instruction gets a label.
1720 History.push_back(MI);
1727 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1729 SmallVectorImpl<const MachineInstr *> &History = I->second;
1730 if (History.empty())
1733 // Make sure the final register assignments are terminated.
1734 const MachineInstr *Prev = History.back();
1735 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1736 const MachineBasicBlock *PrevMBB = Prev->getParent();
1737 MachineBasicBlock::const_iterator LastMI =
1738 PrevMBB->getLastNonDebugInstr();
1739 if (LastMI == PrevMBB->end())
1740 // Drop DBG_VALUE for empty range.
1742 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1743 // Terminate after LastMI.
1744 History.push_back(LastMI);
1747 // Request labels for the full history.
1748 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1749 const MachineInstr *MI = History[i];
1750 if (MI->isDebugValue())
1751 requestLabelBeforeInsn(MI);
1753 requestLabelAfterInsn(MI);
1757 PrevInstLoc = DebugLoc();
1758 PrevLabel = FunctionBeginSym;
1760 // Record beginning of function.
1761 if (!PrologEndLoc.isUnknown()) {
1762 DebugLoc FnStartDL =
1763 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1765 FnStartDL.getLine(), FnStartDL.getCol(),
1766 FnStartDL.getScope(MF->getFunction()->getContext()),
1767 // We'd like to list the prologue as "not statements" but GDB behaves
1768 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1769 DWARF2_FLAG_IS_STMT);
1773 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1774 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1775 DIVariable DV = Var->getVariable();
1776 // Variables with positive arg numbers are parameters.
1777 if (unsigned ArgNum = DV.getArgNumber()) {
1778 // Keep all parameters in order at the start of the variable list to ensure
1779 // function types are correct (no out-of-order parameters)
1781 // This could be improved by only doing it for optimized builds (unoptimized
1782 // builds have the right order to begin with), searching from the back (this
1783 // would catch the unoptimized case quickly), or doing a binary search
1784 // rather than linear search.
1785 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1786 while (I != Vars.end()) {
1787 unsigned CurNum = (*I)->getVariable().getArgNumber();
1788 // A local (non-parameter) variable has been found, insert immediately
1792 // A later indexed parameter has been found, insert immediately before it.
1793 if (CurNum > ArgNum)
1797 Vars.insert(I, Var);
1801 Vars.push_back(Var);
1804 // Gather and emit post-function debug information.
1805 void DwarfDebug::endFunction(const MachineFunction *MF) {
1806 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1807 // though the beginFunction may not be called at all.
1808 // We should handle both cases.
1812 assert(CurFn == MF);
1815 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1820 // Define end label for subprogram.
1821 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1822 // Assumes in correct section after the entry point.
1823 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1824 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1825 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1827 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1828 collectVariableInfo(ProcessedVars);
1830 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1831 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1832 assert(TheCU && "Unable to find compile unit!");
1834 // Construct abstract scopes.
1835 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1836 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1837 LexicalScope *AScope = AList[i];
1838 DISubprogram SP(AScope->getScopeNode());
1839 if (SP.isSubprogram()) {
1840 // Collect info for variables that were optimized out.
1841 DIArray Variables = SP.getVariables();
1842 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1843 DIVariable DV(Variables.getElement(i));
1844 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1846 // Check that DbgVariable for DV wasn't created earlier, when
1847 // findAbstractVariable() was called for inlined instance of DV.
1848 LLVMContext &Ctx = DV->getContext();
1849 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1850 if (AbstractVariables.lookup(CleanDV))
1852 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1853 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1856 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1857 constructScopeDIE(TheCU, AScope);
1860 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1862 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1863 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1866 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1867 E = ScopeVariables.end();
1869 DeleteContainerPointers(I->second);
1870 ScopeVariables.clear();
1871 DeleteContainerPointers(CurrentFnArguments);
1872 UserVariables.clear();
1874 AbstractVariables.clear();
1875 LabelsBeforeInsn.clear();
1876 LabelsAfterInsn.clear();
1881 // Register a source line with debug info. Returns the unique label that was
1882 // emitted and which provides correspondence to the source line list.
1883 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1889 DIDescriptor Scope(S);
1891 if (Scope.isCompileUnit()) {
1892 DICompileUnit CU(S);
1893 Fn = CU.getFilename();
1894 Dir = CU.getDirectory();
1895 } else if (Scope.isFile()) {
1897 Fn = F.getFilename();
1898 Dir = F.getDirectory();
1899 } else if (Scope.isSubprogram()) {
1901 Fn = SP.getFilename();
1902 Dir = SP.getDirectory();
1903 } else if (Scope.isLexicalBlockFile()) {
1904 DILexicalBlockFile DBF(S);
1905 Fn = DBF.getFilename();
1906 Dir = DBF.getDirectory();
1907 } else if (Scope.isLexicalBlock()) {
1908 DILexicalBlock DB(S);
1909 Fn = DB.getFilename();
1910 Dir = DB.getDirectory();
1912 llvm_unreachable("Unexpected scope info");
1914 Src = getOrCreateSourceID(
1915 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1917 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1920 //===----------------------------------------------------------------------===//
1922 //===----------------------------------------------------------------------===//
1924 // Compute the size and offset of a DIE. The offset is relative to start of the
1925 // CU. It returns the offset after laying out the DIE.
1926 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1927 // Get the children.
1928 const std::vector<DIE *> &Children = Die->getChildren();
1930 // Record the abbreviation.
1931 assignAbbrevNumber(Die->getAbbrev());
1933 // Get the abbreviation for this DIE.
1934 const DIEAbbrev &Abbrev = Die->getAbbrev();
1937 Die->setOffset(Offset);
1939 // Start the size with the size of abbreviation code.
1940 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1942 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1943 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1945 // Size the DIE attribute values.
1946 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1947 // Size attribute value.
1948 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1950 // Size the DIE children if any.
1951 if (!Children.empty()) {
1952 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1953 "Children flag not set");
1955 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1956 Offset = computeSizeAndOffset(Children[j], Offset);
1958 // End of children marker.
1959 Offset += sizeof(int8_t);
1962 Die->setSize(Offset - Die->getOffset());
1966 // Compute the size and offset for each DIE.
1967 void DwarfFile::computeSizeAndOffsets() {
1968 // Offset from the first CU in the debug info section is 0 initially.
1969 unsigned SecOffset = 0;
1971 // Iterate over each compile unit and set the size and offsets for each
1972 // DIE within each compile unit. All offsets are CU relative.
1973 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1976 (*I)->setDebugInfoOffset(SecOffset);
1978 // CU-relative offset is reset to 0 here.
1979 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1980 (*I)->getHeaderSize(); // Unit-specific headers
1982 // EndOffset here is CU-relative, after laying out
1983 // all of the CU DIE.
1984 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1985 SecOffset += EndOffset;
1989 // Emit initial Dwarf sections with a label at the start of each one.
1990 void DwarfDebug::emitSectionLabels() {
1991 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1993 // Dwarf sections base addresses.
1994 DwarfInfoSectionSym =
1995 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1996 DwarfAbbrevSectionSym =
1997 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1998 if (useSplitDwarf())
1999 DwarfAbbrevDWOSectionSym = emitSectionSym(
2000 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
2001 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
2003 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2004 emitSectionSym(Asm, MacroInfo);
2006 DwarfLineSectionSym =
2007 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2008 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2009 if (GenerateGnuPubSections) {
2010 DwarfGnuPubNamesSectionSym =
2011 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2012 DwarfGnuPubTypesSectionSym =
2013 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2014 } else if (HasDwarfPubSections) {
2015 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2016 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2019 DwarfStrSectionSym =
2020 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2021 if (useSplitDwarf()) {
2022 DwarfStrDWOSectionSym =
2023 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2024 DwarfAddrSectionSym =
2025 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2027 DwarfDebugRangeSectionSym =
2028 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2030 DwarfDebugLocSectionSym =
2031 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2033 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2034 emitSectionSym(Asm, TLOF.getDataSection());
2037 // Recursively emits a debug information entry.
2038 void DwarfDebug::emitDIE(DIE *Die) {
2039 // Get the abbreviation for this DIE.
2040 const DIEAbbrev &Abbrev = Die->getAbbrev();
2042 // Emit the code (index) for the abbreviation.
2043 if (Asm->isVerbose())
2044 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2045 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2046 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2047 dwarf::TagString(Abbrev.getTag()));
2048 Asm->EmitULEB128(Abbrev.getNumber());
2050 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2051 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2053 // Emit the DIE attribute values.
2054 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2055 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2056 dwarf::Form Form = AbbrevData[i].getForm();
2057 assert(Form && "Too many attributes for DIE (check abbreviation)");
2059 if (Asm->isVerbose())
2060 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2063 case dwarf::DW_AT_abstract_origin:
2064 case dwarf::DW_AT_type:
2065 case dwarf::DW_AT_friend:
2066 case dwarf::DW_AT_specification:
2067 case dwarf::DW_AT_import:
2068 case dwarf::DW_AT_containing_type: {
2069 DIEEntry *E = cast<DIEEntry>(Values[i]);
2070 DIE *Origin = E->getEntry();
2071 unsigned Addr = Origin->getOffset();
2072 if (Form == dwarf::DW_FORM_ref_addr) {
2073 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2074 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2075 // section. Origin->getOffset() returns the offset from start of the
2077 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2078 assert(CU && "CUDie should belong to a CU.");
2079 Addr += CU->getDebugInfoOffset();
2080 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2081 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2082 DIEEntry::getRefAddrSize(Asm));
2084 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2085 CU->getSectionSym(),
2086 DIEEntry::getRefAddrSize(Asm));
2088 // Make sure Origin belong to the same CU.
2089 assert(Die->getUnit() == Origin->getUnit() &&
2090 "The referenced DIE should belong to the same CU in ref4");
2091 Asm->EmitInt32(Addr);
2095 case dwarf::DW_AT_location: {
2096 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2097 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2098 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2100 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2102 Values[i]->EmitValue(Asm, Form);
2106 case dwarf::DW_AT_accessibility: {
2107 if (Asm->isVerbose()) {
2108 DIEInteger *V = cast<DIEInteger>(Values[i]);
2109 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2111 Values[i]->EmitValue(Asm, Form);
2115 // Emit an attribute using the defined form.
2116 Values[i]->EmitValue(Asm, Form);
2121 // Emit the DIE children if any.
2122 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2123 const std::vector<DIE *> &Children = Die->getChildren();
2125 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2126 emitDIE(Children[j]);
2128 Asm->OutStreamer.AddComment("End Of Children Mark");
2133 // Emit the various dwarf units to the unit section USection with
2134 // the abbreviations going into ASection.
2135 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2136 const MCSymbol *ASectionSym) {
2137 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2139 DwarfUnit *TheU = *I;
2140 DIE *Die = TheU->getUnitDie();
2141 const MCSection *USection = TheU->getSection();
2142 Asm->OutStreamer.SwitchSection(USection);
2144 // Emit the compile units header.
2145 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2147 // Emit size of content not including length itself
2148 Asm->OutStreamer.AddComment("Length of Unit");
2149 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2151 TheU->emitHeader(ASection, ASectionSym);
2154 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2158 // Emit the debug info section.
2159 void DwarfDebug::emitDebugInfo() {
2160 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2162 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2163 DwarfAbbrevSectionSym);
2166 // Emit the abbreviation section.
2167 void DwarfDebug::emitAbbreviations() {
2168 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2170 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2173 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2174 // Check to see if it is worth the effort.
2175 if (!Abbreviations.empty()) {
2176 // Start the debug abbrev section.
2177 Asm->OutStreamer.SwitchSection(Section);
2179 // For each abbrevation.
2180 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2181 // Get abbreviation data
2182 const DIEAbbrev *Abbrev = Abbreviations[i];
2184 // Emit the abbrevations code (base 1 index.)
2185 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2187 // Emit the abbreviations data.
2191 // Mark end of abbreviations.
2192 Asm->EmitULEB128(0, "EOM(3)");
2196 // Emit the last address of the section and the end of the line matrix.
2197 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2198 // Define last address of section.
2199 Asm->OutStreamer.AddComment("Extended Op");
2202 Asm->OutStreamer.AddComment("Op size");
2203 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2204 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2205 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2207 Asm->OutStreamer.AddComment("Section end label");
2209 Asm->OutStreamer.EmitSymbolValue(
2210 Asm->GetTempSymbol("section_end", SectionEnd),
2211 Asm->getDataLayout().getPointerSize());
2213 // Mark end of matrix.
2214 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2220 // Emit visible names into a hashed accelerator table section.
2221 void DwarfDebug::emitAccelNames() {
2223 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2224 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2225 E = getUnits().end();
2227 DwarfUnit *TheU = *I;
2228 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2229 for (StringMap<std::vector<const DIE *> >::const_iterator
2233 StringRef Name = GI->getKey();
2234 const std::vector<const DIE *> &Entities = GI->second;
2235 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2236 DE = Entities.end();
2238 AT.AddName(Name, *DI);
2242 AT.FinalizeTable(Asm, "Names");
2243 Asm->OutStreamer.SwitchSection(
2244 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2245 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2246 Asm->OutStreamer.EmitLabel(SectionBegin);
2248 // Emit the full data.
2249 AT.Emit(Asm, SectionBegin, &InfoHolder);
2252 // Emit objective C classes and categories into a hashed accelerator table
2254 void DwarfDebug::emitAccelObjC() {
2256 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2257 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2258 E = getUnits().end();
2260 DwarfUnit *TheU = *I;
2261 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2262 for (StringMap<std::vector<const DIE *> >::const_iterator
2266 StringRef Name = GI->getKey();
2267 const std::vector<const DIE *> &Entities = GI->second;
2268 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2269 DE = Entities.end();
2271 AT.AddName(Name, *DI);
2275 AT.FinalizeTable(Asm, "ObjC");
2276 Asm->OutStreamer.SwitchSection(
2277 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2278 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2279 Asm->OutStreamer.EmitLabel(SectionBegin);
2281 // Emit the full data.
2282 AT.Emit(Asm, SectionBegin, &InfoHolder);
2285 // Emit namespace dies into a hashed accelerator table.
2286 void DwarfDebug::emitAccelNamespaces() {
2288 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2289 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2290 E = getUnits().end();
2292 DwarfUnit *TheU = *I;
2293 const StringMap<std::vector<const DIE *> > &Names =
2294 TheU->getAccelNamespace();
2295 for (StringMap<std::vector<const DIE *> >::const_iterator
2299 StringRef Name = GI->getKey();
2300 const std::vector<const DIE *> &Entities = GI->second;
2301 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2302 DE = Entities.end();
2304 AT.AddName(Name, *DI);
2308 AT.FinalizeTable(Asm, "namespac");
2309 Asm->OutStreamer.SwitchSection(
2310 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2311 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2312 Asm->OutStreamer.EmitLabel(SectionBegin);
2314 // Emit the full data.
2315 AT.Emit(Asm, SectionBegin, &InfoHolder);
2318 // Emit type dies into a hashed accelerator table.
2319 void DwarfDebug::emitAccelTypes() {
2320 std::vector<DwarfAccelTable::Atom> Atoms;
2322 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2324 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2326 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2327 DwarfAccelTable AT(Atoms);
2328 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2329 E = getUnits().end();
2331 DwarfUnit *TheU = *I;
2332 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2333 TheU->getAccelTypes();
2335 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2339 StringRef Name = GI->getKey();
2340 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2342 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2343 DI = Entities.begin(),
2344 DE = Entities.end();
2346 AT.AddName(Name, DI->first, DI->second);
2350 AT.FinalizeTable(Asm, "types");
2351 Asm->OutStreamer.SwitchSection(
2352 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2353 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2354 Asm->OutStreamer.EmitLabel(SectionBegin);
2356 // Emit the full data.
2357 AT.Emit(Asm, SectionBegin, &InfoHolder);
2360 // Public name handling.
2361 // The format for the various pubnames:
2363 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2364 // for the DIE that is named.
2366 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2367 // into the CU and the index value is computed according to the type of value
2368 // for the DIE that is named.
2370 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2371 // it's the offset within the debug_info/debug_types dwo section, however, the
2372 // reference in the pubname header doesn't change.
2374 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2375 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2377 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2379 // We could have a specification DIE that has our most of our knowledge,
2380 // look for that now.
2381 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2383 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2384 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2385 Linkage = dwarf::GIEL_EXTERNAL;
2386 } else if (Die->findAttribute(dwarf::DW_AT_external))
2387 Linkage = dwarf::GIEL_EXTERNAL;
2389 switch (Die->getTag()) {
2390 case dwarf::DW_TAG_class_type:
2391 case dwarf::DW_TAG_structure_type:
2392 case dwarf::DW_TAG_union_type:
2393 case dwarf::DW_TAG_enumeration_type:
2394 return dwarf::PubIndexEntryDescriptor(
2395 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2396 ? dwarf::GIEL_STATIC
2397 : dwarf::GIEL_EXTERNAL);
2398 case dwarf::DW_TAG_typedef:
2399 case dwarf::DW_TAG_base_type:
2400 case dwarf::DW_TAG_subrange_type:
2401 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2402 case dwarf::DW_TAG_namespace:
2403 return dwarf::GIEK_TYPE;
2404 case dwarf::DW_TAG_subprogram:
2405 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2406 case dwarf::DW_TAG_constant:
2407 case dwarf::DW_TAG_variable:
2408 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2409 case dwarf::DW_TAG_enumerator:
2410 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2411 dwarf::GIEL_STATIC);
2413 return dwarf::GIEK_NONE;
2417 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2419 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2420 const MCSection *PSec =
2421 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2422 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2424 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2425 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2426 for (unsigned i = 0; i != Units.size(); ++i) {
2427 DwarfUnit *TheU = Units[i];
2428 unsigned ID = TheU->getUniqueID();
2430 // Start the dwarf pubnames section.
2431 Asm->OutStreamer.SwitchSection(PSec);
2433 // Emit a label so we can reference the beginning of this pubname section.
2435 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2438 Asm->OutStreamer.AddComment("Length of Public Names Info");
2439 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2440 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2441 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2443 Asm->OutStreamer.EmitLabel(BeginLabel);
2445 Asm->OutStreamer.AddComment("DWARF Version");
2446 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2448 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2449 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2451 Asm->OutStreamer.AddComment("Compilation Unit Length");
2452 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2454 // Emit the pubnames for this compilation unit.
2455 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2456 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2459 const char *Name = GI->getKeyData();
2460 const DIE *Entity = GI->second;
2462 Asm->OutStreamer.AddComment("DIE offset");
2463 Asm->EmitInt32(Entity->getOffset());
2466 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2467 Asm->OutStreamer.AddComment(
2468 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2469 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2470 Asm->EmitInt8(Desc.toBits());
2473 Asm->OutStreamer.AddComment("External Name");
2474 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2477 Asm->OutStreamer.AddComment("End Mark");
2479 Asm->OutStreamer.EmitLabel(EndLabel);
2483 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2484 const MCSection *PSec =
2485 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2486 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2488 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2489 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2490 for (unsigned i = 0; i != Units.size(); ++i) {
2491 DwarfUnit *TheU = Units[i];
2492 unsigned ID = TheU->getUniqueID();
2494 // Start the dwarf pubtypes section.
2495 Asm->OutStreamer.SwitchSection(PSec);
2497 // Emit a label so we can reference the beginning of this pubtype section.
2499 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2502 Asm->OutStreamer.AddComment("Length of Public Types Info");
2503 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2504 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2505 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2507 Asm->OutStreamer.EmitLabel(BeginLabel);
2509 Asm->OutStreamer.AddComment("DWARF Version");
2510 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2512 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2513 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2515 Asm->OutStreamer.AddComment("Compilation Unit Length");
2516 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2518 // Emit the pubtypes.
2519 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2520 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2523 const char *Name = GI->getKeyData();
2524 const DIE *Entity = GI->second;
2526 Asm->OutStreamer.AddComment("DIE offset");
2527 Asm->EmitInt32(Entity->getOffset());
2530 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2531 Asm->OutStreamer.AddComment(
2532 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2533 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2534 Asm->EmitInt8(Desc.toBits());
2537 Asm->OutStreamer.AddComment("External Name");
2539 // Emit the name with a terminating null byte.
2540 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2543 Asm->OutStreamer.AddComment("End Mark");
2545 Asm->OutStreamer.EmitLabel(EndLabel);
2549 // Emit strings into a string section.
2550 void DwarfFile::emitStrings(const MCSection *StrSection,
2551 const MCSection *OffsetSection = NULL,
2552 const MCSymbol *StrSecSym = NULL) {
2554 if (StringPool.empty())
2557 // Start the dwarf str section.
2558 Asm->OutStreamer.SwitchSection(StrSection);
2560 // Get all of the string pool entries and put them in an array by their ID so
2561 // we can sort them.
2563 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2566 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2567 I = StringPool.begin(),
2568 E = StringPool.end();
2570 Entries.push_back(std::make_pair(I->second.second, &*I));
2572 array_pod_sort(Entries.begin(), Entries.end());
2574 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2575 // Emit a label for reference from debug information entries.
2576 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2578 // Emit the string itself with a terminating null byte.
2579 Asm->OutStreamer.EmitBytes(
2580 StringRef(Entries[i].second->getKeyData(),
2581 Entries[i].second->getKeyLength() + 1));
2584 // If we've got an offset section go ahead and emit that now as well.
2585 if (OffsetSection) {
2586 Asm->OutStreamer.SwitchSection(OffsetSection);
2587 unsigned offset = 0;
2588 unsigned size = 4; // FIXME: DWARF64 is 8.
2589 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2590 Asm->OutStreamer.EmitIntValue(offset, size);
2591 offset += Entries[i].second->getKeyLength() + 1;
2596 // Emit addresses into the section given.
2597 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2599 if (AddressPool.empty())
2602 // Start the dwarf addr section.
2603 Asm->OutStreamer.SwitchSection(AddrSection);
2605 // Order the address pool entries by ID
2606 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2608 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2609 E = AddressPool.end();
2611 Entries[I->second] = I->first;
2613 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2614 // Emit an expression for reference from debug information entries.
2615 if (const MCExpr *Expr = Entries[i])
2616 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2618 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2622 // Emit visible names into a debug str section.
2623 void DwarfDebug::emitDebugStr() {
2624 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2625 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2628 // Emit locations into the debug loc section.
2629 void DwarfDebug::emitDebugLoc() {
2630 if (DotDebugLocEntries.empty())
2633 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2634 I = DotDebugLocEntries.begin(),
2635 E = DotDebugLocEntries.end();
2637 DotDebugLocEntry &Entry = *I;
2638 if (I + 1 != DotDebugLocEntries.end())
2642 // Start the dwarf loc section.
2643 Asm->OutStreamer.SwitchSection(
2644 Asm->getObjFileLowering().getDwarfLocSection());
2645 unsigned char Size = Asm->getDataLayout().getPointerSize();
2646 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2648 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2649 I = DotDebugLocEntries.begin(),
2650 E = DotDebugLocEntries.end();
2651 I != E; ++I, ++index) {
2652 DotDebugLocEntry &Entry = *I;
2653 if (Entry.isMerged())
2655 if (Entry.isEmpty()) {
2656 Asm->OutStreamer.EmitIntValue(0, Size);
2657 Asm->OutStreamer.EmitIntValue(0, Size);
2658 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2660 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2661 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2662 DIVariable DV(Entry.getVariable());
2663 Asm->OutStreamer.AddComment("Loc expr size");
2664 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2665 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2666 Asm->EmitLabelDifference(end, begin, 2);
2667 Asm->OutStreamer.EmitLabel(begin);
2668 if (Entry.isInt()) {
2669 DIBasicType BTy(DV.getType());
2670 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2671 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2672 Asm->OutStreamer.AddComment("DW_OP_consts");
2673 Asm->EmitInt8(dwarf::DW_OP_consts);
2674 Asm->EmitSLEB128(Entry.getInt());
2676 Asm->OutStreamer.AddComment("DW_OP_constu");
2677 Asm->EmitInt8(dwarf::DW_OP_constu);
2678 Asm->EmitULEB128(Entry.getInt());
2680 } else if (Entry.isLocation()) {
2681 MachineLocation Loc = Entry.getLoc();
2682 if (!DV.hasComplexAddress())
2684 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2686 // Complex address entry.
2687 unsigned N = DV.getNumAddrElements();
2689 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2690 if (Loc.getOffset()) {
2692 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2693 Asm->OutStreamer.AddComment("DW_OP_deref");
2694 Asm->EmitInt8(dwarf::DW_OP_deref);
2695 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2696 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2697 Asm->EmitSLEB128(DV.getAddrElement(1));
2699 // If first address element is OpPlus then emit
2700 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2701 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2702 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2706 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2709 // Emit remaining complex address elements.
2710 for (; i < N; ++i) {
2711 uint64_t Element = DV.getAddrElement(i);
2712 if (Element == DIBuilder::OpPlus) {
2713 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2714 Asm->EmitULEB128(DV.getAddrElement(++i));
2715 } else if (Element == DIBuilder::OpDeref) {
2717 Asm->EmitInt8(dwarf::DW_OP_deref);
2719 llvm_unreachable("unknown Opcode found in complex address");
2723 // else ... ignore constant fp. There is not any good way to
2724 // to represent them here in dwarf.
2725 Asm->OutStreamer.EmitLabel(end);
2730 struct SymbolCUSorter {
2731 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2732 const MCStreamer &Streamer;
2734 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2735 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2736 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2738 // Symbols with no order assigned should be placed at the end.
2739 // (e.g. section end labels)
2741 IA = (unsigned)(-1);
2743 IB = (unsigned)(-1);
2748 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2749 return (A->getUniqueID() < B->getUniqueID());
2753 const MCSymbol *Start, *End;
2756 // Emit a debug aranges section, containing a CU lookup for any
2757 // address we can tie back to a CU.
2758 void DwarfDebug::emitDebugARanges() {
2759 // Start the dwarf aranges section.
2760 Asm->OutStreamer.SwitchSection(
2761 Asm->getObjFileLowering().getDwarfARangesSection());
2763 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2767 // Build a list of sections used.
2768 std::vector<const MCSection *> Sections;
2769 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2771 const MCSection *Section = it->first;
2772 Sections.push_back(Section);
2775 // Sort the sections into order.
2776 // This is only done to ensure consistent output order across different runs.
2777 std::sort(Sections.begin(), Sections.end(), SectionSort);
2779 // Build a set of address spans, sorted by CU.
2780 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2781 const MCSection *Section = Sections[SecIdx];
2782 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2783 if (List.size() < 2)
2786 // Sort the symbols by offset within the section.
2787 SymbolCUSorter sorter(Asm->OutStreamer);
2788 std::sort(List.begin(), List.end(), sorter);
2790 // If we have no section (e.g. common), just write out
2791 // individual spans for each symbol.
2792 if (Section == NULL) {
2793 for (size_t n = 0; n < List.size(); n++) {
2794 const SymbolCU &Cur = List[n];
2797 Span.Start = Cur.Sym;
2800 Spans[Cur.CU].push_back(Span);
2803 // Build spans between each label.
2804 const MCSymbol *StartSym = List[0].Sym;
2805 for (size_t n = 1; n < List.size(); n++) {
2806 const SymbolCU &Prev = List[n - 1];
2807 const SymbolCU &Cur = List[n];
2809 // Try and build the longest span we can within the same CU.
2810 if (Cur.CU != Prev.CU) {
2812 Span.Start = StartSym;
2814 Spans[Prev.CU].push_back(Span);
2821 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2823 // Build a list of CUs used.
2824 std::vector<DwarfCompileUnit *> CUs;
2825 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2826 DwarfCompileUnit *CU = it->first;
2830 // Sort the CU list (again, to ensure consistent output order).
2831 std::sort(CUs.begin(), CUs.end(), CUSort);
2833 // Emit an arange table for each CU we used.
2834 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2835 DwarfCompileUnit *CU = CUs[CUIdx];
2836 std::vector<ArangeSpan> &List = Spans[CU];
2838 // Emit size of content not including length itself.
2839 unsigned ContentSize =
2840 sizeof(int16_t) + // DWARF ARange version number
2841 sizeof(int32_t) + // Offset of CU in the .debug_info section
2842 sizeof(int8_t) + // Pointer Size (in bytes)
2843 sizeof(int8_t); // Segment Size (in bytes)
2845 unsigned TupleSize = PtrSize * 2;
2847 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2848 unsigned Padding = 0;
2849 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2852 ContentSize += Padding;
2853 ContentSize += (List.size() + 1) * TupleSize;
2855 // For each compile unit, write the list of spans it covers.
2856 Asm->OutStreamer.AddComment("Length of ARange Set");
2857 Asm->EmitInt32(ContentSize);
2858 Asm->OutStreamer.AddComment("DWARF Arange version number");
2859 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2860 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2861 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
2862 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2863 Asm->EmitInt8(PtrSize);
2864 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2867 for (unsigned n = 0; n < Padding; n++)
2868 Asm->EmitInt8(0xff);
2870 for (unsigned n = 0; n < List.size(); n++) {
2871 const ArangeSpan &Span = List[n];
2872 Asm->EmitLabelReference(Span.Start, PtrSize);
2874 // Calculate the size as being from the span start to it's end.
2876 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2878 // For symbols without an end marker (e.g. common), we
2879 // write a single arange entry containing just that one symbol.
2880 uint64_t Size = SymSize[Span.Start];
2884 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2888 Asm->OutStreamer.AddComment("ARange terminator");
2889 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2890 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2894 // Emit visible names into a debug ranges section.
2895 void DwarfDebug::emitDebugRanges() {
2896 // Start the dwarf ranges section.
2897 Asm->OutStreamer.SwitchSection(
2898 Asm->getObjFileLowering().getDwarfRangesSection());
2900 // Size for our labels.
2901 unsigned char Size = Asm->getDataLayout().getPointerSize();
2903 // Grab the specific ranges for the compile units in the module.
2904 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2907 DwarfCompileUnit *TheCU = I->second;
2909 // Emit a symbol so we can find the beginning of our ranges.
2910 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2912 // Iterate over the misc ranges for the compile units in the module.
2913 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2914 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2915 E = RangeLists.end();
2917 const RangeSpanList &List = *I;
2919 // Emit our symbol so we can find the beginning of the range.
2920 Asm->OutStreamer.EmitLabel(List.getSym());
2922 for (SmallVectorImpl<RangeSpan>::const_iterator
2923 RI = List.getRanges().begin(),
2924 RE = List.getRanges().end();
2926 const RangeSpan &Range = *RI;
2927 // We occasionally have ranges without begin/end labels.
2928 // FIXME: Verify and fix.
2929 const MCSymbol *Begin = Range.getStart();
2930 const MCSymbol *End = Range.getEnd();
2931 Begin ? Asm->OutStreamer.EmitSymbolValue(Begin, Size)
2932 : Asm->OutStreamer.EmitIntValue(0, Size);
2933 End ? Asm->OutStreamer.EmitSymbolValue(End, Size)
2934 : Asm->OutStreamer.EmitIntValue(0, Size);
2937 // And terminate the list with two 0 values.
2938 Asm->OutStreamer.EmitIntValue(0, Size);
2939 Asm->OutStreamer.EmitIntValue(0, Size);
2944 // Emit visible names into a debug macinfo section.
2945 void DwarfDebug::emitDebugMacInfo() {
2946 if (const MCSection *LineInfo =
2947 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2948 // Start the dwarf macinfo section.
2949 Asm->OutStreamer.SwitchSection(LineInfo);
2953 // DWARF5 Experimental Separate Dwarf emitters.
2955 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2956 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2957 // DW_AT_ranges_base, DW_AT_addr_base.
2958 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2960 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2961 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2962 CU->getUniqueID(), Die, CU->getNode(), Asm, this, &SkeletonHolder);
2963 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2964 DwarfInfoSectionSym);
2966 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2967 CU->getNode().getSplitDebugFilename());
2969 // Relocate to the beginning of the addr_base section, else 0 for the
2970 // beginning of the one for this compile unit.
2971 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2972 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2973 DwarfAddrSectionSym);
2975 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2977 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2978 // into an entity. We're using 0, or a NULL label for this.
2979 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2981 // DW_AT_stmt_list is a offset of line number information for this
2982 // compile unit in debug_line section.
2983 // FIXME: Should handle multiple compile units.
2984 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2985 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2987 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2989 if (!CompilationDir.empty())
2990 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2992 addGnuPubAttributes(NewCU, Die);
2994 // Attribute if we've emitted any ranges and their location for the compile
2996 if (!CU->getRangeLists().empty())
2997 addSectionLabel(Asm, NewCU, Die, dwarf::DW_AT_GNU_ranges_base,
2998 NewCU->getLabelRange(), DwarfDebugRangeSectionSym);
3000 SkeletonHolder.addUnit(NewCU);
3005 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3006 // compile units that would normally be in debug_info.
3007 void DwarfDebug::emitDebugInfoDWO() {
3008 assert(useSplitDwarf() && "No split dwarf debug info?");
3009 InfoHolder.emitUnits(this,
3010 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3011 DwarfAbbrevDWOSectionSym);
3014 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3015 // abbreviations for the .debug_info.dwo section.
3016 void DwarfDebug::emitDebugAbbrevDWO() {
3017 assert(useSplitDwarf() && "No split dwarf?");
3018 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3021 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3022 // string section and is identical in format to traditional .debug_str
3024 void DwarfDebug::emitDebugStrDWO() {
3025 assert(useSplitDwarf() && "No split dwarf?");
3026 const MCSection *OffSec =
3027 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3028 const MCSymbol *StrSym = DwarfStrSectionSym;
3029 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3033 void DwarfDebug::addDwarfTypeUnitType(uint16_t Language, DIE *RefDie,
3034 DICompositeType CTy) {
3035 DenseMap<const MDNode *,
3036 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3037 DwarfTypeUnits.find(CTy);
3038 SmallVector<DIE *, 8> References;
3039 References.push_back(RefDie);
3040 if (I != DwarfTypeUnits.end()) {
3041 if (I->second.second) {
3042 I->second.second->push_back(RefDie);
3046 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3047 DwarfTypeUnit *NewTU =
3048 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, Language, Asm,
3050 InfoHolder.addUnit(NewTU);
3052 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3055 // Register the type in the DwarfTypeUnits map with a vector of references
3057 // populated whenever a reference is required.
3058 I = DwarfTypeUnits.insert(std::make_pair(
3059 CTy, std::make_pair(0, &References))).first;
3061 // Construct the type, this may, recursively, require more type units that
3062 // may in turn require this type again - in which case they will add DIEs to
3063 // the References vector.
3064 DIE *Die = NewTU->createTypeDIE(CTy);
3066 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3067 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3068 dwarf::DW_FORM_data8,
3069 DIEHash().computeDIEODRSignature(*Die));
3070 // FIXME: This won't handle circularly referential structures, as the DIE
3071 // may have references to other DIEs still under construction and missing
3072 // their signature. Hashing should walk through the signatures to their
3073 // referenced type, or possibly walk the precomputed hashes of related types
3075 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3077 // Remove the References vector and add the type hash.
3078 I->second.first = Signature;
3079 I->second.second = NULL;
3082 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
3083 : Asm->getObjFileLowering().getDwarfInfoSection(),
3084 // FIXME: This is subtle (using the info section even when
3085 // this CU is in the dwo section) and necessary for the
3086 // current arange code - ideally it should iterate
3087 // skeleton units, not full units, if it's going to reference skeletons
3088 useSplitDwarf() ? NULL : DwarfInfoSectionSym);
3091 // Populate all the signatures.
3092 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3093 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3094 dwarf::DW_FORM_ref_sig8, I->second.first);