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."),
61 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
62 cl::desc("Add the CU hash as the dwo_id."),
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
71 enum DefaultOnOff { Default, Enable, Disable };
74 static cl::opt<DefaultOnOff>
75 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
76 cl::desc("Output prototype dwarf accelerator tables."),
77 cl::values(clEnumVal(Default, "Default for platform"),
78 clEnumVal(Enable, "Enabled"),
79 clEnumVal(Disable, "Disabled"), clEnumValEnd),
82 static cl::opt<DefaultOnOff>
83 SplitDwarf("split-dwarf", cl::Hidden,
84 cl::desc("Output DWARF5 split debug info."),
85 cl::values(clEnumVal(Default, "Default for platform"),
86 clEnumVal(Enable, "Enabled"),
87 clEnumVal(Disable, "Disabled"), clEnumValEnd),
90 static cl::opt<DefaultOnOff>
91 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
92 cl::desc("Generate DWARF pubnames and pubtypes sections"),
93 cl::values(clEnumVal(Default, "Default for platform"),
94 clEnumVal(Enable, "Enabled"),
95 clEnumVal(Disable, "Disabled"), clEnumValEnd),
98 static cl::opt<unsigned>
99 DwarfVersionNumber("dwarf-version", cl::Hidden,
100 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
103 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
104 cl::desc("Generate DW_AT_ranges for compile units"),
107 static const char *const DWARFGroupName = "DWARF Emission";
108 static const char *const DbgTimerName = "DWARF Debug Writer";
110 //===----------------------------------------------------------------------===//
114 /// resolve - Look in the DwarfDebug map for the MDNode that
115 /// corresponds to the reference.
116 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
117 return DD->resolve(Ref);
120 DIType DbgVariable::getType() const {
121 DIType Ty = Var.getType();
122 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
123 // addresses instead.
124 if (Var.isBlockByrefVariable()) {
125 /* Byref variables, in Blocks, are declared by the programmer as
126 "SomeType VarName;", but the compiler creates a
127 __Block_byref_x_VarName struct, and gives the variable VarName
128 either the struct, or a pointer to the struct, as its type. This
129 is necessary for various behind-the-scenes things the compiler
130 needs to do with by-reference variables in blocks.
132 However, as far as the original *programmer* is concerned, the
133 variable should still have type 'SomeType', as originally declared.
135 The following function dives into the __Block_byref_x_VarName
136 struct to find the original type of the variable. This will be
137 passed back to the code generating the type for the Debug
138 Information Entry for the variable 'VarName'. 'VarName' will then
139 have the original type 'SomeType' in its debug information.
141 The original type 'SomeType' will be the type of the field named
142 'VarName' inside the __Block_byref_x_VarName struct.
144 NOTE: In order for this to not completely fail on the debugger
145 side, the Debug Information Entry for the variable VarName needs to
146 have a DW_AT_location that tells the debugger how to unwind through
147 the pointers and __Block_byref_x_VarName struct to find the actual
148 value of the variable. The function addBlockByrefType does this. */
150 uint16_t tag = Ty.getTag();
152 if (tag == dwarf::DW_TAG_pointer_type)
153 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
155 DIArray Elements = DICompositeType(subType).getTypeArray();
156 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
157 DIDerivedType DT(Elements.getElement(i));
158 if (getName() == DT.getName())
159 return (resolve(DT.getTypeDerivedFrom()));
165 } // end llvm namespace
167 /// Return Dwarf Version by checking module flags.
168 static unsigned getDwarfVersionFromModule(const Module *M) {
169 Value *Val = M->getModuleFlag("Dwarf Version");
171 return dwarf::DWARF_VERSION;
172 return cast<ConstantInt>(Val)->getZExtValue();
175 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
176 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
177 PrevLabel(NULL), GlobalRangeCount(0),
178 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
179 UsedNonDefaultText(false),
180 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
182 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
183 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
184 DwarfAddrSectionSym = 0;
185 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
186 FunctionBeginSym = FunctionEndSym = 0;
190 // Turn on accelerator tables for Darwin by default, pubnames by
191 // default for non-Darwin, and handle split dwarf.
192 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
194 if (DwarfAccelTables == Default)
195 HasDwarfAccelTables = IsDarwin;
197 HasDwarfAccelTables = DwarfAccelTables == Enable;
199 if (SplitDwarf == Default)
200 HasSplitDwarf = false;
202 HasSplitDwarf = SplitDwarf == Enable;
204 if (DwarfPubSections == Default)
205 HasDwarfPubSections = !IsDarwin;
207 HasDwarfPubSections = DwarfPubSections == Enable;
209 DwarfVersion = DwarfVersionNumber
211 : getDwarfVersionFromModule(MMI->getModule());
214 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
219 // Switch to the specified MCSection and emit an assembler
220 // temporary label to it if SymbolStem is specified.
221 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
222 const char *SymbolStem = 0) {
223 Asm->OutStreamer.SwitchSection(Section);
227 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
228 Asm->OutStreamer.EmitLabel(TmpSym);
232 DwarfFile::~DwarfFile() {
233 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
238 MCSymbol *DwarfFile::getStringPoolSym() {
239 return Asm->GetTempSymbol(StringPref);
242 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
243 std::pair<MCSymbol *, unsigned> &Entry =
244 StringPool.GetOrCreateValue(Str).getValue();
248 Entry.second = NextStringPoolNumber++;
249 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
252 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
253 std::pair<MCSymbol *, unsigned> &Entry =
254 StringPool.GetOrCreateValue(Str).getValue();
258 Entry.second = NextStringPoolNumber++;
259 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
263 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
264 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
267 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
268 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
269 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
271 ++NextAddrPoolNumber;
272 return P.first->second;
275 // Define a unique number for the abbreviation.
277 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
278 // Check the set for priors.
279 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
281 // If it's newly added.
282 if (InSet == &Abbrev) {
283 // Add to abbreviation list.
284 Abbreviations.push_back(&Abbrev);
286 // Assign the vector position + 1 as its number.
287 Abbrev.setNumber(Abbreviations.size());
289 // Assign existing abbreviation number.
290 Abbrev.setNumber(InSet->getNumber());
294 static bool isObjCClass(StringRef Name) {
295 return Name.startswith("+") || Name.startswith("-");
298 static bool hasObjCCategory(StringRef Name) {
299 if (!isObjCClass(Name))
302 return Name.find(") ") != StringRef::npos;
305 static void getObjCClassCategory(StringRef In, StringRef &Class,
306 StringRef &Category) {
307 if (!hasObjCCategory(In)) {
308 Class = In.slice(In.find('[') + 1, In.find(' '));
313 Class = In.slice(In.find('[') + 1, In.find('('));
314 Category = In.slice(In.find('[') + 1, In.find(' '));
318 static StringRef getObjCMethodName(StringRef In) {
319 return In.slice(In.find(' ') + 1, In.find(']'));
322 // Helper for sorting sections into a stable output order.
323 static bool SectionSort(const MCSection *A, const MCSection *B) {
324 std::string LA = (A ? A->getLabelBeginName() : "");
325 std::string LB = (B ? B->getLabelBeginName() : "");
329 // Add the various names to the Dwarf accelerator table names.
330 // TODO: Determine whether or not we should add names for programs
331 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
332 // is only slightly different than the lookup of non-standard ObjC names.
333 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
334 if (!SP.isDefinition())
336 TheU->addAccelName(SP.getName(), Die);
338 // If the linkage name is different than the name, go ahead and output
339 // that as well into the name table.
340 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
341 TheU->addAccelName(SP.getLinkageName(), Die);
343 // If this is an Objective-C selector name add it to the ObjC accelerator
345 if (isObjCClass(SP.getName())) {
346 StringRef Class, Category;
347 getObjCClassCategory(SP.getName(), Class, Category);
348 TheU->addAccelObjC(Class, Die);
350 TheU->addAccelObjC(Category, Die);
351 // Also add the base method name to the name table.
352 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
356 /// isSubprogramContext - Return true if Context is either a subprogram
357 /// or another context nested inside a subprogram.
358 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
361 DIDescriptor D(Context);
362 if (D.isSubprogram())
365 return isSubprogramContext(resolve(DIType(Context).getContext()));
369 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
370 // and DW_AT_high_pc attributes. If there are global variables in this
371 // scope then create and insert DIEs for these variables.
372 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
374 DIE *SPDie = SPCU->getDIE(SP);
376 assert(SPDie && "Unable to find subprogram DIE!");
378 // If we're updating an abstract DIE, then we will be adding the children and
379 // object pointer later on. But what we don't want to do is process the
380 // concrete DIE twice.
381 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
382 // Pick up abstract subprogram DIE.
384 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
385 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
387 DISubprogram SPDecl = SP.getFunctionDeclaration();
388 if (!SPDecl.isSubprogram()) {
389 // There is not any need to generate specification DIE for a function
390 // defined at compile unit level. If a function is defined inside another
391 // function then gdb prefers the definition at top level and but does not
392 // expect specification DIE in parent function. So avoid creating
393 // specification DIE for a function defined inside a function.
394 DIScope SPContext = resolve(SP.getContext());
395 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
396 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
397 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
400 DICompositeType SPTy = SP.getType();
401 DIArray Args = SPTy.getTypeArray();
402 uint16_t SPTag = SPTy.getTag();
403 if (SPTag == dwarf::DW_TAG_subroutine_type)
404 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
406 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
407 DIType ATy(Args.getElement(i));
408 SPCU->addType(Arg, ATy);
409 if (ATy.isArtificial())
410 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
411 if (ATy.isObjectPointer())
412 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
414 DIE *SPDeclDie = SPDie;
415 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
416 *SPCU->getUnitDie());
417 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
422 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
423 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
425 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
426 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
427 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
429 // Add name to the name table, we do this here because we're guaranteed
430 // to have concrete versions of our DW_TAG_subprogram nodes.
431 addSubprogramNames(SPCU, SP, SPDie);
436 /// Check whether we should create a DIE for the given Scope, return true
437 /// if we don't create a DIE (the corresponding DIE is null).
438 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
439 if (Scope->isAbstractScope())
442 // We don't create a DIE if there is no Range.
443 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
447 if (Ranges.size() > 1)
450 // We don't create a DIE if we have a single Range and the end label
452 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
453 MCSymbol *End = getLabelAfterInsn(RI->second);
457 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
458 dwarf::Attribute A, const MCSymbol *L,
459 const MCSymbol *Sec) {
460 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
461 U->addSectionLabel(D, A, L);
463 U->addSectionDelta(D, A, L, Sec);
466 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
467 const SmallVectorImpl<InsnRange> &Range) {
468 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
469 // emitting it appropriately.
470 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
471 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
472 DwarfDebugRangeSectionSym);
474 RangeSpanList List(RangeSym);
475 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
478 RangeSpan Span(getLabelBeforeInsn(RI->first),
479 getLabelAfterInsn(RI->second));
480 List.addRange(llvm_move(Span));
483 // Add the range list to the set of ranges to be emitted.
484 TheCU->addRangeList(llvm_move(List));
487 // Construct new DW_TAG_lexical_block for this scope and attach
488 // DW_AT_low_pc/DW_AT_high_pc labels.
489 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
490 LexicalScope *Scope) {
491 if (isLexicalScopeDIENull(Scope))
494 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
495 if (Scope->isAbstractScope())
498 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
500 // If we have multiple ranges, emit them into the range section.
501 if (ScopeRanges.size() > 1) {
502 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
506 // Construct the address range for this DIE.
507 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
508 MCSymbol *Start = getLabelBeforeInsn(RI->first);
509 MCSymbol *End = getLabelAfterInsn(RI->second);
510 assert(End && "End label should not be null!");
512 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
513 assert(End->isDefined() && "Invalid end label for an inlined scope!");
515 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
516 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
521 // This scope represents inlined body of a function. Construct DIE to
522 // represent this concrete inlined copy of the function.
523 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
524 LexicalScope *Scope) {
525 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
526 assert(!ScopeRanges.empty() &&
527 "LexicalScope does not have instruction markers!");
529 if (!Scope->getScopeNode())
531 DIScope DS(Scope->getScopeNode());
532 DISubprogram InlinedSP = getDISubprogram(DS);
533 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
535 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
539 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
540 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
542 // If we have multiple ranges, emit them into the range section.
543 if (ScopeRanges.size() > 1)
544 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
546 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
547 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
548 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
550 if (StartLabel == 0 || EndLabel == 0)
551 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
553 assert(StartLabel->isDefined() &&
554 "Invalid starting label for an inlined scope!");
555 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
557 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
558 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
561 InlinedSubprogramDIEs.insert(OriginDIE);
563 // Add the call site information to the DIE.
564 DILocation DL(Scope->getInlinedAt());
565 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
566 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
567 TheCU->getUniqueID()));
568 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
570 // Add name to the name table, we do this here because we're guaranteed
571 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
572 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
577 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
579 SmallVectorImpl<DIE *> &Children) {
580 DIE *ObjectPointer = NULL;
582 // Collect arguments for current function.
583 if (LScopes.isCurrentFunctionScope(Scope))
584 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
585 if (DbgVariable *ArgDV = CurrentFnArguments[i])
587 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
588 Children.push_back(Arg);
589 if (ArgDV->isObjectPointer())
593 // Collect lexical scope children first.
594 const SmallVectorImpl<DbgVariable *> &Variables =
595 ScopeVariables.lookup(Scope);
596 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
597 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
598 Scope->isAbstractScope())) {
599 Children.push_back(Variable);
600 if (Variables[i]->isObjectPointer())
601 ObjectPointer = Variable;
603 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
604 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
605 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
606 Children.push_back(Nested);
607 return ObjectPointer;
610 // Construct a DIE for this scope.
611 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
612 LexicalScope *Scope) {
613 if (!Scope || !Scope->getScopeNode())
616 DIScope DS(Scope->getScopeNode());
618 SmallVector<DIE *, 8> Children;
619 DIE *ObjectPointer = NULL;
620 bool ChildrenCreated = false;
622 // We try to create the scope DIE first, then the children DIEs. This will
623 // avoid creating un-used children then removing them later when we find out
624 // the scope DIE is null.
625 DIE *ScopeDIE = NULL;
626 if (Scope->getInlinedAt())
627 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
628 else if (DS.isSubprogram()) {
629 ProcessedSPNodes.insert(DS);
630 if (Scope->isAbstractScope()) {
631 ScopeDIE = TheCU->getDIE(DS);
632 // Note down abstract DIE.
634 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
636 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
638 // Early exit when we know the scope DIE is going to be null.
639 if (isLexicalScopeDIENull(Scope))
642 // We create children here when we know the scope DIE is not going to be
643 // null and the children will be added to the scope DIE.
644 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
645 ChildrenCreated = true;
647 // There is no need to emit empty lexical block DIE.
648 std::pair<ImportedEntityMap::const_iterator,
649 ImportedEntityMap::const_iterator> Range =
651 ScopesWithImportedEntities.begin(),
652 ScopesWithImportedEntities.end(),
653 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
655 if (Children.empty() && Range.first == Range.second)
657 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
658 assert(ScopeDIE && "Scope DIE should not be null.");
659 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
661 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
665 assert(Children.empty() &&
666 "We create children only when the scope DIE is not null.");
669 if (!ChildrenCreated)
670 // We create children when the scope DIE is not null.
671 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
674 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
677 ScopeDIE->addChild(*I);
679 if (DS.isSubprogram() && ObjectPointer != NULL)
680 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
685 // Look up the source id with the given directory and source file names.
686 // If none currently exists, create a new id and insert it in the
687 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
689 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
691 // If we use .loc in assembly, we can't separate .file entries according to
692 // compile units. Thus all files will belong to the default compile unit.
694 // FIXME: add a better feature test than hasRawTextSupport. Even better,
695 // extend .file to support this.
696 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
699 // If FE did not provide a file name, then assume stdin.
700 if (FileName.empty())
701 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
703 // TODO: this might not belong here. See if we can factor this better.
704 if (DirName == CompilationDir)
707 // FileIDCUMap stores the current ID for the given compile unit.
708 unsigned SrcId = FileIDCUMap[CUID] + 1;
710 // We look up the CUID/file/dir by concatenating them with a zero byte.
711 SmallString<128> NamePair;
712 NamePair += utostr(CUID);
715 NamePair += '\0'; // Zero bytes are not allowed in paths.
716 NamePair += FileName;
718 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
719 if (Ent.getValue() != SrcId)
720 return Ent.getValue();
722 FileIDCUMap[CUID] = SrcId;
723 // Print out a .file directive to specify files for .loc directives.
724 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
729 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
730 if (!GenerateGnuPubSections)
733 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
734 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
735 DwarfGnuPubNamesSectionSym);
737 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
738 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
739 DwarfGnuPubTypesSectionSym);
742 // Create new DwarfCompileUnit for the given metadata node with tag
743 // DW_TAG_compile_unit.
744 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
745 StringRef FN = DIUnit.getFilename();
746 CompilationDir = DIUnit.getDirectory();
748 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
749 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
750 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
751 InfoHolder.addUnit(NewCU);
753 FileIDCUMap[NewCU->getUniqueID()] = 0;
754 // Call this to emit a .file directive if it wasn't emitted for the source
755 // file this CU comes from yet.
756 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
758 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
759 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
760 DIUnit.getLanguage());
761 NewCU->addString(Die, dwarf::DW_AT_name, FN);
763 // Define start line table label for each Compile Unit.
764 MCSymbol *LineTableStartSym =
765 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
766 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
767 NewCU->getUniqueID());
769 // Use a single line table if we are using .loc and generating assembly.
771 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
772 (NewCU->getUniqueID() == 0);
774 if (!useSplitDwarf()) {
775 // DW_AT_stmt_list is a offset of line number information for this
776 // compile unit in debug_line section. For split dwarf this is
777 // left in the skeleton CU and so not included.
778 // The line table entries are not always emitted in assembly, so it
779 // is not okay to use line_table_start here.
780 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
781 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
782 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
783 : LineTableStartSym);
784 else if (UseTheFirstCU)
785 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
787 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
788 DwarfLineSectionSym);
790 // If we're using split dwarf the compilation dir is going to be in the
791 // skeleton CU and so we don't need to duplicate it here.
792 if (!CompilationDir.empty())
793 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
795 addGnuPubAttributes(NewCU, Die);
798 if (DIUnit.isOptimized())
799 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
801 StringRef Flags = DIUnit.getFlags();
803 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
805 if (unsigned RVer = DIUnit.getRunTimeVersion())
806 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
807 dwarf::DW_FORM_data1, RVer);
812 if (useSplitDwarf()) {
813 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
814 DwarfInfoDWOSectionSym);
815 NewCU->setSkeleton(constructSkeletonCU(NewCU));
817 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
818 DwarfInfoSectionSym);
820 CUMap.insert(std::make_pair(DIUnit, NewCU));
821 CUDieMap.insert(std::make_pair(Die, NewCU));
825 // Construct subprogram DIE.
826 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
828 // FIXME: We should only call this routine once, however, during LTO if a
829 // program is defined in multiple CUs we could end up calling it out of
830 // beginModule as we walk the CUs.
832 DwarfCompileUnit *&CURef = SPMap[N];
838 if (!SP.isDefinition())
839 // This is a method declaration which will be handled while constructing
843 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
845 // Expose as a global name.
846 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
849 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
851 DIImportedEntity Module(N);
852 if (!Module.Verify())
854 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
855 constructImportedEntityDIE(TheCU, Module, D);
858 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
859 const MDNode *N, DIE *Context) {
860 DIImportedEntity Module(N);
861 if (!Module.Verify())
863 return constructImportedEntityDIE(TheCU, Module, Context);
866 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
867 const DIImportedEntity &Module,
869 assert(Module.Verify() &&
870 "Use one of the MDNode * overloads to handle invalid metadata");
871 assert(Context && "Should always have a context for an imported_module");
872 DIE *IMDie = new DIE(Module.getTag());
873 TheCU->insertDIE(Module, IMDie);
875 DIDescriptor Entity = Module.getEntity();
876 if (Entity.isNameSpace())
877 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
878 else if (Entity.isSubprogram())
879 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
880 else if (Entity.isType())
881 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
883 EntityDie = TheCU->getDIE(Entity);
884 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
885 Module.getContext().getDirectory(),
886 TheCU->getUniqueID());
887 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
888 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
889 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
890 StringRef Name = Module.getName();
892 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
893 Context->addChild(IMDie);
896 // Emit all Dwarf sections that should come prior to the content. Create
897 // global DIEs and emit initial debug info sections. This is invoked by
898 // the target AsmPrinter.
899 void DwarfDebug::beginModule() {
900 if (DisableDebugInfoPrinting)
903 const Module *M = MMI->getModule();
905 // If module has named metadata anchors then use them, otherwise scan the
906 // module using debug info finder to collect debug info.
907 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
910 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
912 // Emit initial sections so we can reference labels later.
915 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
916 DICompileUnit CUNode(CU_Nodes->getOperand(i));
917 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
918 DIArray ImportedEntities = CUNode.getImportedEntities();
919 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
920 ScopesWithImportedEntities.push_back(std::make_pair(
921 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
922 ImportedEntities.getElement(i)));
923 std::sort(ScopesWithImportedEntities.begin(),
924 ScopesWithImportedEntities.end(), less_first());
925 DIArray GVs = CUNode.getGlobalVariables();
926 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
927 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
928 DIArray SPs = CUNode.getSubprograms();
929 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
930 constructSubprogramDIE(CU, SPs.getElement(i));
931 DIArray EnumTypes = CUNode.getEnumTypes();
932 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
933 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
934 DIArray RetainedTypes = CUNode.getRetainedTypes();
935 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
936 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
937 // Emit imported_modules last so that the relevant context is already
939 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
940 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
943 // Tell MMI that we have debug info.
944 MMI->setDebugInfoAvailability(true);
946 // Prime section data.
947 SectionMap[Asm->getObjFileLowering().getTextSection()];
950 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
951 void DwarfDebug::computeInlinedDIEs() {
952 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
953 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
954 AE = InlinedSubprogramDIEs.end();
957 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
959 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
960 AE = AbstractSPDies.end();
962 DIE *ISP = AI->second;
963 if (InlinedSubprogramDIEs.count(ISP))
965 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
969 // Collect info for variables that were optimized out.
970 void DwarfDebug::collectDeadVariables() {
971 const Module *M = MMI->getModule();
973 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
974 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
975 DICompileUnit TheCU(CU_Nodes->getOperand(i));
976 DIArray Subprograms = TheCU.getSubprograms();
977 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
978 DISubprogram SP(Subprograms.getElement(i));
979 if (ProcessedSPNodes.count(SP) != 0)
981 if (!SP.isSubprogram())
983 if (!SP.isDefinition())
985 DIArray Variables = SP.getVariables();
986 if (Variables.getNumElements() == 0)
989 // Construct subprogram DIE and add variables DIEs.
990 DwarfCompileUnit *SPCU =
991 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
992 assert(SPCU && "Unable to find Compile Unit!");
993 // FIXME: See the comment in constructSubprogramDIE about duplicate
995 constructSubprogramDIE(SPCU, SP);
996 DIE *SPDIE = SPCU->getDIE(SP);
997 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
998 DIVariable DV(Variables.getElement(vi));
999 if (!DV.isVariable())
1001 DbgVariable NewVar(DV, NULL, this);
1002 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1003 SPDIE->addChild(VariableDIE);
1010 void DwarfDebug::finalizeModuleInfo() {
1011 // Collect info for variables that were optimized out.
1012 collectDeadVariables();
1014 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1015 computeInlinedDIEs();
1017 // Handle anything that needs to be done on a per-unit basis after
1018 // all other generation.
1019 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1020 E = getUnits().end();
1022 DwarfUnit *TheU = *I;
1023 // Emit DW_AT_containing_type attribute to connect types with their
1024 // vtable holding type.
1025 TheU->constructContainingTypeDIEs();
1027 // Add CU specific attributes if we need to add any.
1028 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1029 // If we're splitting the dwarf out now that we've got the entire
1030 // CU then add the dwo id to it.
1031 DwarfCompileUnit *SkCU =
1032 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1033 if (useSplitDwarf()) {
1034 // This should be a unique identifier when we want to build .dwp files.
1036 if (GenerateCUHash) {
1038 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1040 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1041 dwarf::DW_FORM_data8, ID);
1042 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1043 dwarf::DW_FORM_data8, ID);
1046 // If we have code split among multiple sections or we've requested
1047 // it then emit a DW_AT_ranges attribute on the unit that will remain
1048 // in the .o file, otherwise add a DW_AT_low_pc.
1049 // FIXME: Also add a high pc if we can.
1050 // FIXME: We should use ranges if we have multiple compile units or
1051 // allow reordering of code ala .subsections_via_symbols in mach-o.
1052 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1053 if (useCURanges() && TheU->getRanges().size()) {
1054 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1055 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1056 DwarfDebugRangeSectionSym);
1058 // A DW_AT_low_pc attribute may also be specified in combination with
1059 // DW_AT_ranges to specify the default base address for use in location
1060 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1061 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1064 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1069 // Compute DIE offsets and sizes.
1070 InfoHolder.computeSizeAndOffsets();
1071 if (useSplitDwarf())
1072 SkeletonHolder.computeSizeAndOffsets();
1075 void DwarfDebug::endSections() {
1076 // Filter labels by section.
1077 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1078 const SymbolCU &SCU = ArangeLabels[n];
1079 if (SCU.Sym->isInSection()) {
1080 // Make a note of this symbol and it's section.
1081 const MCSection *Section = &SCU.Sym->getSection();
1082 if (!Section->getKind().isMetadata())
1083 SectionMap[Section].push_back(SCU);
1085 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1086 // appear in the output. This sucks as we rely on sections to build
1087 // arange spans. We can do it without, but it's icky.
1088 SectionMap[NULL].push_back(SCU);
1092 // Build a list of sections used.
1093 std::vector<const MCSection *> Sections;
1094 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1096 const MCSection *Section = it->first;
1097 Sections.push_back(Section);
1100 // Sort the sections into order.
1101 // This is only done to ensure consistent output order across different runs.
1102 std::sort(Sections.begin(), Sections.end(), SectionSort);
1104 // Add terminating symbols for each section.
1105 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1106 const MCSection *Section = Sections[ID];
1107 MCSymbol *Sym = NULL;
1110 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1111 // if we know the section name up-front. For user-created sections, the
1112 // resulting label may not be valid to use as a label. (section names can
1113 // use a greater set of characters on some systems)
1114 Sym = Asm->GetTempSymbol("debug_end", ID);
1115 Asm->OutStreamer.SwitchSection(Section);
1116 Asm->OutStreamer.EmitLabel(Sym);
1119 // Insert a final terminator.
1120 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1123 // For now only turn on CU ranges if we've explicitly asked for it,
1124 // we have -ffunction-sections enabled, we've emitted a function
1125 // into a unique section, or we're using LTO. If we're using LTO then
1126 // we can't know that any particular function in the module is correlated
1127 // to a particular CU and so we need to be conservative. At this point all
1128 // sections should be finalized except for dwarf sections.
1129 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1130 TargetMachine::getFunctionSections();
1133 // Emit all Dwarf sections that should come after the content.
1134 void DwarfDebug::endModule() {
1141 // End any existing sections.
1142 // TODO: Does this need to happen?
1145 // Finalize the debug info for the module.
1146 finalizeModuleInfo();
1150 // Emit all the DIEs into a debug info section.
1153 // Corresponding abbreviations into a abbrev section.
1154 emitAbbreviations();
1156 // Emit info into a debug loc section.
1159 // Emit info into a debug aranges section.
1162 // Emit info into a debug ranges section.
1165 if (useSplitDwarf()) {
1168 emitDebugAbbrevDWO();
1169 // Emit DWO addresses.
1170 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1173 // Emit info into the dwarf accelerator table sections.
1174 if (useDwarfAccelTables()) {
1177 emitAccelNamespaces();
1181 // Emit the pubnames and pubtypes sections if requested.
1182 if (HasDwarfPubSections) {
1183 emitDebugPubNames(GenerateGnuPubSections);
1184 emitDebugPubTypes(GenerateGnuPubSections);
1190 // Reset these for the next Module if we have one.
1194 // Find abstract variable, if any, associated with Var.
1195 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1196 DebugLoc ScopeLoc) {
1197 LLVMContext &Ctx = DV->getContext();
1198 // More then one inlined variable corresponds to one abstract variable.
1199 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1200 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1202 return AbsDbgVariable;
1204 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1208 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1209 addScopeVariable(Scope, AbsDbgVariable);
1210 AbstractVariables[Var] = AbsDbgVariable;
1211 return AbsDbgVariable;
1214 // If Var is a current function argument then add it to CurrentFnArguments list.
1215 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1216 if (!LScopes.isCurrentFunctionScope(Scope))
1218 DIVariable DV = Var->getVariable();
1219 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1221 unsigned ArgNo = DV.getArgNumber();
1225 size_t Size = CurrentFnArguments.size();
1227 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1228 // llvm::Function argument size is not good indicator of how many
1229 // arguments does the function have at source level.
1231 CurrentFnArguments.resize(ArgNo * 2);
1232 CurrentFnArguments[ArgNo - 1] = Var;
1236 // Collect variable information from side table maintained by MMI.
1237 void DwarfDebug::collectVariableInfoFromMMITable(
1238 SmallPtrSet<const MDNode *, 16> &Processed) {
1239 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1240 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1243 const MDNode *Var = VI->first;
1246 Processed.insert(Var);
1248 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1250 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1252 // If variable scope is not found then skip this variable.
1256 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1257 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1258 RegVar->setFrameIndex(VP.first);
1259 if (!addCurrentFnArgument(RegVar, Scope))
1260 addScopeVariable(Scope, RegVar);
1262 AbsDbgVariable->setFrameIndex(VP.first);
1266 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1268 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1269 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1270 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1271 MI->getOperand(0).getReg() &&
1272 (MI->getOperand(1).isImm() ||
1273 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1276 // Get .debug_loc entry for the instruction range starting at MI.
1277 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1278 const MCSymbol *FLabel,
1279 const MCSymbol *SLabel,
1280 const MachineInstr *MI) {
1281 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1283 assert(MI->getNumOperands() == 3);
1284 if (MI->getOperand(0).isReg()) {
1285 MachineLocation MLoc;
1286 // If the second operand is an immediate, this is a
1287 // register-indirect address.
1288 if (!MI->getOperand(1).isImm())
1289 MLoc.set(MI->getOperand(0).getReg());
1291 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1292 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1294 if (MI->getOperand(0).isImm())
1295 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1296 if (MI->getOperand(0).isFPImm())
1297 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1298 if (MI->getOperand(0).isCImm())
1299 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1301 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1304 // Find variables for each lexical scope.
1306 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1308 // Grab the variable info that was squirreled away in the MMI side-table.
1309 collectVariableInfoFromMMITable(Processed);
1311 for (SmallVectorImpl<const MDNode *>::const_iterator
1312 UVI = UserVariables.begin(),
1313 UVE = UserVariables.end();
1314 UVI != UVE; ++UVI) {
1315 const MDNode *Var = *UVI;
1316 if (Processed.count(Var))
1319 // History contains relevant DBG_VALUE instructions for Var and instructions
1321 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1322 if (History.empty())
1324 const MachineInstr *MInsn = History.front();
1327 LexicalScope *Scope = NULL;
1328 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1329 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1330 Scope = LScopes.getCurrentFunctionScope();
1331 else if (MDNode *IA = DV.getInlinedAt())
1332 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1334 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1335 // If variable scope is not found then skip this variable.
1339 Processed.insert(DV);
1340 assert(MInsn->isDebugValue() && "History must begin with debug value");
1341 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1342 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1343 if (!addCurrentFnArgument(RegVar, Scope))
1344 addScopeVariable(Scope, RegVar);
1346 AbsVar->setMInsn(MInsn);
1348 // Simplify ranges that are fully coalesced.
1349 if (History.size() <= 1 ||
1350 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1351 RegVar->setMInsn(MInsn);
1355 // Handle multiple DBG_VALUE instructions describing one variable.
1356 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1358 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1359 HI = History.begin(),
1362 const MachineInstr *Begin = *HI;
1363 assert(Begin->isDebugValue() && "Invalid History entry");
1365 // Check if DBG_VALUE is truncating a range.
1366 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1367 !Begin->getOperand(0).getReg())
1370 // Compute the range for a register location.
1371 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1372 const MCSymbol *SLabel = 0;
1375 // If Begin is the last instruction in History then its value is valid
1376 // until the end of the function.
1377 SLabel = FunctionEndSym;
1379 const MachineInstr *End = HI[1];
1380 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1381 << "\t" << *Begin << "\t" << *End << "\n");
1382 if (End->isDebugValue())
1383 SLabel = getLabelBeforeInsn(End);
1385 // End is a normal instruction clobbering the range.
1386 SLabel = getLabelAfterInsn(End);
1387 assert(SLabel && "Forgot label after clobber instruction");
1392 // The value is valid until the next DBG_VALUE or clobber.
1393 DotDebugLocEntries.push_back(
1394 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1396 DotDebugLocEntries.push_back(DotDebugLocEntry());
1399 // Collect info for variables that were optimized out.
1400 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1401 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1402 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1403 DIVariable DV(Variables.getElement(i));
1404 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1406 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1407 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1411 // Return Label preceding the instruction.
1412 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1413 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1414 assert(Label && "Didn't insert label before instruction");
1418 // Return Label immediately following the instruction.
1419 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1420 return LabelsAfterInsn.lookup(MI);
1423 // Process beginning of an instruction.
1424 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1427 // Check if source location changes, but ignore DBG_VALUE locations.
1428 if (!MI->isDebugValue()) {
1429 DebugLoc DL = MI->getDebugLoc();
1430 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1433 if (DL == PrologEndLoc) {
1434 Flags |= DWARF2_FLAG_PROLOGUE_END;
1435 PrologEndLoc = DebugLoc();
1437 if (PrologEndLoc.isUnknown())
1438 Flags |= DWARF2_FLAG_IS_STMT;
1440 if (!DL.isUnknown()) {
1441 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1442 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1444 recordSourceLine(0, 0, 0, 0);
1448 // Insert labels where requested.
1449 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1450 LabelsBeforeInsn.find(MI);
1453 if (I == LabelsBeforeInsn.end())
1456 // Label already assigned.
1461 PrevLabel = MMI->getContext().CreateTempSymbol();
1462 Asm->OutStreamer.EmitLabel(PrevLabel);
1464 I->second = PrevLabel;
1467 // Process end of an instruction.
1468 void DwarfDebug::endInstruction() {
1470 // Don't create a new label after DBG_VALUE instructions.
1471 // They don't generate code.
1472 if (!CurMI->isDebugValue())
1475 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1476 LabelsAfterInsn.find(CurMI);
1480 if (I == LabelsAfterInsn.end())
1483 // Label already assigned.
1487 // We need a label after this instruction.
1489 PrevLabel = MMI->getContext().CreateTempSymbol();
1490 Asm->OutStreamer.EmitLabel(PrevLabel);
1492 I->second = PrevLabel;
1495 // Each LexicalScope has first instruction and last instruction to mark
1496 // beginning and end of a scope respectively. Create an inverse map that list
1497 // scopes starts (and ends) with an instruction. One instruction may start (or
1498 // end) multiple scopes. Ignore scopes that are not reachable.
1499 void DwarfDebug::identifyScopeMarkers() {
1500 SmallVector<LexicalScope *, 4> WorkList;
1501 WorkList.push_back(LScopes.getCurrentFunctionScope());
1502 while (!WorkList.empty()) {
1503 LexicalScope *S = WorkList.pop_back_val();
1505 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1506 if (!Children.empty())
1507 for (SmallVectorImpl<LexicalScope *>::const_iterator
1508 SI = Children.begin(),
1509 SE = Children.end();
1511 WorkList.push_back(*SI);
1513 if (S->isAbstractScope())
1516 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1519 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1522 assert(RI->first && "InsnRange does not have first instruction!");
1523 assert(RI->second && "InsnRange does not have second instruction!");
1524 requestLabelBeforeInsn(RI->first);
1525 requestLabelAfterInsn(RI->second);
1530 // Get MDNode for DebugLoc's scope.
1531 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1532 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1533 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1534 return DL.getScope(Ctx);
1537 // Walk up the scope chain of given debug loc and find line number info
1538 // for the function.
1539 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1540 const MDNode *Scope = getScopeNode(DL, Ctx);
1541 DISubprogram SP = getDISubprogram(Scope);
1542 if (SP.isSubprogram()) {
1543 // Check for number of operands since the compatibility is
1545 if (SP->getNumOperands() > 19)
1546 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1548 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1554 // Gather pre-function debug information. Assumes being called immediately
1555 // after the function entry point has been emitted.
1556 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1559 // If there's no debug info for the function we're not going to do anything.
1560 if (!MMI->hasDebugInfo())
1563 // Grab the lexical scopes for the function, if we don't have any of those
1564 // then we're not going to be able to do anything.
1565 LScopes.initialize(*MF);
1566 if (LScopes.empty())
1569 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1571 // Make sure that each lexical scope will have a begin/end label.
1572 identifyScopeMarkers();
1574 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1575 // belongs to so that we add to the correct per-cu line table in the
1577 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1578 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1579 assert(TheCU && "Unable to find compile unit!");
1580 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1581 // Use a single line table if we are using .loc and generating assembly.
1582 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1584 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1586 // Check the current section against the standard text section. If different
1587 // keep track so that we will know when we're emitting functions into multiple
1589 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1590 UsedNonDefaultText = true;
1592 // Emit a label for the function so that we have a beginning address.
1593 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1594 // Assumes in correct section after the entry point.
1595 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1597 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1598 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1599 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1601 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1603 bool AtBlockEntry = true;
1604 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1606 const MachineInstr *MI = II;
1608 if (MI->isDebugValue()) {
1609 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1611 // Keep track of user variables.
1613 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1615 // Variable is in a register, we need to check for clobbers.
1616 if (isDbgValueInDefinedReg(MI))
1617 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1619 // Check the history of this variable.
1620 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1621 if (History.empty()) {
1622 UserVariables.push_back(Var);
1623 // The first mention of a function argument gets the FunctionBeginSym
1624 // label, so arguments are visible when breaking at function entry.
1626 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1627 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1628 LabelsBeforeInsn[MI] = FunctionBeginSym;
1630 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1631 const MachineInstr *Prev = History.back();
1632 if (Prev->isDebugValue()) {
1633 // Coalesce identical entries at the end of History.
1634 if (History.size() >= 2 &&
1635 Prev->isIdenticalTo(History[History.size() - 2])) {
1636 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1637 << "\t" << *Prev << "\t"
1638 << *History[History.size() - 2] << "\n");
1642 // Terminate old register assignments that don't reach MI;
1643 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1644 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1645 isDbgValueInDefinedReg(Prev)) {
1646 // Previous register assignment needs to terminate at the end of
1648 MachineBasicBlock::const_iterator LastMI =
1649 PrevMBB->getLastNonDebugInstr();
1650 if (LastMI == PrevMBB->end()) {
1651 // Drop DBG_VALUE for empty range.
1652 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1653 << "\t" << *Prev << "\n");
1655 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1656 // Terminate after LastMI.
1657 History.push_back(LastMI);
1661 History.push_back(MI);
1663 // Not a DBG_VALUE instruction.
1665 AtBlockEntry = false;
1667 // First known non-DBG_VALUE and non-frame setup location marks
1668 // the beginning of the function body.
1669 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1670 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1671 PrologEndLoc = MI->getDebugLoc();
1673 // Check if the instruction clobbers any registers with debug vars.
1674 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1675 MOE = MI->operands_end();
1676 MOI != MOE; ++MOI) {
1677 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1679 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1682 const MDNode *Var = LiveUserVar[Reg];
1685 // Reg is now clobbered.
1686 LiveUserVar[Reg] = 0;
1688 // Was MD last defined by a DBG_VALUE referring to Reg?
1689 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1690 if (HistI == DbgValues.end())
1692 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1693 if (History.empty())
1695 const MachineInstr *Prev = History.back();
1696 // Sanity-check: Register assignments are terminated at the end of
1698 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1700 // Is the variable still in Reg?
1701 if (!isDbgValueInDefinedReg(Prev) ||
1702 Prev->getOperand(0).getReg() != Reg)
1704 // Var is clobbered. Make sure the next instruction gets a label.
1705 History.push_back(MI);
1712 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1714 SmallVectorImpl<const MachineInstr *> &History = I->second;
1715 if (History.empty())
1718 // Make sure the final register assignments are terminated.
1719 const MachineInstr *Prev = History.back();
1720 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1721 const MachineBasicBlock *PrevMBB = Prev->getParent();
1722 MachineBasicBlock::const_iterator LastMI =
1723 PrevMBB->getLastNonDebugInstr();
1724 if (LastMI == PrevMBB->end())
1725 // Drop DBG_VALUE for empty range.
1727 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1728 // Terminate after LastMI.
1729 History.push_back(LastMI);
1732 // Request labels for the full history.
1733 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1734 const MachineInstr *MI = History[i];
1735 if (MI->isDebugValue())
1736 requestLabelBeforeInsn(MI);
1738 requestLabelAfterInsn(MI);
1742 PrevInstLoc = DebugLoc();
1743 PrevLabel = FunctionBeginSym;
1745 // Record beginning of function.
1746 if (!PrologEndLoc.isUnknown()) {
1747 DebugLoc FnStartDL =
1748 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1750 FnStartDL.getLine(), FnStartDL.getCol(),
1751 FnStartDL.getScope(MF->getFunction()->getContext()),
1752 // We'd like to list the prologue as "not statements" but GDB behaves
1753 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1754 DWARF2_FLAG_IS_STMT);
1758 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1759 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1760 DIVariable DV = Var->getVariable();
1761 // Variables with positive arg numbers are parameters.
1762 if (unsigned ArgNum = DV.getArgNumber()) {
1763 // Keep all parameters in order at the start of the variable list to ensure
1764 // function types are correct (no out-of-order parameters)
1766 // This could be improved by only doing it for optimized builds (unoptimized
1767 // builds have the right order to begin with), searching from the back (this
1768 // would catch the unoptimized case quickly), or doing a binary search
1769 // rather than linear search.
1770 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1771 while (I != Vars.end()) {
1772 unsigned CurNum = (*I)->getVariable().getArgNumber();
1773 // A local (non-parameter) variable has been found, insert immediately
1777 // A later indexed parameter has been found, insert immediately before it.
1778 if (CurNum > ArgNum)
1782 Vars.insert(I, Var);
1786 Vars.push_back(Var);
1789 // Gather and emit post-function debug information.
1790 void DwarfDebug::endFunction(const MachineFunction *MF) {
1791 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1792 // though the beginFunction may not be called at all.
1793 // We should handle both cases.
1797 assert(CurFn == MF);
1800 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1805 // Define end label for subprogram.
1806 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1807 // Assumes in correct section after the entry point.
1808 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1810 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1811 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1813 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1814 collectVariableInfo(ProcessedVars);
1816 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1817 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1818 assert(TheCU && "Unable to find compile unit!");
1820 // Construct abstract scopes.
1821 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1822 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1823 LexicalScope *AScope = AList[i];
1824 DISubprogram SP(AScope->getScopeNode());
1825 if (SP.isSubprogram()) {
1826 // Collect info for variables that were optimized out.
1827 DIArray Variables = SP.getVariables();
1828 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1829 DIVariable DV(Variables.getElement(i));
1830 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1832 // Check that DbgVariable for DV wasn't created earlier, when
1833 // findAbstractVariable() was called for inlined instance of DV.
1834 LLVMContext &Ctx = DV->getContext();
1835 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1836 if (AbstractVariables.lookup(CleanDV))
1838 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1839 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1842 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1843 constructScopeDIE(TheCU, AScope);
1846 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1847 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1848 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1850 // Add the range of this function to the list of ranges for the CU.
1851 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1852 TheCU->addRange(llvm_move(Span));
1855 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1856 E = ScopeVariables.end();
1858 DeleteContainerPointers(I->second);
1859 ScopeVariables.clear();
1860 DeleteContainerPointers(CurrentFnArguments);
1861 UserVariables.clear();
1863 AbstractVariables.clear();
1864 LabelsBeforeInsn.clear();
1865 LabelsAfterInsn.clear();
1870 // Register a source line with debug info. Returns the unique label that was
1871 // emitted and which provides correspondence to the source line list.
1872 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1878 DIDescriptor Scope(S);
1880 if (Scope.isCompileUnit()) {
1881 DICompileUnit CU(S);
1882 Fn = CU.getFilename();
1883 Dir = CU.getDirectory();
1884 } else if (Scope.isFile()) {
1886 Fn = F.getFilename();
1887 Dir = F.getDirectory();
1888 } else if (Scope.isSubprogram()) {
1890 Fn = SP.getFilename();
1891 Dir = SP.getDirectory();
1892 } else if (Scope.isLexicalBlockFile()) {
1893 DILexicalBlockFile DBF(S);
1894 Fn = DBF.getFilename();
1895 Dir = DBF.getDirectory();
1896 } else if (Scope.isLexicalBlock()) {
1897 DILexicalBlock DB(S);
1898 Fn = DB.getFilename();
1899 Dir = DB.getDirectory();
1901 llvm_unreachable("Unexpected scope info");
1903 Src = getOrCreateSourceID(
1904 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1906 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1909 //===----------------------------------------------------------------------===//
1911 //===----------------------------------------------------------------------===//
1913 // Compute the size and offset of a DIE. The offset is relative to start of the
1914 // CU. It returns the offset after laying out the DIE.
1915 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1916 // Get the children.
1917 const std::vector<DIE *> &Children = Die->getChildren();
1919 // Record the abbreviation.
1920 assignAbbrevNumber(Die->getAbbrev());
1922 // Get the abbreviation for this DIE.
1923 const DIEAbbrev &Abbrev = Die->getAbbrev();
1926 Die->setOffset(Offset);
1928 // Start the size with the size of abbreviation code.
1929 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1931 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1932 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1934 // Size the DIE attribute values.
1935 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1936 // Size attribute value.
1937 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1939 // Size the DIE children if any.
1940 if (!Children.empty()) {
1941 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1942 "Children flag not set");
1944 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1945 Offset = computeSizeAndOffset(Children[j], Offset);
1947 // End of children marker.
1948 Offset += sizeof(int8_t);
1951 Die->setSize(Offset - Die->getOffset());
1955 // Compute the size and offset for each DIE.
1956 void DwarfFile::computeSizeAndOffsets() {
1957 // Offset from the first CU in the debug info section is 0 initially.
1958 unsigned SecOffset = 0;
1960 // Iterate over each compile unit and set the size and offsets for each
1961 // DIE within each compile unit. All offsets are CU relative.
1962 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1965 (*I)->setDebugInfoOffset(SecOffset);
1967 // CU-relative offset is reset to 0 here.
1968 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1969 (*I)->getHeaderSize(); // Unit-specific headers
1971 // EndOffset here is CU-relative, after laying out
1972 // all of the CU DIE.
1973 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1974 SecOffset += EndOffset;
1978 // Emit initial Dwarf sections with a label at the start of each one.
1979 void DwarfDebug::emitSectionLabels() {
1980 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1982 // Dwarf sections base addresses.
1983 DwarfInfoSectionSym =
1984 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1985 if (useSplitDwarf())
1986 DwarfInfoDWOSectionSym =
1987 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1988 DwarfAbbrevSectionSym =
1989 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1990 if (useSplitDwarf())
1991 DwarfAbbrevDWOSectionSym = emitSectionSym(
1992 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1993 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1995 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1996 emitSectionSym(Asm, MacroInfo);
1998 DwarfLineSectionSym =
1999 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2000 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2001 if (GenerateGnuPubSections) {
2002 DwarfGnuPubNamesSectionSym =
2003 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2004 DwarfGnuPubTypesSectionSym =
2005 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2006 } else if (HasDwarfPubSections) {
2007 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2008 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2011 DwarfStrSectionSym =
2012 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2013 if (useSplitDwarf()) {
2014 DwarfStrDWOSectionSym =
2015 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2016 DwarfAddrSectionSym =
2017 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2019 DwarfDebugRangeSectionSym =
2020 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2022 DwarfDebugLocSectionSym =
2023 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2026 // Recursively emits a debug information entry.
2027 void DwarfDebug::emitDIE(DIE *Die) {
2028 // Get the abbreviation for this DIE.
2029 const DIEAbbrev &Abbrev = Die->getAbbrev();
2031 // Emit the code (index) for the abbreviation.
2032 if (Asm->isVerbose())
2033 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2034 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2035 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2036 dwarf::TagString(Abbrev.getTag()));
2037 Asm->EmitULEB128(Abbrev.getNumber());
2039 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2040 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2042 // Emit the DIE attribute values.
2043 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2044 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2045 dwarf::Form Form = AbbrevData[i].getForm();
2046 assert(Form && "Too many attributes for DIE (check abbreviation)");
2048 if (Asm->isVerbose())
2049 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2052 case dwarf::DW_AT_abstract_origin:
2053 case dwarf::DW_AT_type:
2054 case dwarf::DW_AT_friend:
2055 case dwarf::DW_AT_specification:
2056 case dwarf::DW_AT_import:
2057 case dwarf::DW_AT_containing_type: {
2058 DIEEntry *E = cast<DIEEntry>(Values[i]);
2059 DIE *Origin = E->getEntry();
2060 unsigned Addr = Origin->getOffset();
2061 if (Form == dwarf::DW_FORM_ref_addr) {
2062 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2063 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2064 // section. Origin->getOffset() returns the offset from start of the
2066 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2067 assert(CU && "CUDie should belong to a CU.");
2068 Addr += CU->getDebugInfoOffset();
2069 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2070 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2071 DIEEntry::getRefAddrSize(Asm));
2073 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2074 CU->getSectionSym(),
2075 DIEEntry::getRefAddrSize(Asm));
2077 // Make sure Origin belong to the same CU.
2078 assert(Die->getUnit() == Origin->getUnit() &&
2079 "The referenced DIE should belong to the same CU in ref4");
2080 Asm->EmitInt32(Addr);
2084 case dwarf::DW_AT_location: {
2085 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2086 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2087 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2089 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2091 Values[i]->EmitValue(Asm, Form);
2095 case dwarf::DW_AT_accessibility: {
2096 if (Asm->isVerbose()) {
2097 DIEInteger *V = cast<DIEInteger>(Values[i]);
2098 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2100 Values[i]->EmitValue(Asm, Form);
2104 // Emit an attribute using the defined form.
2105 Values[i]->EmitValue(Asm, Form);
2110 // Emit the DIE children if any.
2111 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2112 const std::vector<DIE *> &Children = Die->getChildren();
2114 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2115 emitDIE(Children[j]);
2117 Asm->OutStreamer.AddComment("End Of Children Mark");
2122 // Emit the various dwarf units to the unit section USection with
2123 // the abbreviations going into ASection.
2124 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2125 const MCSymbol *ASectionSym) {
2126 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2128 DwarfUnit *TheU = *I;
2129 DIE *Die = TheU->getUnitDie();
2130 const MCSection *USection = TheU->getSection();
2131 Asm->OutStreamer.SwitchSection(USection);
2133 // Emit the compile units header.
2134 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2136 // Emit size of content not including length itself
2137 Asm->OutStreamer.AddComment("Length of Unit");
2138 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2140 TheU->emitHeader(ASection, ASectionSym);
2143 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2147 // Emit the debug info section.
2148 void DwarfDebug::emitDebugInfo() {
2149 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2151 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2152 DwarfAbbrevSectionSym);
2155 // Emit the abbreviation section.
2156 void DwarfDebug::emitAbbreviations() {
2157 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2159 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2162 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2163 // Check to see if it is worth the effort.
2164 if (!Abbreviations.empty()) {
2165 // Start the debug abbrev section.
2166 Asm->OutStreamer.SwitchSection(Section);
2168 // For each abbrevation.
2169 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2170 // Get abbreviation data
2171 const DIEAbbrev *Abbrev = Abbreviations[i];
2173 // Emit the abbrevations code (base 1 index.)
2174 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2176 // Emit the abbreviations data.
2180 // Mark end of abbreviations.
2181 Asm->EmitULEB128(0, "EOM(3)");
2185 // Emit the last address of the section and the end of the line matrix.
2186 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2187 // Define last address of section.
2188 Asm->OutStreamer.AddComment("Extended Op");
2191 Asm->OutStreamer.AddComment("Op size");
2192 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2193 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2194 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2196 Asm->OutStreamer.AddComment("Section end label");
2198 Asm->OutStreamer.EmitSymbolValue(
2199 Asm->GetTempSymbol("section_end", SectionEnd),
2200 Asm->getDataLayout().getPointerSize());
2202 // Mark end of matrix.
2203 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2209 // Emit visible names into a hashed accelerator table section.
2210 void DwarfDebug::emitAccelNames() {
2212 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2213 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2214 E = getUnits().end();
2216 DwarfUnit *TheU = *I;
2217 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2218 for (StringMap<std::vector<const DIE *> >::const_iterator
2222 StringRef Name = GI->getKey();
2223 const std::vector<const DIE *> &Entities = GI->second;
2224 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2225 DE = Entities.end();
2227 AT.AddName(Name, *DI);
2231 AT.FinalizeTable(Asm, "Names");
2232 Asm->OutStreamer.SwitchSection(
2233 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2234 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2235 Asm->OutStreamer.EmitLabel(SectionBegin);
2237 // Emit the full data.
2238 AT.Emit(Asm, SectionBegin, &InfoHolder);
2241 // Emit objective C classes and categories into a hashed accelerator table
2243 void DwarfDebug::emitAccelObjC() {
2245 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2246 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2247 E = getUnits().end();
2249 DwarfUnit *TheU = *I;
2250 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2251 for (StringMap<std::vector<const DIE *> >::const_iterator
2255 StringRef Name = GI->getKey();
2256 const std::vector<const DIE *> &Entities = GI->second;
2257 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2258 DE = Entities.end();
2260 AT.AddName(Name, *DI);
2264 AT.FinalizeTable(Asm, "ObjC");
2265 Asm->OutStreamer.SwitchSection(
2266 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2267 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2268 Asm->OutStreamer.EmitLabel(SectionBegin);
2270 // Emit the full data.
2271 AT.Emit(Asm, SectionBegin, &InfoHolder);
2274 // Emit namespace dies into a hashed accelerator table.
2275 void DwarfDebug::emitAccelNamespaces() {
2277 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2278 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2279 E = getUnits().end();
2281 DwarfUnit *TheU = *I;
2282 const StringMap<std::vector<const DIE *> > &Names =
2283 TheU->getAccelNamespace();
2284 for (StringMap<std::vector<const DIE *> >::const_iterator
2288 StringRef Name = GI->getKey();
2289 const std::vector<const DIE *> &Entities = GI->second;
2290 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2291 DE = Entities.end();
2293 AT.AddName(Name, *DI);
2297 AT.FinalizeTable(Asm, "namespac");
2298 Asm->OutStreamer.SwitchSection(
2299 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2300 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2301 Asm->OutStreamer.EmitLabel(SectionBegin);
2303 // Emit the full data.
2304 AT.Emit(Asm, SectionBegin, &InfoHolder);
2307 // Emit type dies into a hashed accelerator table.
2308 void DwarfDebug::emitAccelTypes() {
2309 std::vector<DwarfAccelTable::Atom> Atoms;
2311 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2313 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2315 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2316 DwarfAccelTable AT(Atoms);
2317 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2318 E = getUnits().end();
2320 DwarfUnit *TheU = *I;
2321 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2322 TheU->getAccelTypes();
2324 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2328 StringRef Name = GI->getKey();
2329 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2331 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2332 DI = Entities.begin(),
2333 DE = Entities.end();
2335 AT.AddName(Name, DI->first, DI->second);
2339 AT.FinalizeTable(Asm, "types");
2340 Asm->OutStreamer.SwitchSection(
2341 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2342 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2343 Asm->OutStreamer.EmitLabel(SectionBegin);
2345 // Emit the full data.
2346 AT.Emit(Asm, SectionBegin, &InfoHolder);
2349 // Public name handling.
2350 // The format for the various pubnames:
2352 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2353 // for the DIE that is named.
2355 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2356 // into the CU and the index value is computed according to the type of value
2357 // for the DIE that is named.
2359 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2360 // it's the offset within the debug_info/debug_types dwo section, however, the
2361 // reference in the pubname header doesn't change.
2363 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2364 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2366 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2368 // We could have a specification DIE that has our most of our knowledge,
2369 // look for that now.
2370 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2372 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2373 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2374 Linkage = dwarf::GIEL_EXTERNAL;
2375 } else if (Die->findAttribute(dwarf::DW_AT_external))
2376 Linkage = dwarf::GIEL_EXTERNAL;
2378 switch (Die->getTag()) {
2379 case dwarf::DW_TAG_class_type:
2380 case dwarf::DW_TAG_structure_type:
2381 case dwarf::DW_TAG_union_type:
2382 case dwarf::DW_TAG_enumeration_type:
2383 return dwarf::PubIndexEntryDescriptor(
2384 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2385 ? dwarf::GIEL_STATIC
2386 : dwarf::GIEL_EXTERNAL);
2387 case dwarf::DW_TAG_typedef:
2388 case dwarf::DW_TAG_base_type:
2389 case dwarf::DW_TAG_subrange_type:
2390 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2391 case dwarf::DW_TAG_namespace:
2392 return dwarf::GIEK_TYPE;
2393 case dwarf::DW_TAG_subprogram:
2394 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2395 case dwarf::DW_TAG_constant:
2396 case dwarf::DW_TAG_variable:
2397 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2398 case dwarf::DW_TAG_enumerator:
2399 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2400 dwarf::GIEL_STATIC);
2402 return dwarf::GIEK_NONE;
2406 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2408 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2409 const MCSection *PSec =
2410 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2411 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2413 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2414 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2415 for (unsigned i = 0; i != Units.size(); ++i) {
2416 DwarfUnit *TheU = Units[i];
2417 unsigned ID = TheU->getUniqueID();
2419 // Start the dwarf pubnames section.
2420 Asm->OutStreamer.SwitchSection(PSec);
2422 // Emit a label so we can reference the beginning of this pubname section.
2424 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2427 Asm->OutStreamer.AddComment("Length of Public Names Info");
2428 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2429 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2430 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2432 Asm->OutStreamer.EmitLabel(BeginLabel);
2434 Asm->OutStreamer.AddComment("DWARF Version");
2435 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2437 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2438 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2440 Asm->OutStreamer.AddComment("Compilation Unit Length");
2441 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2443 // Emit the pubnames for this compilation unit.
2444 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2445 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2448 const char *Name = GI->getKeyData();
2449 const DIE *Entity = GI->second;
2451 Asm->OutStreamer.AddComment("DIE offset");
2452 Asm->EmitInt32(Entity->getOffset());
2455 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2456 Asm->OutStreamer.AddComment(
2457 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2458 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2459 Asm->EmitInt8(Desc.toBits());
2462 Asm->OutStreamer.AddComment("External Name");
2463 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2466 Asm->OutStreamer.AddComment("End Mark");
2468 Asm->OutStreamer.EmitLabel(EndLabel);
2472 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2473 const MCSection *PSec =
2474 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2475 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2477 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2478 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2479 for (unsigned i = 0; i != Units.size(); ++i) {
2480 DwarfUnit *TheU = Units[i];
2481 unsigned ID = TheU->getUniqueID();
2483 // Start the dwarf pubtypes section.
2484 Asm->OutStreamer.SwitchSection(PSec);
2486 // Emit a label so we can reference the beginning of this pubtype section.
2488 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2491 Asm->OutStreamer.AddComment("Length of Public Types Info");
2492 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2493 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2494 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2496 Asm->OutStreamer.EmitLabel(BeginLabel);
2498 Asm->OutStreamer.AddComment("DWARF Version");
2499 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2501 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2502 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2504 Asm->OutStreamer.AddComment("Compilation Unit Length");
2505 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2507 // Emit the pubtypes.
2508 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2509 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2512 const char *Name = GI->getKeyData();
2513 const DIE *Entity = GI->second;
2515 Asm->OutStreamer.AddComment("DIE offset");
2516 Asm->EmitInt32(Entity->getOffset());
2519 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2520 Asm->OutStreamer.AddComment(
2521 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2522 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2523 Asm->EmitInt8(Desc.toBits());
2526 Asm->OutStreamer.AddComment("External Name");
2528 // Emit the name with a terminating null byte.
2529 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2532 Asm->OutStreamer.AddComment("End Mark");
2534 Asm->OutStreamer.EmitLabel(EndLabel);
2538 // Emit strings into a string section.
2539 void DwarfFile::emitStrings(const MCSection *StrSection,
2540 const MCSection *OffsetSection = NULL,
2541 const MCSymbol *StrSecSym = NULL) {
2543 if (StringPool.empty())
2546 // Start the dwarf str section.
2547 Asm->OutStreamer.SwitchSection(StrSection);
2549 // Get all of the string pool entries and put them in an array by their ID so
2550 // we can sort them.
2552 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2555 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2556 I = StringPool.begin(),
2557 E = StringPool.end();
2559 Entries.push_back(std::make_pair(I->second.second, &*I));
2561 array_pod_sort(Entries.begin(), Entries.end());
2563 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2564 // Emit a label for reference from debug information entries.
2565 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2567 // Emit the string itself with a terminating null byte.
2568 Asm->OutStreamer.EmitBytes(
2569 StringRef(Entries[i].second->getKeyData(),
2570 Entries[i].second->getKeyLength() + 1));
2573 // If we've got an offset section go ahead and emit that now as well.
2574 if (OffsetSection) {
2575 Asm->OutStreamer.SwitchSection(OffsetSection);
2576 unsigned offset = 0;
2577 unsigned size = 4; // FIXME: DWARF64 is 8.
2578 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2579 Asm->OutStreamer.EmitIntValue(offset, size);
2580 offset += Entries[i].second->getKeyLength() + 1;
2585 // Emit addresses into the section given.
2586 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2588 if (AddressPool.empty())
2591 // Start the dwarf addr section.
2592 Asm->OutStreamer.SwitchSection(AddrSection);
2594 // Order the address pool entries by ID
2595 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2597 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2598 E = AddressPool.end();
2600 Entries[I->second] = I->first;
2602 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2603 // Emit an expression for reference from debug information entries.
2604 if (const MCExpr *Expr = Entries[i])
2605 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2607 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2611 // Emit visible names into a debug str section.
2612 void DwarfDebug::emitDebugStr() {
2613 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2614 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2617 // Emit locations into the debug loc section.
2618 void DwarfDebug::emitDebugLoc() {
2619 if (DotDebugLocEntries.empty())
2622 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2623 I = DotDebugLocEntries.begin(),
2624 E = DotDebugLocEntries.end();
2626 DotDebugLocEntry &Entry = *I;
2627 if (I + 1 != DotDebugLocEntries.end())
2631 // Start the dwarf loc section.
2632 Asm->OutStreamer.SwitchSection(
2633 Asm->getObjFileLowering().getDwarfLocSection());
2634 unsigned char Size = Asm->getDataLayout().getPointerSize();
2635 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2637 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2638 I = DotDebugLocEntries.begin(),
2639 E = DotDebugLocEntries.end();
2640 I != E; ++I, ++index) {
2641 DotDebugLocEntry &Entry = *I;
2642 if (Entry.isMerged())
2644 if (Entry.isEmpty()) {
2645 Asm->OutStreamer.EmitIntValue(0, Size);
2646 Asm->OutStreamer.EmitIntValue(0, Size);
2647 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2649 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2650 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2651 DIVariable DV(Entry.getVariable());
2652 Asm->OutStreamer.AddComment("Loc expr size");
2653 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2654 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2655 Asm->EmitLabelDifference(end, begin, 2);
2656 Asm->OutStreamer.EmitLabel(begin);
2657 if (Entry.isInt()) {
2658 DIBasicType BTy(DV.getType());
2659 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2660 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2661 Asm->OutStreamer.AddComment("DW_OP_consts");
2662 Asm->EmitInt8(dwarf::DW_OP_consts);
2663 Asm->EmitSLEB128(Entry.getInt());
2665 Asm->OutStreamer.AddComment("DW_OP_constu");
2666 Asm->EmitInt8(dwarf::DW_OP_constu);
2667 Asm->EmitULEB128(Entry.getInt());
2669 } else if (Entry.isLocation()) {
2670 MachineLocation Loc = Entry.getLoc();
2671 if (!DV.hasComplexAddress())
2673 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2675 // Complex address entry.
2676 unsigned N = DV.getNumAddrElements();
2678 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2679 if (Loc.getOffset()) {
2681 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2682 Asm->OutStreamer.AddComment("DW_OP_deref");
2683 Asm->EmitInt8(dwarf::DW_OP_deref);
2684 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2685 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2686 Asm->EmitSLEB128(DV.getAddrElement(1));
2688 // If first address element is OpPlus then emit
2689 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2690 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2691 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2695 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2698 // Emit remaining complex address elements.
2699 for (; i < N; ++i) {
2700 uint64_t Element = DV.getAddrElement(i);
2701 if (Element == DIBuilder::OpPlus) {
2702 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2703 Asm->EmitULEB128(DV.getAddrElement(++i));
2704 } else if (Element == DIBuilder::OpDeref) {
2706 Asm->EmitInt8(dwarf::DW_OP_deref);
2708 llvm_unreachable("unknown Opcode found in complex address");
2712 // else ... ignore constant fp. There is not any good way to
2713 // to represent them here in dwarf.
2714 Asm->OutStreamer.EmitLabel(end);
2719 struct SymbolCUSorter {
2720 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2721 const MCStreamer &Streamer;
2723 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2724 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2725 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2727 // Symbols with no order assigned should be placed at the end.
2728 // (e.g. section end labels)
2730 IA = (unsigned)(-1);
2732 IB = (unsigned)(-1);
2737 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2738 return (A->getUniqueID() < B->getUniqueID());
2742 const MCSymbol *Start, *End;
2745 // Emit a debug aranges section, containing a CU lookup for any
2746 // address we can tie back to a CU.
2747 void DwarfDebug::emitDebugARanges() {
2748 // Start the dwarf aranges section.
2749 Asm->OutStreamer.SwitchSection(
2750 Asm->getObjFileLowering().getDwarfARangesSection());
2752 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2756 // Build a list of sections used.
2757 std::vector<const MCSection *> Sections;
2758 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2760 const MCSection *Section = it->first;
2761 Sections.push_back(Section);
2764 // Sort the sections into order.
2765 // This is only done to ensure consistent output order across different runs.
2766 std::sort(Sections.begin(), Sections.end(), SectionSort);
2768 // Build a set of address spans, sorted by CU.
2769 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2770 const MCSection *Section = Sections[SecIdx];
2771 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2772 if (List.size() < 2)
2775 // Sort the symbols by offset within the section.
2776 SymbolCUSorter sorter(Asm->OutStreamer);
2777 std::sort(List.begin(), List.end(), sorter);
2779 // If we have no section (e.g. common), just write out
2780 // individual spans for each symbol.
2781 if (Section == NULL) {
2782 for (size_t n = 0; n < List.size(); n++) {
2783 const SymbolCU &Cur = List[n];
2786 Span.Start = Cur.Sym;
2789 Spans[Cur.CU].push_back(Span);
2792 // Build spans between each label.
2793 const MCSymbol *StartSym = List[0].Sym;
2794 for (size_t n = 1; n < List.size(); n++) {
2795 const SymbolCU &Prev = List[n - 1];
2796 const SymbolCU &Cur = List[n];
2798 // Try and build the longest span we can within the same CU.
2799 if (Cur.CU != Prev.CU) {
2801 Span.Start = StartSym;
2803 Spans[Prev.CU].push_back(Span);
2810 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2812 // Build a list of CUs used.
2813 std::vector<DwarfCompileUnit *> CUs;
2814 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2815 DwarfCompileUnit *CU = it->first;
2819 // Sort the CU list (again, to ensure consistent output order).
2820 std::sort(CUs.begin(), CUs.end(), CUSort);
2822 // Emit an arange table for each CU we used.
2823 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2824 DwarfCompileUnit *CU = CUs[CUIdx];
2825 std::vector<ArangeSpan> &List = Spans[CU];
2827 // Emit size of content not including length itself.
2828 unsigned ContentSize =
2829 sizeof(int16_t) + // DWARF ARange version number
2830 sizeof(int32_t) + // Offset of CU in the .debug_info section
2831 sizeof(int8_t) + // Pointer Size (in bytes)
2832 sizeof(int8_t); // Segment Size (in bytes)
2834 unsigned TupleSize = PtrSize * 2;
2836 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2838 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2840 ContentSize += Padding;
2841 ContentSize += (List.size() + 1) * TupleSize;
2843 // For each compile unit, write the list of spans it covers.
2844 Asm->OutStreamer.AddComment("Length of ARange Set");
2845 Asm->EmitInt32(ContentSize);
2846 Asm->OutStreamer.AddComment("DWARF Arange version number");
2847 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2848 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2849 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2850 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2851 Asm->EmitInt8(PtrSize);
2852 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2855 Asm->OutStreamer.EmitFill(Padding, 0xff);
2857 for (unsigned n = 0; n < List.size(); n++) {
2858 const ArangeSpan &Span = List[n];
2859 Asm->EmitLabelReference(Span.Start, PtrSize);
2861 // Calculate the size as being from the span start to it's end.
2863 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2865 // For symbols without an end marker (e.g. common), we
2866 // write a single arange entry containing just that one symbol.
2867 uint64_t Size = SymSize[Span.Start];
2871 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2875 Asm->OutStreamer.AddComment("ARange terminator");
2876 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2877 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2881 // Emit visible names into a debug ranges section.
2882 void DwarfDebug::emitDebugRanges() {
2883 // Start the dwarf ranges section.
2884 Asm->OutStreamer.SwitchSection(
2885 Asm->getObjFileLowering().getDwarfRangesSection());
2887 // Size for our labels.
2888 unsigned char Size = Asm->getDataLayout().getPointerSize();
2890 // Grab the specific ranges for the compile units in the module.
2891 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2895 DwarfCompileUnit *TheCU = I->second;
2897 // Emit a symbol so we can find the beginning of our ranges.
2898 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2900 // Iterate over the misc ranges for the compile units in the module.
2901 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2902 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2903 E = RangeLists.end();
2905 const RangeSpanList &List = *I;
2907 // Emit our symbol so we can find the beginning of the range.
2908 Asm->OutStreamer.EmitLabel(List.getSym());
2910 for (SmallVectorImpl<RangeSpan>::const_iterator
2911 RI = List.getRanges().begin(),
2912 RE = List.getRanges().end();
2914 const RangeSpan &Range = *RI;
2915 const MCSymbol *Begin = Range.getStart();
2916 const MCSymbol *End = Range.getEnd();
2917 assert(Begin && "Range without a begin symbol?");
2918 assert(End && "Range without an end symbol?");
2919 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2920 Asm->OutStreamer.EmitSymbolValue(End, Size);
2923 // And terminate the list with two 0 values.
2924 Asm->OutStreamer.EmitIntValue(0, Size);
2925 Asm->OutStreamer.EmitIntValue(0, Size);
2928 // Now emit a range for the CU itself.
2929 if (useCURanges()) {
2930 Asm->OutStreamer.EmitLabel(
2931 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2932 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2933 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2934 RangeSpan Range = Ranges[i];
2935 const MCSymbol *Begin = Range.getStart();
2936 const MCSymbol *End = Range.getEnd();
2937 assert(Begin && "Range without a begin symbol?");
2938 assert(End && "Range without an end symbol?");
2939 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2940 Asm->OutStreamer.EmitSymbolValue(End, Size);
2942 // And terminate the list with two 0 values.
2943 Asm->OutStreamer.EmitIntValue(0, Size);
2944 Asm->OutStreamer.EmitIntValue(0, Size);
2949 // DWARF5 Experimental Separate Dwarf emitters.
2951 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2953 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2954 U->getCUNode().getSplitDebugFilename());
2956 // Relocate to the beginning of the addr_base section, else 0 for the
2957 // beginning of the one for this compile unit.
2958 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2959 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2961 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2963 if (!CompilationDir.empty())
2964 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2966 addGnuPubAttributes(NewU, Die);
2968 SkeletonHolder.addUnit(NewU);
2971 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2972 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2973 // DW_AT_ranges_base, DW_AT_addr_base.
2974 // TODO: Implement DW_AT_ranges_base.
2975 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2977 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2978 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2979 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2980 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2981 DwarfInfoSectionSym);
2983 // DW_AT_stmt_list is a offset of line number information for this
2984 // compile unit in debug_line section.
2985 // FIXME: Should handle multiple compile units.
2986 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2987 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2989 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2991 initSkeletonUnit(CU, Die, NewCU);
2996 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2998 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
3000 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
3001 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3002 TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
3003 NewTU->setTypeSignature(TU->getTypeSignature());
3004 NewTU->setType(NULL);
3006 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
3008 initSkeletonUnit(TU, Die, NewTU);
3012 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3013 // compile units that would normally be in debug_info.
3014 void DwarfDebug::emitDebugInfoDWO() {
3015 assert(useSplitDwarf() && "No split dwarf debug info?");
3016 InfoHolder.emitUnits(this,
3017 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3018 DwarfAbbrevDWOSectionSym);
3021 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3022 // abbreviations for the .debug_info.dwo section.
3023 void DwarfDebug::emitDebugAbbrevDWO() {
3024 assert(useSplitDwarf() && "No split dwarf?");
3025 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3028 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3029 // string section and is identical in format to traditional .debug_str
3031 void DwarfDebug::emitDebugStrDWO() {
3032 assert(useSplitDwarf() && "No split dwarf?");
3033 const MCSection *OffSec =
3034 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3035 const MCSymbol *StrSym = DwarfStrSectionSym;
3036 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3040 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3041 StringRef Identifier, DIE *RefDie,
3042 DICompositeType CTy) {
3044 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3046 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3050 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3051 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3052 InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3054 InfoHolder.addUnit(NewTU);
3056 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3057 CUNode.getLanguage());
3060 Hash.update(Identifier);
3061 // ... take the least significant 8 bytes and return those. Our MD5
3062 // implementation always returns its results in little endian, swap bytes
3064 MD5::MD5Result Result;
3066 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3067 NewTU->setTypeSignature(Signature);
3068 if (useSplitDwarf())
3069 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3071 NewTU->setType(NewTU->createTypeDIE(CTy));
3075 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3076 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3078 CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);