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 print 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->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 generating assembly.
771 Asm->OutStreamer.hasRawTextSupport() || (NewCU->getUniqueID() == 0);
773 if (!useSplitDwarf()) {
774 // DW_AT_stmt_list is a offset of line number information for this
775 // compile unit in debug_line section. For split dwarf this is
776 // left in the skeleton CU and so not included.
777 // The line table entries are not always emitted in assembly, so it
778 // is not okay to use line_table_start here.
779 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
780 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
781 UseTheFirstCU ? DwarfLineSectionSym
782 : LineTableStartSym);
783 else if (UseTheFirstCU)
784 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
786 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
787 DwarfLineSectionSym);
789 // If we're using split dwarf the compilation dir is going to be in the
790 // skeleton CU and so we don't need to duplicate it here.
791 if (!CompilationDir.empty())
792 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
794 addGnuPubAttributes(NewCU, Die);
797 if (DIUnit.isOptimized())
798 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
800 StringRef Flags = DIUnit.getFlags();
802 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
804 if (unsigned RVer = DIUnit.getRunTimeVersion())
805 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
806 dwarf::DW_FORM_data1, RVer);
811 if (useSplitDwarf()) {
812 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
813 DwarfInfoDWOSectionSym);
814 NewCU->setSkeleton(constructSkeletonCU(NewCU));
816 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
817 DwarfInfoSectionSym);
819 CUMap.insert(std::make_pair(DIUnit, NewCU));
820 CUDieMap.insert(std::make_pair(Die, NewCU));
824 // Construct subprogram DIE.
825 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
827 // FIXME: We should only call this routine once, however, during LTO if a
828 // program is defined in multiple CUs we could end up calling it out of
829 // beginModule as we walk the CUs.
831 DwarfCompileUnit *&CURef = SPMap[N];
837 if (!SP.isDefinition())
838 // This is a method declaration which will be handled while constructing
842 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
844 // Expose as a global name.
845 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
848 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
850 DIImportedEntity Module(N);
851 assert(Module.Verify());
852 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
853 constructImportedEntityDIE(TheCU, Module, D);
856 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
857 const MDNode *N, DIE *Context) {
858 DIImportedEntity Module(N);
859 assert(Module.Verify());
860 return constructImportedEntityDIE(TheCU, Module, Context);
863 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
864 const DIImportedEntity &Module,
866 assert(Module.Verify() &&
867 "Use one of the MDNode * overloads to handle invalid metadata");
868 assert(Context && "Should always have a context for an imported_module");
869 DIE *IMDie = new DIE(Module.getTag());
870 TheCU->insertDIE(Module, IMDie);
872 DIDescriptor Entity = Module.getEntity();
873 if (Entity.isNameSpace())
874 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
875 else if (Entity.isSubprogram())
876 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
877 else if (Entity.isType())
878 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
880 EntityDie = TheCU->getDIE(Entity);
881 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
882 Module.getContext().getDirectory(),
883 TheCU->getUniqueID());
884 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
885 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
886 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
887 StringRef Name = Module.getName();
889 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
890 Context->addChild(IMDie);
893 // Emit all Dwarf sections that should come prior to the content. Create
894 // global DIEs and emit initial debug info sections. This is invoked by
895 // the target AsmPrinter.
896 void DwarfDebug::beginModule() {
897 if (DisableDebugInfoPrinting)
900 const Module *M = MMI->getModule();
902 // If module has named metadata anchors then use them, otherwise scan the
903 // module using debug info finder to collect debug info.
904 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
907 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
909 // Emit initial sections so we can reference labels later.
912 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
913 DICompileUnit CUNode(CU_Nodes->getOperand(i));
914 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
915 DIArray ImportedEntities = CUNode.getImportedEntities();
916 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
917 ScopesWithImportedEntities.push_back(std::make_pair(
918 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
919 ImportedEntities.getElement(i)));
920 std::sort(ScopesWithImportedEntities.begin(),
921 ScopesWithImportedEntities.end(), less_first());
922 DIArray GVs = CUNode.getGlobalVariables();
923 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
924 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
925 DIArray SPs = CUNode.getSubprograms();
926 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
927 constructSubprogramDIE(CU, SPs.getElement(i));
928 DIArray EnumTypes = CUNode.getEnumTypes();
929 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
930 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
931 DIArray RetainedTypes = CUNode.getRetainedTypes();
932 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
933 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
934 // Emit imported_modules last so that the relevant context is already
936 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
937 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
940 // Tell MMI that we have debug info.
941 MMI->setDebugInfoAvailability(true);
943 // Prime section data.
944 SectionMap[Asm->getObjFileLowering().getTextSection()];
947 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
948 void DwarfDebug::computeInlinedDIEs() {
949 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
950 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
951 AE = InlinedSubprogramDIEs.end();
954 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
956 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
957 AE = AbstractSPDies.end();
959 DIE *ISP = AI->second;
960 if (InlinedSubprogramDIEs.count(ISP))
962 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
966 // Collect info for variables that were optimized out.
967 void DwarfDebug::collectDeadVariables() {
968 const Module *M = MMI->getModule();
970 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
971 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
972 DICompileUnit TheCU(CU_Nodes->getOperand(i));
973 DIArray Subprograms = TheCU.getSubprograms();
974 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
975 DISubprogram SP(Subprograms.getElement(i));
976 if (ProcessedSPNodes.count(SP) != 0)
978 if (!SP.isSubprogram())
980 if (!SP.isDefinition())
982 DIArray Variables = SP.getVariables();
983 if (Variables.getNumElements() == 0)
986 // Construct subprogram DIE and add variables DIEs.
987 DwarfCompileUnit *SPCU =
988 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
989 assert(SPCU && "Unable to find Compile Unit!");
990 // FIXME: See the comment in constructSubprogramDIE about duplicate
992 constructSubprogramDIE(SPCU, SP);
993 DIE *SPDIE = SPCU->getDIE(SP);
994 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
995 DIVariable DV(Variables.getElement(vi));
996 if (!DV.isVariable())
998 DbgVariable NewVar(DV, NULL, this);
999 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1000 SPDIE->addChild(VariableDIE);
1007 void DwarfDebug::finalizeModuleInfo() {
1008 // Collect info for variables that were optimized out.
1009 collectDeadVariables();
1011 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1012 computeInlinedDIEs();
1014 // Handle anything that needs to be done on a per-unit basis after
1015 // all other generation.
1016 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1017 E = getUnits().end();
1019 DwarfUnit *TheU = *I;
1020 // Emit DW_AT_containing_type attribute to connect types with their
1021 // vtable holding type.
1022 TheU->constructContainingTypeDIEs();
1024 // Add CU specific attributes if we need to add any.
1025 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1026 // If we're splitting the dwarf out now that we've got the entire
1027 // CU then add the dwo id to it.
1028 DwarfCompileUnit *SkCU =
1029 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1030 if (useSplitDwarf()) {
1031 // This should be a unique identifier when we want to build .dwp files.
1033 if (GenerateCUHash) {
1035 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1037 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1038 dwarf::DW_FORM_data8, ID);
1039 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1040 dwarf::DW_FORM_data8, ID);
1043 // If we have code split among multiple sections or we've requested
1044 // it then emit a DW_AT_ranges attribute on the unit that will remain
1045 // in the .o file, otherwise add a DW_AT_low_pc.
1046 // FIXME: Also add a high pc if we can.
1047 // FIXME: We should use ranges if we have multiple compile units or
1048 // allow reordering of code ala .subsections_via_symbols in mach-o.
1049 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1050 if (useCURanges() && TheU->getRanges().size()) {
1051 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1052 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1053 DwarfDebugRangeSectionSym);
1055 // A DW_AT_low_pc attribute may also be specified in combination with
1056 // DW_AT_ranges to specify the default base address for use in location
1057 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
1058 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1061 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1066 // Compute DIE offsets and sizes.
1067 InfoHolder.computeSizeAndOffsets();
1068 if (useSplitDwarf())
1069 SkeletonHolder.computeSizeAndOffsets();
1072 void DwarfDebug::endSections() {
1073 // Filter labels by section.
1074 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1075 const SymbolCU &SCU = ArangeLabels[n];
1076 if (SCU.Sym->isInSection()) {
1077 // Make a note of this symbol and it's section.
1078 const MCSection *Section = &SCU.Sym->getSection();
1079 if (!Section->getKind().isMetadata())
1080 SectionMap[Section].push_back(SCU);
1082 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1083 // appear in the output. This sucks as we rely on sections to build
1084 // arange spans. We can do it without, but it's icky.
1085 SectionMap[NULL].push_back(SCU);
1089 // Build a list of sections used.
1090 std::vector<const MCSection *> Sections;
1091 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1093 const MCSection *Section = it->first;
1094 Sections.push_back(Section);
1097 // Sort the sections into order.
1098 // This is only done to ensure consistent output order across different runs.
1099 std::sort(Sections.begin(), Sections.end(), SectionSort);
1101 // Add terminating symbols for each section.
1102 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1103 const MCSection *Section = Sections[ID];
1104 MCSymbol *Sym = NULL;
1107 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1108 // if we know the section name up-front. For user-created sections, the
1109 // resulting label may not be valid to use as a label. (section names can
1110 // use a greater set of characters on some systems)
1111 Sym = Asm->GetTempSymbol("debug_end", ID);
1112 Asm->OutStreamer.SwitchSection(Section);
1113 Asm->OutStreamer.EmitLabel(Sym);
1116 // Insert a final terminator.
1117 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1120 // For now only turn on CU ranges if we've explicitly asked for it,
1121 // we have -ffunction-sections enabled, we've emitted a function
1122 // into a unique section, or we're using LTO. If we're using LTO then
1123 // we can't know that any particular function in the module is correlated
1124 // to a particular CU and so we need to be conservative. At this point all
1125 // sections should be finalized except for dwarf sections.
1126 HasCURanges = DwarfCURanges || UsedNonDefaultText || (CUMap.size() > 1) ||
1127 TargetMachine::getFunctionSections();
1130 // Emit all Dwarf sections that should come after the content.
1131 void DwarfDebug::endModule() {
1138 // End any existing sections.
1139 // TODO: Does this need to happen?
1142 // Finalize the debug info for the module.
1143 finalizeModuleInfo();
1147 // Emit all the DIEs into a debug info section.
1150 // Corresponding abbreviations into a abbrev section.
1151 emitAbbreviations();
1153 // Emit info into a debug loc section.
1156 // Emit info into a debug aranges section.
1159 // Emit info into a debug ranges section.
1162 if (useSplitDwarf()) {
1165 emitDebugAbbrevDWO();
1166 // Emit DWO addresses.
1167 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1170 // Emit info into the dwarf accelerator table sections.
1171 if (useDwarfAccelTables()) {
1174 emitAccelNamespaces();
1178 // Emit the pubnames and pubtypes sections if requested.
1179 if (HasDwarfPubSections) {
1180 emitDebugPubNames(GenerateGnuPubSections);
1181 emitDebugPubTypes(GenerateGnuPubSections);
1187 // Reset these for the next Module if we have one.
1191 // Find abstract variable, if any, associated with Var.
1192 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1193 DebugLoc ScopeLoc) {
1194 LLVMContext &Ctx = DV->getContext();
1195 // More then one inlined variable corresponds to one abstract variable.
1196 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1197 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1199 return AbsDbgVariable;
1201 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1205 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1206 addScopeVariable(Scope, AbsDbgVariable);
1207 AbstractVariables[Var] = AbsDbgVariable;
1208 return AbsDbgVariable;
1211 // If Var is a current function argument then add it to CurrentFnArguments list.
1212 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1213 if (!LScopes.isCurrentFunctionScope(Scope))
1215 DIVariable DV = Var->getVariable();
1216 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1218 unsigned ArgNo = DV.getArgNumber();
1222 size_t Size = CurrentFnArguments.size();
1224 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1225 // llvm::Function argument size is not good indicator of how many
1226 // arguments does the function have at source level.
1228 CurrentFnArguments.resize(ArgNo * 2);
1229 CurrentFnArguments[ArgNo - 1] = Var;
1233 // Collect variable information from side table maintained by MMI.
1234 void DwarfDebug::collectVariableInfoFromMMITable(
1235 SmallPtrSet<const MDNode *, 16> &Processed) {
1236 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1237 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1240 const MDNode *Var = VI->first;
1243 Processed.insert(Var);
1245 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1247 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1249 // If variable scope is not found then skip this variable.
1253 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1254 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1255 RegVar->setFrameIndex(VP.first);
1256 if (!addCurrentFnArgument(RegVar, Scope))
1257 addScopeVariable(Scope, RegVar);
1259 AbsDbgVariable->setFrameIndex(VP.first);
1263 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1265 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1266 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1267 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1268 MI->getOperand(0).getReg() &&
1269 (MI->getOperand(1).isImm() ||
1270 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1273 // Get .debug_loc entry for the instruction range starting at MI.
1274 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1275 const MCSymbol *FLabel,
1276 const MCSymbol *SLabel,
1277 const MachineInstr *MI) {
1278 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1280 assert(MI->getNumOperands() == 3);
1281 if (MI->getOperand(0).isReg()) {
1282 MachineLocation MLoc;
1283 // If the second operand is an immediate, this is a
1284 // register-indirect address.
1285 if (!MI->getOperand(1).isImm())
1286 MLoc.set(MI->getOperand(0).getReg());
1288 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1289 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1291 if (MI->getOperand(0).isImm())
1292 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1293 if (MI->getOperand(0).isFPImm())
1294 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1295 if (MI->getOperand(0).isCImm())
1296 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1298 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1301 // Find variables for each lexical scope.
1303 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1305 // Grab the variable info that was squirreled away in the MMI side-table.
1306 collectVariableInfoFromMMITable(Processed);
1308 for (SmallVectorImpl<const MDNode *>::const_iterator
1309 UVI = UserVariables.begin(),
1310 UVE = UserVariables.end();
1311 UVI != UVE; ++UVI) {
1312 const MDNode *Var = *UVI;
1313 if (Processed.count(Var))
1316 // History contains relevant DBG_VALUE instructions for Var and instructions
1318 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1319 if (History.empty())
1321 const MachineInstr *MInsn = History.front();
1324 LexicalScope *Scope = NULL;
1325 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1326 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1327 Scope = LScopes.getCurrentFunctionScope();
1328 else if (MDNode *IA = DV.getInlinedAt())
1329 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1331 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1332 // If variable scope is not found then skip this variable.
1336 Processed.insert(DV);
1337 assert(MInsn->isDebugValue() && "History must begin with debug value");
1338 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1339 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1340 if (!addCurrentFnArgument(RegVar, Scope))
1341 addScopeVariable(Scope, RegVar);
1343 AbsVar->setMInsn(MInsn);
1345 // Simplify ranges that are fully coalesced.
1346 if (History.size() <= 1 ||
1347 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1348 RegVar->setMInsn(MInsn);
1352 // Handle multiple DBG_VALUE instructions describing one variable.
1353 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1355 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1356 HI = History.begin(),
1359 const MachineInstr *Begin = *HI;
1360 assert(Begin->isDebugValue() && "Invalid History entry");
1362 // Check if DBG_VALUE is truncating a range.
1363 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1364 !Begin->getOperand(0).getReg())
1367 // Compute the range for a register location.
1368 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1369 const MCSymbol *SLabel = 0;
1372 // If Begin is the last instruction in History then its value is valid
1373 // until the end of the function.
1374 SLabel = FunctionEndSym;
1376 const MachineInstr *End = HI[1];
1377 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1378 << "\t" << *Begin << "\t" << *End << "\n");
1379 if (End->isDebugValue())
1380 SLabel = getLabelBeforeInsn(End);
1382 // End is a normal instruction clobbering the range.
1383 SLabel = getLabelAfterInsn(End);
1384 assert(SLabel && "Forgot label after clobber instruction");
1389 // The value is valid until the next DBG_VALUE or clobber.
1390 DotDebugLocEntries.push_back(
1391 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1393 DotDebugLocEntries.push_back(DotDebugLocEntry());
1396 // Collect info for variables that were optimized out.
1397 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1398 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1399 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1400 DIVariable DV(Variables.getElement(i));
1401 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1403 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1404 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1408 // Return Label preceding the instruction.
1409 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1410 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1411 assert(Label && "Didn't insert label before instruction");
1415 // Return Label immediately following the instruction.
1416 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1417 return LabelsAfterInsn.lookup(MI);
1420 // Process beginning of an instruction.
1421 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1424 // Check if source location changes, but ignore DBG_VALUE locations.
1425 if (!MI->isDebugValue()) {
1426 DebugLoc DL = MI->getDebugLoc();
1427 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1430 if (DL == PrologEndLoc) {
1431 Flags |= DWARF2_FLAG_PROLOGUE_END;
1432 PrologEndLoc = DebugLoc();
1434 if (PrologEndLoc.isUnknown())
1435 Flags |= DWARF2_FLAG_IS_STMT;
1437 if (!DL.isUnknown()) {
1438 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1439 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1441 recordSourceLine(0, 0, 0, 0);
1445 // Insert labels where requested.
1446 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1447 LabelsBeforeInsn.find(MI);
1450 if (I == LabelsBeforeInsn.end())
1453 // Label already assigned.
1458 PrevLabel = MMI->getContext().CreateTempSymbol();
1459 Asm->OutStreamer.EmitLabel(PrevLabel);
1461 I->second = PrevLabel;
1464 // Process end of an instruction.
1465 void DwarfDebug::endInstruction() {
1467 // Don't create a new label after DBG_VALUE instructions.
1468 // They don't generate code.
1469 if (!CurMI->isDebugValue())
1472 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1473 LabelsAfterInsn.find(CurMI);
1477 if (I == LabelsAfterInsn.end())
1480 // Label already assigned.
1484 // We need a label after this instruction.
1486 PrevLabel = MMI->getContext().CreateTempSymbol();
1487 Asm->OutStreamer.EmitLabel(PrevLabel);
1489 I->second = PrevLabel;
1492 // Each LexicalScope has first instruction and last instruction to mark
1493 // beginning and end of a scope respectively. Create an inverse map that list
1494 // scopes starts (and ends) with an instruction. One instruction may start (or
1495 // end) multiple scopes. Ignore scopes that are not reachable.
1496 void DwarfDebug::identifyScopeMarkers() {
1497 SmallVector<LexicalScope *, 4> WorkList;
1498 WorkList.push_back(LScopes.getCurrentFunctionScope());
1499 while (!WorkList.empty()) {
1500 LexicalScope *S = WorkList.pop_back_val();
1502 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1503 if (!Children.empty())
1504 for (SmallVectorImpl<LexicalScope *>::const_iterator
1505 SI = Children.begin(),
1506 SE = Children.end();
1508 WorkList.push_back(*SI);
1510 if (S->isAbstractScope())
1513 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1516 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1519 assert(RI->first && "InsnRange does not have first instruction!");
1520 assert(RI->second && "InsnRange does not have second instruction!");
1521 requestLabelBeforeInsn(RI->first);
1522 requestLabelAfterInsn(RI->second);
1527 // Gather pre-function debug information. Assumes being called immediately
1528 // after the function entry point has been emitted.
1529 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1532 // If there's no debug info for the function we're not going to do anything.
1533 if (!MMI->hasDebugInfo())
1536 // Grab the lexical scopes for the function, if we don't have any of those
1537 // then we're not going to be able to do anything.
1538 LScopes.initialize(*MF);
1539 if (LScopes.empty())
1542 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1544 // Make sure that each lexical scope will have a begin/end label.
1545 identifyScopeMarkers();
1547 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1548 // belongs to so that we add to the correct per-cu line table in the
1550 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1551 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1552 assert(TheCU && "Unable to find compile unit!");
1553 if (Asm->OutStreamer.hasRawTextSupport())
1554 // Use a single line table if we are generating assembly.
1555 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1557 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1559 // Check the current section against the standard text section. If different
1560 // keep track so that we will know when we're emitting functions into multiple
1562 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1563 UsedNonDefaultText = true;
1565 // Emit a label for the function so that we have a beginning address.
1566 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1567 // Assumes in correct section after the entry point.
1568 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1570 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1571 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1572 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1574 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1576 bool AtBlockEntry = true;
1577 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1579 const MachineInstr *MI = II;
1581 if (MI->isDebugValue()) {
1582 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1584 // Keep track of user variables.
1586 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1588 // Variable is in a register, we need to check for clobbers.
1589 if (isDbgValueInDefinedReg(MI))
1590 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1592 // Check the history of this variable.
1593 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1594 if (History.empty()) {
1595 UserVariables.push_back(Var);
1596 // The first mention of a function argument gets the FunctionBeginSym
1597 // label, so arguments are visible when breaking at function entry.
1599 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1600 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1601 LabelsBeforeInsn[MI] = FunctionBeginSym;
1603 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1604 const MachineInstr *Prev = History.back();
1605 if (Prev->isDebugValue()) {
1606 // Coalesce identical entries at the end of History.
1607 if (History.size() >= 2 &&
1608 Prev->isIdenticalTo(History[History.size() - 2])) {
1609 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1610 << "\t" << *Prev << "\t"
1611 << *History[History.size() - 2] << "\n");
1615 // Terminate old register assignments that don't reach MI;
1616 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1617 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1618 isDbgValueInDefinedReg(Prev)) {
1619 // Previous register assignment needs to terminate at the end of
1621 MachineBasicBlock::const_iterator LastMI =
1622 PrevMBB->getLastNonDebugInstr();
1623 if (LastMI == PrevMBB->end()) {
1624 // Drop DBG_VALUE for empty range.
1625 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1626 << "\t" << *Prev << "\n");
1628 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1629 // Terminate after LastMI.
1630 History.push_back(LastMI);
1634 History.push_back(MI);
1636 // Not a DBG_VALUE instruction.
1638 AtBlockEntry = false;
1640 // First known non-DBG_VALUE and non-frame setup location marks
1641 // the beginning of the function body.
1642 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1643 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1644 PrologEndLoc = MI->getDebugLoc();
1646 // Check if the instruction clobbers any registers with debug vars.
1647 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1648 MOE = MI->operands_end();
1649 MOI != MOE; ++MOI) {
1650 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1652 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1655 const MDNode *Var = LiveUserVar[Reg];
1658 // Reg is now clobbered.
1659 LiveUserVar[Reg] = 0;
1661 // Was MD last defined by a DBG_VALUE referring to Reg?
1662 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1663 if (HistI == DbgValues.end())
1665 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1666 if (History.empty())
1668 const MachineInstr *Prev = History.back();
1669 // Sanity-check: Register assignments are terminated at the end of
1671 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1673 // Is the variable still in Reg?
1674 if (!isDbgValueInDefinedReg(Prev) ||
1675 Prev->getOperand(0).getReg() != Reg)
1677 // Var is clobbered. Make sure the next instruction gets a label.
1678 History.push_back(MI);
1685 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1687 SmallVectorImpl<const MachineInstr *> &History = I->second;
1688 if (History.empty())
1691 // Make sure the final register assignments are terminated.
1692 const MachineInstr *Prev = History.back();
1693 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1694 const MachineBasicBlock *PrevMBB = Prev->getParent();
1695 MachineBasicBlock::const_iterator LastMI =
1696 PrevMBB->getLastNonDebugInstr();
1697 if (LastMI == PrevMBB->end())
1698 // Drop DBG_VALUE for empty range.
1700 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1701 // Terminate after LastMI.
1702 History.push_back(LastMI);
1705 // Request labels for the full history.
1706 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1707 const MachineInstr *MI = History[i];
1708 if (MI->isDebugValue())
1709 requestLabelBeforeInsn(MI);
1711 requestLabelAfterInsn(MI);
1715 PrevInstLoc = DebugLoc();
1716 PrevLabel = FunctionBeginSym;
1718 // Record beginning of function.
1719 if (!PrologEndLoc.isUnknown()) {
1720 DebugLoc FnStartDL =
1721 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1723 FnStartDL.getLine(), FnStartDL.getCol(),
1724 FnStartDL.getScope(MF->getFunction()->getContext()),
1725 // We'd like to list the prologue as "not statements" but GDB behaves
1726 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1727 DWARF2_FLAG_IS_STMT);
1731 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1732 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1733 DIVariable DV = Var->getVariable();
1734 // Variables with positive arg numbers are parameters.
1735 if (unsigned ArgNum = DV.getArgNumber()) {
1736 // Keep all parameters in order at the start of the variable list to ensure
1737 // function types are correct (no out-of-order parameters)
1739 // This could be improved by only doing it for optimized builds (unoptimized
1740 // builds have the right order to begin with), searching from the back (this
1741 // would catch the unoptimized case quickly), or doing a binary search
1742 // rather than linear search.
1743 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1744 while (I != Vars.end()) {
1745 unsigned CurNum = (*I)->getVariable().getArgNumber();
1746 // A local (non-parameter) variable has been found, insert immediately
1750 // A later indexed parameter has been found, insert immediately before it.
1751 if (CurNum > ArgNum)
1755 Vars.insert(I, Var);
1759 Vars.push_back(Var);
1762 // Gather and emit post-function debug information.
1763 void DwarfDebug::endFunction(const MachineFunction *MF) {
1764 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1765 // though the beginFunction may not be called at all.
1766 // We should handle both cases.
1770 assert(CurFn == MF);
1773 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1778 // Define end label for subprogram.
1779 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1780 // Assumes in correct section after the entry point.
1781 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1783 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1784 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1786 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1787 collectVariableInfo(ProcessedVars);
1789 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1790 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1791 assert(TheCU && "Unable to find compile unit!");
1793 // Construct abstract scopes.
1794 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1795 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1796 LexicalScope *AScope = AList[i];
1797 DISubprogram SP(AScope->getScopeNode());
1798 if (SP.isSubprogram()) {
1799 // Collect info for variables that were optimized out.
1800 DIArray Variables = SP.getVariables();
1801 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1802 DIVariable DV(Variables.getElement(i));
1803 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1805 // Check that DbgVariable for DV wasn't created earlier, when
1806 // findAbstractVariable() was called for inlined instance of DV.
1807 LLVMContext &Ctx = DV->getContext();
1808 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1809 if (AbstractVariables.lookup(CleanDV))
1811 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1812 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1815 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1816 constructScopeDIE(TheCU, AScope);
1819 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1820 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1821 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1823 // Add the range of this function to the list of ranges for the CU.
1824 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1825 TheCU->addRange(llvm_move(Span));
1828 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1829 E = ScopeVariables.end();
1831 DeleteContainerPointers(I->second);
1832 ScopeVariables.clear();
1833 DeleteContainerPointers(CurrentFnArguments);
1834 UserVariables.clear();
1836 AbstractVariables.clear();
1837 LabelsBeforeInsn.clear();
1838 LabelsAfterInsn.clear();
1843 // Register a source line with debug info. Returns the unique label that was
1844 // emitted and which provides correspondence to the source line list.
1845 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1851 DIDescriptor Scope(S);
1853 if (Scope.isCompileUnit()) {
1854 DICompileUnit CU(S);
1855 Fn = CU.getFilename();
1856 Dir = CU.getDirectory();
1857 } else if (Scope.isFile()) {
1859 Fn = F.getFilename();
1860 Dir = F.getDirectory();
1861 } else if (Scope.isSubprogram()) {
1863 Fn = SP.getFilename();
1864 Dir = SP.getDirectory();
1865 } else if (Scope.isLexicalBlockFile()) {
1866 DILexicalBlockFile DBF(S);
1867 Fn = DBF.getFilename();
1868 Dir = DBF.getDirectory();
1869 } else if (Scope.isLexicalBlock()) {
1870 DILexicalBlock DB(S);
1871 Fn = DB.getFilename();
1872 Dir = DB.getDirectory();
1874 llvm_unreachable("Unexpected scope info");
1876 Src = getOrCreateSourceID(
1877 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1879 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1882 //===----------------------------------------------------------------------===//
1884 //===----------------------------------------------------------------------===//
1886 // Compute the size and offset of a DIE. The offset is relative to start of the
1887 // CU. It returns the offset after laying out the DIE.
1888 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1889 // Get the children.
1890 const std::vector<DIE *> &Children = Die->getChildren();
1892 // Record the abbreviation.
1893 assignAbbrevNumber(Die->getAbbrev());
1895 // Get the abbreviation for this DIE.
1896 const DIEAbbrev &Abbrev = Die->getAbbrev();
1899 Die->setOffset(Offset);
1901 // Start the size with the size of abbreviation code.
1902 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1904 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1905 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1907 // Size the DIE attribute values.
1908 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1909 // Size attribute value.
1910 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1912 // Size the DIE children if any.
1913 if (!Children.empty()) {
1914 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1915 "Children flag not set");
1917 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1918 Offset = computeSizeAndOffset(Children[j], Offset);
1920 // End of children marker.
1921 Offset += sizeof(int8_t);
1924 Die->setSize(Offset - Die->getOffset());
1928 // Compute the size and offset for each DIE.
1929 void DwarfFile::computeSizeAndOffsets() {
1930 // Offset from the first CU in the debug info section is 0 initially.
1931 unsigned SecOffset = 0;
1933 // Iterate over each compile unit and set the size and offsets for each
1934 // DIE within each compile unit. All offsets are CU relative.
1935 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1938 (*I)->setDebugInfoOffset(SecOffset);
1940 // CU-relative offset is reset to 0 here.
1941 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1942 (*I)->getHeaderSize(); // Unit-specific headers
1944 // EndOffset here is CU-relative, after laying out
1945 // all of the CU DIE.
1946 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1947 SecOffset += EndOffset;
1951 // Emit initial Dwarf sections with a label at the start of each one.
1952 void DwarfDebug::emitSectionLabels() {
1953 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1955 // Dwarf sections base addresses.
1956 DwarfInfoSectionSym =
1957 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1958 if (useSplitDwarf())
1959 DwarfInfoDWOSectionSym =
1960 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1961 DwarfAbbrevSectionSym =
1962 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1963 if (useSplitDwarf())
1964 DwarfAbbrevDWOSectionSym = emitSectionSym(
1965 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1966 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1968 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1969 emitSectionSym(Asm, MacroInfo);
1971 DwarfLineSectionSym =
1972 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1973 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1974 if (GenerateGnuPubSections) {
1975 DwarfGnuPubNamesSectionSym =
1976 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1977 DwarfGnuPubTypesSectionSym =
1978 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1979 } else if (HasDwarfPubSections) {
1980 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1981 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1984 DwarfStrSectionSym =
1985 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1986 if (useSplitDwarf()) {
1987 DwarfStrDWOSectionSym =
1988 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1989 DwarfAddrSectionSym =
1990 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1992 DwarfDebugRangeSectionSym =
1993 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1995 DwarfDebugLocSectionSym =
1996 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1999 // Recursively emits a debug information entry.
2000 void DwarfDebug::emitDIE(DIE *Die) {
2001 // Get the abbreviation for this DIE.
2002 const DIEAbbrev &Abbrev = Die->getAbbrev();
2004 // Emit the code (index) for the abbreviation.
2005 if (Asm->isVerbose())
2006 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2007 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2008 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2009 dwarf::TagString(Abbrev.getTag()));
2010 Asm->EmitULEB128(Abbrev.getNumber());
2012 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2013 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2015 // Emit the DIE attribute values.
2016 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2017 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2018 dwarf::Form Form = AbbrevData[i].getForm();
2019 assert(Form && "Too many attributes for DIE (check abbreviation)");
2021 if (Asm->isVerbose())
2022 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2025 case dwarf::DW_AT_abstract_origin:
2026 case dwarf::DW_AT_type:
2027 case dwarf::DW_AT_friend:
2028 case dwarf::DW_AT_specification:
2029 case dwarf::DW_AT_import:
2030 case dwarf::DW_AT_containing_type: {
2031 DIEEntry *E = cast<DIEEntry>(Values[i]);
2032 DIE *Origin = E->getEntry();
2033 unsigned Addr = Origin->getOffset();
2034 if (Form == dwarf::DW_FORM_ref_addr) {
2035 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2036 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2037 // section. Origin->getOffset() returns the offset from start of the
2039 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2040 assert(CU && "CUDie should belong to a CU.");
2041 Addr += CU->getDebugInfoOffset();
2042 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2043 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2044 DIEEntry::getRefAddrSize(Asm));
2046 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2047 CU->getSectionSym(),
2048 DIEEntry::getRefAddrSize(Asm));
2050 // Make sure Origin belong to the same CU.
2051 assert(Die->getUnit() == Origin->getUnit() &&
2052 "The referenced DIE should belong to the same CU in ref4");
2053 Asm->EmitInt32(Addr);
2057 case dwarf::DW_AT_location: {
2058 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2059 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2060 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2062 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2064 Values[i]->EmitValue(Asm, Form);
2068 case dwarf::DW_AT_accessibility: {
2069 if (Asm->isVerbose()) {
2070 DIEInteger *V = cast<DIEInteger>(Values[i]);
2071 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2073 Values[i]->EmitValue(Asm, Form);
2077 // Emit an attribute using the defined form.
2078 Values[i]->EmitValue(Asm, Form);
2083 // Emit the DIE children if any.
2084 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2085 const std::vector<DIE *> &Children = Die->getChildren();
2087 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2088 emitDIE(Children[j]);
2090 Asm->OutStreamer.AddComment("End Of Children Mark");
2095 // Emit the various dwarf units to the unit section USection with
2096 // the abbreviations going into ASection.
2097 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2098 const MCSymbol *ASectionSym) {
2099 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2101 DwarfUnit *TheU = *I;
2102 DIE *Die = TheU->getUnitDie();
2103 const MCSection *USection = TheU->getSection();
2104 Asm->OutStreamer.SwitchSection(USection);
2106 // Emit the compile units header.
2107 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2109 // Emit size of content not including length itself
2110 Asm->OutStreamer.AddComment("Length of Unit");
2111 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2113 TheU->emitHeader(ASection, ASectionSym);
2116 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2120 // Emit the debug info section.
2121 void DwarfDebug::emitDebugInfo() {
2122 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2124 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2125 DwarfAbbrevSectionSym);
2128 // Emit the abbreviation section.
2129 void DwarfDebug::emitAbbreviations() {
2130 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2132 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2135 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2136 // Check to see if it is worth the effort.
2137 if (!Abbreviations.empty()) {
2138 // Start the debug abbrev section.
2139 Asm->OutStreamer.SwitchSection(Section);
2141 // For each abbrevation.
2142 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2143 // Get abbreviation data
2144 const DIEAbbrev *Abbrev = Abbreviations[i];
2146 // Emit the abbrevations code (base 1 index.)
2147 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2149 // Emit the abbreviations data.
2153 // Mark end of abbreviations.
2154 Asm->EmitULEB128(0, "EOM(3)");
2158 // Emit the last address of the section and the end of the line matrix.
2159 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2160 // Define last address of section.
2161 Asm->OutStreamer.AddComment("Extended Op");
2164 Asm->OutStreamer.AddComment("Op size");
2165 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2166 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2167 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2169 Asm->OutStreamer.AddComment("Section end label");
2171 Asm->OutStreamer.EmitSymbolValue(
2172 Asm->GetTempSymbol("section_end", SectionEnd),
2173 Asm->getDataLayout().getPointerSize());
2175 // Mark end of matrix.
2176 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2182 // Emit visible names into a hashed accelerator table section.
2183 void DwarfDebug::emitAccelNames() {
2185 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2186 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2187 E = getUnits().end();
2189 DwarfUnit *TheU = *I;
2190 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2191 for (StringMap<std::vector<const DIE *> >::const_iterator
2195 StringRef Name = GI->getKey();
2196 const std::vector<const DIE *> &Entities = GI->second;
2197 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2198 DE = Entities.end();
2200 AT.AddName(Name, *DI);
2204 AT.FinalizeTable(Asm, "Names");
2205 Asm->OutStreamer.SwitchSection(
2206 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2207 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2208 Asm->OutStreamer.EmitLabel(SectionBegin);
2210 // Emit the full data.
2211 AT.Emit(Asm, SectionBegin, &InfoHolder);
2214 // Emit objective C classes and categories into a hashed accelerator table
2216 void DwarfDebug::emitAccelObjC() {
2218 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2219 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2220 E = getUnits().end();
2222 DwarfUnit *TheU = *I;
2223 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2224 for (StringMap<std::vector<const DIE *> >::const_iterator
2228 StringRef Name = GI->getKey();
2229 const std::vector<const DIE *> &Entities = GI->second;
2230 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2231 DE = Entities.end();
2233 AT.AddName(Name, *DI);
2237 AT.FinalizeTable(Asm, "ObjC");
2238 Asm->OutStreamer.SwitchSection(
2239 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2240 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2241 Asm->OutStreamer.EmitLabel(SectionBegin);
2243 // Emit the full data.
2244 AT.Emit(Asm, SectionBegin, &InfoHolder);
2247 // Emit namespace dies into a hashed accelerator table.
2248 void DwarfDebug::emitAccelNamespaces() {
2250 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2251 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2252 E = getUnits().end();
2254 DwarfUnit *TheU = *I;
2255 const StringMap<std::vector<const DIE *> > &Names =
2256 TheU->getAccelNamespace();
2257 for (StringMap<std::vector<const DIE *> >::const_iterator
2261 StringRef Name = GI->getKey();
2262 const std::vector<const DIE *> &Entities = GI->second;
2263 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2264 DE = Entities.end();
2266 AT.AddName(Name, *DI);
2270 AT.FinalizeTable(Asm, "namespac");
2271 Asm->OutStreamer.SwitchSection(
2272 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2273 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2274 Asm->OutStreamer.EmitLabel(SectionBegin);
2276 // Emit the full data.
2277 AT.Emit(Asm, SectionBegin, &InfoHolder);
2280 // Emit type dies into a hashed accelerator table.
2281 void DwarfDebug::emitAccelTypes() {
2282 std::vector<DwarfAccelTable::Atom> Atoms;
2284 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2286 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2288 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2289 DwarfAccelTable AT(Atoms);
2290 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2291 E = getUnits().end();
2293 DwarfUnit *TheU = *I;
2294 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2295 TheU->getAccelTypes();
2297 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2301 StringRef Name = GI->getKey();
2302 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2304 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2305 DI = Entities.begin(),
2306 DE = Entities.end();
2308 AT.AddName(Name, DI->first, DI->second);
2312 AT.FinalizeTable(Asm, "types");
2313 Asm->OutStreamer.SwitchSection(
2314 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2315 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2316 Asm->OutStreamer.EmitLabel(SectionBegin);
2318 // Emit the full data.
2319 AT.Emit(Asm, SectionBegin, &InfoHolder);
2322 // Public name handling.
2323 // The format for the various pubnames:
2325 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2326 // for the DIE that is named.
2328 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2329 // into the CU and the index value is computed according to the type of value
2330 // for the DIE that is named.
2332 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2333 // it's the offset within the debug_info/debug_types dwo section, however, the
2334 // reference in the pubname header doesn't change.
2336 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2337 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2339 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2341 // We could have a specification DIE that has our most of our knowledge,
2342 // look for that now.
2343 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2345 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2346 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2347 Linkage = dwarf::GIEL_EXTERNAL;
2348 } else if (Die->findAttribute(dwarf::DW_AT_external))
2349 Linkage = dwarf::GIEL_EXTERNAL;
2351 switch (Die->getTag()) {
2352 case dwarf::DW_TAG_class_type:
2353 case dwarf::DW_TAG_structure_type:
2354 case dwarf::DW_TAG_union_type:
2355 case dwarf::DW_TAG_enumeration_type:
2356 return dwarf::PubIndexEntryDescriptor(
2357 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2358 ? dwarf::GIEL_STATIC
2359 : dwarf::GIEL_EXTERNAL);
2360 case dwarf::DW_TAG_typedef:
2361 case dwarf::DW_TAG_base_type:
2362 case dwarf::DW_TAG_subrange_type:
2363 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2364 case dwarf::DW_TAG_namespace:
2365 return dwarf::GIEK_TYPE;
2366 case dwarf::DW_TAG_subprogram:
2367 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2368 case dwarf::DW_TAG_constant:
2369 case dwarf::DW_TAG_variable:
2370 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2371 case dwarf::DW_TAG_enumerator:
2372 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2373 dwarf::GIEL_STATIC);
2375 return dwarf::GIEK_NONE;
2379 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2381 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2382 const MCSection *PSec =
2383 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2384 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2386 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2387 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2388 for (unsigned i = 0; i != Units.size(); ++i) {
2389 DwarfUnit *TheU = Units[i];
2390 unsigned ID = TheU->getUniqueID();
2392 // Start the dwarf pubnames section.
2393 Asm->OutStreamer.SwitchSection(PSec);
2395 // Emit a label so we can reference the beginning of this pubname section.
2397 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2400 Asm->OutStreamer.AddComment("Length of Public Names Info");
2401 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2402 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2403 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2405 Asm->OutStreamer.EmitLabel(BeginLabel);
2407 Asm->OutStreamer.AddComment("DWARF Version");
2408 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2410 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2411 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2413 Asm->OutStreamer.AddComment("Compilation Unit Length");
2414 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2416 // Emit the pubnames for this compilation unit.
2417 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2418 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2421 const char *Name = GI->getKeyData();
2422 const DIE *Entity = GI->second;
2424 Asm->OutStreamer.AddComment("DIE offset");
2425 Asm->EmitInt32(Entity->getOffset());
2428 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2429 Asm->OutStreamer.AddComment(
2430 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2431 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2432 Asm->EmitInt8(Desc.toBits());
2435 Asm->OutStreamer.AddComment("External Name");
2436 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2439 Asm->OutStreamer.AddComment("End Mark");
2441 Asm->OutStreamer.EmitLabel(EndLabel);
2445 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2446 const MCSection *PSec =
2447 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2448 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2450 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2451 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2452 for (unsigned i = 0; i != Units.size(); ++i) {
2453 DwarfUnit *TheU = Units[i];
2454 unsigned ID = TheU->getUniqueID();
2456 // Start the dwarf pubtypes section.
2457 Asm->OutStreamer.SwitchSection(PSec);
2459 // Emit a label so we can reference the beginning of this pubtype section.
2461 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2464 Asm->OutStreamer.AddComment("Length of Public Types Info");
2465 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2466 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2467 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2469 Asm->OutStreamer.EmitLabel(BeginLabel);
2471 Asm->OutStreamer.AddComment("DWARF Version");
2472 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2474 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2475 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2477 Asm->OutStreamer.AddComment("Compilation Unit Length");
2478 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2480 // Emit the pubtypes.
2481 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2482 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2485 const char *Name = GI->getKeyData();
2486 const DIE *Entity = GI->second;
2488 Asm->OutStreamer.AddComment("DIE offset");
2489 Asm->EmitInt32(Entity->getOffset());
2492 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2493 Asm->OutStreamer.AddComment(
2494 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2495 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2496 Asm->EmitInt8(Desc.toBits());
2499 Asm->OutStreamer.AddComment("External Name");
2501 // Emit the name with a terminating null byte.
2502 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2505 Asm->OutStreamer.AddComment("End Mark");
2507 Asm->OutStreamer.EmitLabel(EndLabel);
2511 // Emit strings into a string section.
2512 void DwarfFile::emitStrings(const MCSection *StrSection,
2513 const MCSection *OffsetSection = NULL,
2514 const MCSymbol *StrSecSym = NULL) {
2516 if (StringPool.empty())
2519 // Start the dwarf str section.
2520 Asm->OutStreamer.SwitchSection(StrSection);
2522 // Get all of the string pool entries and put them in an array by their ID so
2523 // we can sort them.
2525 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2528 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2529 I = StringPool.begin(),
2530 E = StringPool.end();
2532 Entries.push_back(std::make_pair(I->second.second, &*I));
2534 array_pod_sort(Entries.begin(), Entries.end());
2536 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2537 // Emit a label for reference from debug information entries.
2538 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2540 // Emit the string itself with a terminating null byte.
2541 Asm->OutStreamer.EmitBytes(
2542 StringRef(Entries[i].second->getKeyData(),
2543 Entries[i].second->getKeyLength() + 1));
2546 // If we've got an offset section go ahead and emit that now as well.
2547 if (OffsetSection) {
2548 Asm->OutStreamer.SwitchSection(OffsetSection);
2549 unsigned offset = 0;
2550 unsigned size = 4; // FIXME: DWARF64 is 8.
2551 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2552 Asm->OutStreamer.EmitIntValue(offset, size);
2553 offset += Entries[i].second->getKeyLength() + 1;
2558 // Emit addresses into the section given.
2559 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2561 if (AddressPool.empty())
2564 // Start the dwarf addr section.
2565 Asm->OutStreamer.SwitchSection(AddrSection);
2567 // Order the address pool entries by ID
2568 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2570 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2571 E = AddressPool.end();
2573 Entries[I->second] = I->first;
2575 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2576 // Emit an expression for reference from debug information entries.
2577 if (const MCExpr *Expr = Entries[i])
2578 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2580 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2584 // Emit visible names into a debug str section.
2585 void DwarfDebug::emitDebugStr() {
2586 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2587 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2590 // Emit locations into the debug loc section.
2591 void DwarfDebug::emitDebugLoc() {
2592 if (DotDebugLocEntries.empty())
2595 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2596 I = DotDebugLocEntries.begin(),
2597 E = DotDebugLocEntries.end();
2599 DotDebugLocEntry &Entry = *I;
2600 if (I + 1 != DotDebugLocEntries.end())
2604 // Start the dwarf loc section.
2605 Asm->OutStreamer.SwitchSection(
2606 Asm->getObjFileLowering().getDwarfLocSection());
2607 unsigned char Size = Asm->getDataLayout().getPointerSize();
2608 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2610 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2611 I = DotDebugLocEntries.begin(),
2612 E = DotDebugLocEntries.end();
2613 I != E; ++I, ++index) {
2614 DotDebugLocEntry &Entry = *I;
2615 if (Entry.isMerged())
2617 if (Entry.isEmpty()) {
2618 Asm->OutStreamer.EmitIntValue(0, Size);
2619 Asm->OutStreamer.EmitIntValue(0, Size);
2620 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2622 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2623 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2624 DIVariable DV(Entry.getVariable());
2625 Asm->OutStreamer.AddComment("Loc expr size");
2626 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2627 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2628 Asm->EmitLabelDifference(end, begin, 2);
2629 Asm->OutStreamer.EmitLabel(begin);
2630 if (Entry.isInt()) {
2631 DIBasicType BTy(DV.getType());
2632 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2633 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2634 Asm->OutStreamer.AddComment("DW_OP_consts");
2635 Asm->EmitInt8(dwarf::DW_OP_consts);
2636 Asm->EmitSLEB128(Entry.getInt());
2638 Asm->OutStreamer.AddComment("DW_OP_constu");
2639 Asm->EmitInt8(dwarf::DW_OP_constu);
2640 Asm->EmitULEB128(Entry.getInt());
2642 } else if (Entry.isLocation()) {
2643 MachineLocation Loc = Entry.getLoc();
2644 if (!DV.hasComplexAddress())
2646 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2648 // Complex address entry.
2649 unsigned N = DV.getNumAddrElements();
2651 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2652 if (Loc.getOffset()) {
2654 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2655 Asm->OutStreamer.AddComment("DW_OP_deref");
2656 Asm->EmitInt8(dwarf::DW_OP_deref);
2657 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2658 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2659 Asm->EmitSLEB128(DV.getAddrElement(1));
2661 // If first address element is OpPlus then emit
2662 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2663 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2664 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2668 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2671 // Emit remaining complex address elements.
2672 for (; i < N; ++i) {
2673 uint64_t Element = DV.getAddrElement(i);
2674 if (Element == DIBuilder::OpPlus) {
2675 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2676 Asm->EmitULEB128(DV.getAddrElement(++i));
2677 } else if (Element == DIBuilder::OpDeref) {
2679 Asm->EmitInt8(dwarf::DW_OP_deref);
2681 llvm_unreachable("unknown Opcode found in complex address");
2685 // else ... ignore constant fp. There is not any good way to
2686 // to represent them here in dwarf.
2687 Asm->OutStreamer.EmitLabel(end);
2692 struct SymbolCUSorter {
2693 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2694 const MCStreamer &Streamer;
2696 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2697 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2698 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2700 // Symbols with no order assigned should be placed at the end.
2701 // (e.g. section end labels)
2703 IA = (unsigned)(-1);
2705 IB = (unsigned)(-1);
2710 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2711 return (A->getUniqueID() < B->getUniqueID());
2715 const MCSymbol *Start, *End;
2718 // Emit a debug aranges section, containing a CU lookup for any
2719 // address we can tie back to a CU.
2720 void DwarfDebug::emitDebugARanges() {
2721 // Start the dwarf aranges section.
2722 Asm->OutStreamer.SwitchSection(
2723 Asm->getObjFileLowering().getDwarfARangesSection());
2725 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2729 // Build a list of sections used.
2730 std::vector<const MCSection *> Sections;
2731 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2733 const MCSection *Section = it->first;
2734 Sections.push_back(Section);
2737 // Sort the sections into order.
2738 // This is only done to ensure consistent output order across different runs.
2739 std::sort(Sections.begin(), Sections.end(), SectionSort);
2741 // Build a set of address spans, sorted by CU.
2742 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2743 const MCSection *Section = Sections[SecIdx];
2744 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2745 if (List.size() < 2)
2748 // Sort the symbols by offset within the section.
2749 SymbolCUSorter sorter(Asm->OutStreamer);
2750 std::sort(List.begin(), List.end(), sorter);
2752 // If we have no section (e.g. common), just write out
2753 // individual spans for each symbol.
2754 if (Section == NULL) {
2755 for (size_t n = 0; n < List.size(); n++) {
2756 const SymbolCU &Cur = List[n];
2759 Span.Start = Cur.Sym;
2762 Spans[Cur.CU].push_back(Span);
2765 // Build spans between each label.
2766 const MCSymbol *StartSym = List[0].Sym;
2767 for (size_t n = 1; n < List.size(); n++) {
2768 const SymbolCU &Prev = List[n - 1];
2769 const SymbolCU &Cur = List[n];
2771 // Try and build the longest span we can within the same CU.
2772 if (Cur.CU != Prev.CU) {
2774 Span.Start = StartSym;
2776 Spans[Prev.CU].push_back(Span);
2783 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2785 // Build a list of CUs used.
2786 std::vector<DwarfCompileUnit *> CUs;
2787 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2788 DwarfCompileUnit *CU = it->first;
2792 // Sort the CU list (again, to ensure consistent output order).
2793 std::sort(CUs.begin(), CUs.end(), CUSort);
2795 // Emit an arange table for each CU we used.
2796 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2797 DwarfCompileUnit *CU = CUs[CUIdx];
2798 std::vector<ArangeSpan> &List = Spans[CU];
2800 // Emit size of content not including length itself.
2801 unsigned ContentSize =
2802 sizeof(int16_t) + // DWARF ARange version number
2803 sizeof(int32_t) + // Offset of CU in the .debug_info section
2804 sizeof(int8_t) + // Pointer Size (in bytes)
2805 sizeof(int8_t); // Segment Size (in bytes)
2807 unsigned TupleSize = PtrSize * 2;
2809 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2811 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2813 ContentSize += Padding;
2814 ContentSize += (List.size() + 1) * TupleSize;
2816 // For each compile unit, write the list of spans it covers.
2817 Asm->OutStreamer.AddComment("Length of ARange Set");
2818 Asm->EmitInt32(ContentSize);
2819 Asm->OutStreamer.AddComment("DWARF Arange version number");
2820 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2821 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2822 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2823 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2824 Asm->EmitInt8(PtrSize);
2825 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2828 Asm->OutStreamer.EmitFill(Padding, 0xff);
2830 for (unsigned n = 0; n < List.size(); n++) {
2831 const ArangeSpan &Span = List[n];
2832 Asm->EmitLabelReference(Span.Start, PtrSize);
2834 // Calculate the size as being from the span start to it's end.
2836 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2838 // For symbols without an end marker (e.g. common), we
2839 // write a single arange entry containing just that one symbol.
2840 uint64_t Size = SymSize[Span.Start];
2844 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2848 Asm->OutStreamer.AddComment("ARange terminator");
2849 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2850 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2854 // Emit visible names into a debug ranges section.
2855 void DwarfDebug::emitDebugRanges() {
2856 // Start the dwarf ranges section.
2857 Asm->OutStreamer.SwitchSection(
2858 Asm->getObjFileLowering().getDwarfRangesSection());
2860 // Size for our labels.
2861 unsigned char Size = Asm->getDataLayout().getPointerSize();
2863 // Grab the specific ranges for the compile units in the module.
2864 for (MapVector<const MDNode *, DwarfCompileUnit *>::iterator
2868 DwarfCompileUnit *TheCU = I->second;
2870 // Emit a symbol so we can find the beginning of our ranges.
2871 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2873 // Iterate over the misc ranges for the compile units in the module.
2874 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2875 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2876 E = RangeLists.end();
2878 const RangeSpanList &List = *I;
2880 // Emit our symbol so we can find the beginning of the range.
2881 Asm->OutStreamer.EmitLabel(List.getSym());
2883 for (SmallVectorImpl<RangeSpan>::const_iterator
2884 RI = List.getRanges().begin(),
2885 RE = List.getRanges().end();
2887 const RangeSpan &Range = *RI;
2888 const MCSymbol *Begin = Range.getStart();
2889 const MCSymbol *End = Range.getEnd();
2890 assert(Begin && "Range without a begin symbol?");
2891 assert(End && "Range without an end symbol?");
2892 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2893 Asm->OutStreamer.EmitSymbolValue(End, Size);
2896 // And terminate the list with two 0 values.
2897 Asm->OutStreamer.EmitIntValue(0, Size);
2898 Asm->OutStreamer.EmitIntValue(0, Size);
2901 // Now emit a range for the CU itself.
2902 if (useCURanges()) {
2903 Asm->OutStreamer.EmitLabel(
2904 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2905 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2906 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2907 RangeSpan Range = Ranges[i];
2908 const MCSymbol *Begin = Range.getStart();
2909 const MCSymbol *End = Range.getEnd();
2910 assert(Begin && "Range without a begin symbol?");
2911 assert(End && "Range without an end symbol?");
2912 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2913 Asm->OutStreamer.EmitSymbolValue(End, Size);
2915 // And terminate the list with two 0 values.
2916 Asm->OutStreamer.EmitIntValue(0, Size);
2917 Asm->OutStreamer.EmitIntValue(0, Size);
2922 // DWARF5 Experimental Separate Dwarf emitters.
2924 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2926 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2927 U->getCUNode().getSplitDebugFilename());
2929 // Relocate to the beginning of the addr_base section, else 0 for the
2930 // beginning of the one for this compile unit.
2931 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2932 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2934 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2936 if (!CompilationDir.empty())
2937 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2939 addGnuPubAttributes(NewU, Die);
2941 SkeletonHolder.addUnit(NewU);
2944 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2945 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2946 // DW_AT_ranges_base, DW_AT_addr_base.
2947 // TODO: Implement DW_AT_ranges_base.
2948 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2950 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2951 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2952 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2953 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2954 DwarfInfoSectionSym);
2956 // DW_AT_stmt_list is a offset of line number information for this
2957 // compile unit in debug_line section.
2958 // FIXME: Should handle multiple compile units.
2959 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2960 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2962 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2964 initSkeletonUnit(CU, Die, NewCU);
2969 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2971 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
2973 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2974 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2975 TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
2976 NewTU->setTypeSignature(TU->getTypeSignature());
2977 NewTU->setType(NULL);
2979 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2981 initSkeletonUnit(TU, Die, NewTU);
2985 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2986 // compile units that would normally be in debug_info.
2987 void DwarfDebug::emitDebugInfoDWO() {
2988 assert(useSplitDwarf() && "No split dwarf debug info?");
2989 InfoHolder.emitUnits(this,
2990 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2991 DwarfAbbrevDWOSectionSym);
2994 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2995 // abbreviations for the .debug_info.dwo section.
2996 void DwarfDebug::emitDebugAbbrevDWO() {
2997 assert(useSplitDwarf() && "No split dwarf?");
2998 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3001 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3002 // string section and is identical in format to traditional .debug_str
3004 void DwarfDebug::emitDebugStrDWO() {
3005 assert(useSplitDwarf() && "No split dwarf?");
3006 const MCSection *OffSec =
3007 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3008 const MCSymbol *StrSym = DwarfStrSectionSym;
3009 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3013 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3014 StringRef Identifier, DIE *RefDie,
3015 DICompositeType CTy) {
3016 // Flag the type unit reference as a declaration so that if it contains
3017 // members (implicit special members, static data member definitions, member
3018 // declarations for definitions in this CU, etc) consumers don't get confused
3019 // and think this is a full definition.
3020 CUMap.begin()->second->addFlag(RefDie, dwarf::DW_AT_declaration);
3022 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3024 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3028 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3029 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3030 InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3032 InfoHolder.addUnit(NewTU);
3034 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3035 CUNode.getLanguage());
3038 Hash.update(Identifier);
3039 // ... take the least significant 8 bytes and return those. Our MD5
3040 // implementation always returns its results in little endian, swap bytes
3042 MD5::MD5Result Result;
3044 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3045 NewTU->setTypeSignature(Signature);
3046 if (useSplitDwarf())
3047 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3049 NewTU->setType(NewTU->createTypeDIE(CTy));
3053 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3054 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3056 CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);