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"),
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
107 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
108 cl::desc("Generate DW_AT_ranges for compile units"),
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
118 /// resolve - Look in the DwarfDebug map for the MDNode that
119 /// corresponds to the reference.
120 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
121 return DD->resolve(Ref);
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType();
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable()) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
181 PrevLabel(NULL), GlobalRangeCount(0),
182 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
187 DwarfAddrSectionSym = 0;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
189 FunctionBeginSym = FunctionEndSym = 0;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber
214 : getDwarfVersionFromModule(MMI->getModule());
217 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
222 // Switch to the specified MCSection and emit an assembler
223 // temporary label to it if SymbolStem is specified.
224 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
225 const char *SymbolStem = 0) {
226 Asm->OutStreamer.SwitchSection(Section);
230 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
231 Asm->OutStreamer.EmitLabel(TmpSym);
235 DwarfFile::~DwarfFile() {
236 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
241 MCSymbol *DwarfFile::getStringPoolSym() {
242 return Asm->GetTempSymbol(StringPref);
245 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
246 std::pair<MCSymbol *, unsigned> &Entry =
247 StringPool.GetOrCreateValue(Str).getValue();
251 Entry.second = NextStringPoolNumber++;
252 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
255 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
256 std::pair<MCSymbol *, unsigned> &Entry =
257 StringPool.GetOrCreateValue(Str).getValue();
261 Entry.second = NextStringPoolNumber++;
262 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
266 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
267 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
270 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
271 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
272 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
274 ++NextAddrPoolNumber;
275 return P.first->second;
278 // Define a unique number for the abbreviation.
280 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
281 // Check the set for priors.
282 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
284 // If it's newly added.
285 if (InSet == &Abbrev) {
286 // Add to abbreviation list.
287 Abbreviations.push_back(&Abbrev);
289 // Assign the vector position + 1 as its number.
290 Abbrev.setNumber(Abbreviations.size());
292 // Assign existing abbreviation number.
293 Abbrev.setNumber(InSet->getNumber());
297 static bool isObjCClass(StringRef Name) {
298 return Name.startswith("+") || Name.startswith("-");
301 static bool hasObjCCategory(StringRef Name) {
302 if (!isObjCClass(Name))
305 return Name.find(") ") != StringRef::npos;
308 static void getObjCClassCategory(StringRef In, StringRef &Class,
309 StringRef &Category) {
310 if (!hasObjCCategory(In)) {
311 Class = In.slice(In.find('[') + 1, In.find(' '));
316 Class = In.slice(In.find('[') + 1, In.find('('));
317 Category = In.slice(In.find('[') + 1, In.find(' '));
321 static StringRef getObjCMethodName(StringRef In) {
322 return In.slice(In.find(' ') + 1, In.find(']'));
325 // Helper for sorting sections into a stable output order.
326 static bool SectionSort(const MCSection *A, const MCSection *B) {
327 std::string LA = (A ? A->getLabelBeginName() : "");
328 std::string LB = (B ? B->getLabelBeginName() : "");
332 // Add the various names to the Dwarf accelerator table names.
333 // TODO: Determine whether or not we should add names for programs
334 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
335 // is only slightly different than the lookup of non-standard ObjC names.
336 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
337 if (!SP.isDefinition())
339 TheU->addAccelName(SP.getName(), Die);
341 // If the linkage name is different than the name, go ahead and output
342 // that as well into the name table.
343 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
344 TheU->addAccelName(SP.getLinkageName(), Die);
346 // If this is an Objective-C selector name add it to the ObjC accelerator
348 if (isObjCClass(SP.getName())) {
349 StringRef Class, Category;
350 getObjCClassCategory(SP.getName(), Class, Category);
351 TheU->addAccelObjC(Class, Die);
353 TheU->addAccelObjC(Category, Die);
354 // Also add the base method name to the name table.
355 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
359 /// isSubprogramContext - Return true if Context is either a subprogram
360 /// or another context nested inside a subprogram.
361 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
364 DIDescriptor D(Context);
365 if (D.isSubprogram())
368 return isSubprogramContext(resolve(DIType(Context).getContext()));
372 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
373 // and DW_AT_high_pc attributes. If there are global variables in this
374 // scope then create and insert DIEs for these variables.
375 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
377 DIE *SPDie = SPCU->getDIE(SP);
379 assert(SPDie && "Unable to find subprogram DIE!");
381 // If we're updating an abstract DIE, then we will be adding the children and
382 // object pointer later on. But what we don't want to do is process the
383 // concrete DIE twice.
384 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
385 // Pick up abstract subprogram DIE.
387 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
388 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
390 DISubprogram SPDecl = SP.getFunctionDeclaration();
391 if (!SPDecl.isSubprogram()) {
392 // There is not any need to generate specification DIE for a function
393 // defined at compile unit level. If a function is defined inside another
394 // function then gdb prefers the definition at top level and but does not
395 // expect specification DIE in parent function. So avoid creating
396 // specification DIE for a function defined inside a function.
397 DIScope SPContext = resolve(SP.getContext());
398 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
399 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
400 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 DICompositeType SPTy = SP.getType();
404 DIArray Args = SPTy.getTypeArray();
405 uint16_t SPTag = SPTy.getTag();
406 if (SPTag == dwarf::DW_TAG_subroutine_type)
407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
410 DIType ATy(Args.getElement(i));
411 SPCU->addType(Arg, ATy);
412 if (ATy.isArtificial())
413 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
414 if (ATy.isObjectPointer())
415 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
417 DIE *SPDeclDie = SPDie;
418 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
419 *SPCU->getUnitDie());
420 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
425 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
428 // Add this range to the list of ranges for the CU.
429 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
430 SPCU->addRange(llvm_move(Span));
432 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
433 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
434 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
436 // Add name to the name table, we do this here because we're guaranteed
437 // to have concrete versions of our DW_TAG_subprogram nodes.
438 addSubprogramNames(SPCU, SP, SPDie);
443 /// Check whether we should create a DIE for the given Scope, return true
444 /// if we don't create a DIE (the corresponding DIE is null).
445 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
446 if (Scope->isAbstractScope())
449 // We don't create a DIE if there is no Range.
450 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
454 if (Ranges.size() > 1)
457 // We don't create a DIE if we have a single Range and the end label
459 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
460 MCSymbol *End = getLabelAfterInsn(RI->second);
464 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
465 dwarf::Attribute A, const MCSymbol *L,
466 const MCSymbol *Sec) {
467 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
468 U->addSectionLabel(D, A, L);
470 U->addSectionDelta(D, A, L, Sec);
473 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
474 const SmallVectorImpl<InsnRange> &Range) {
475 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
476 // emitting it appropriately.
477 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
478 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
479 DwarfDebugRangeSectionSym);
481 RangeSpanList List(RangeSym);
482 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
485 RangeSpan Span(getLabelBeforeInsn(RI->first),
486 getLabelAfterInsn(RI->second));
487 List.addRange(llvm_move(Span));
490 // Add the range list to the set of ranges to be emitted.
491 TheCU->addRangeList(llvm_move(List));
494 // Construct new DW_TAG_lexical_block for this scope and attach
495 // DW_AT_low_pc/DW_AT_high_pc labels.
496 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
497 LexicalScope *Scope) {
498 if (isLexicalScopeDIENull(Scope))
501 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
502 if (Scope->isAbstractScope())
505 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
507 // If we have multiple ranges, emit them into the range section.
508 if (ScopeRanges.size() > 1) {
509 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
513 // Construct the address range for this DIE.
514 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
515 MCSymbol *Start = getLabelBeforeInsn(RI->first);
516 MCSymbol *End = getLabelAfterInsn(RI->second);
517 assert(End && "End label should not be null!");
519 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
520 assert(End->isDefined() && "Invalid end label for an inlined scope!");
522 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
523 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
528 // This scope represents inlined body of a function. Construct DIE to
529 // represent this concrete inlined copy of the function.
530 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
531 LexicalScope *Scope) {
532 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
533 assert(!ScopeRanges.empty() &&
534 "LexicalScope does not have instruction markers!");
536 if (!Scope->getScopeNode())
538 DIScope DS(Scope->getScopeNode());
539 DISubprogram InlinedSP = getDISubprogram(DS);
540 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
542 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
546 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
547 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
549 // If we have multiple ranges, emit them into the range section.
550 if (ScopeRanges.size() > 1)
551 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
553 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
554 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
555 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
557 if (StartLabel == 0 || EndLabel == 0)
558 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
560 assert(StartLabel->isDefined() &&
561 "Invalid starting label for an inlined scope!");
562 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
564 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
565 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
568 InlinedSubprogramDIEs.insert(OriginDIE);
570 // Add the call site information to the DIE.
571 DILocation DL(Scope->getInlinedAt());
572 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
573 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
574 TheCU->getUniqueID()));
575 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
577 // Add name to the name table, we do this here because we're guaranteed
578 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
579 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
584 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
586 SmallVectorImpl<DIE *> &Children) {
587 DIE *ObjectPointer = NULL;
589 // Collect arguments for current function.
590 if (LScopes.isCurrentFunctionScope(Scope))
591 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
592 if (DbgVariable *ArgDV = CurrentFnArguments[i])
594 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
595 Children.push_back(Arg);
596 if (ArgDV->isObjectPointer())
600 // Collect lexical scope children first.
601 const SmallVectorImpl<DbgVariable *> &Variables =
602 ScopeVariables.lookup(Scope);
603 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
604 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
605 Scope->isAbstractScope())) {
606 Children.push_back(Variable);
607 if (Variables[i]->isObjectPointer())
608 ObjectPointer = Variable;
610 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
611 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
612 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
613 Children.push_back(Nested);
614 return ObjectPointer;
617 // Construct a DIE for this scope.
618 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
619 LexicalScope *Scope) {
620 if (!Scope || !Scope->getScopeNode())
623 DIScope DS(Scope->getScopeNode());
625 SmallVector<DIE *, 8> Children;
626 DIE *ObjectPointer = NULL;
627 bool ChildrenCreated = false;
629 // We try to create the scope DIE first, then the children DIEs. This will
630 // avoid creating un-used children then removing them later when we find out
631 // the scope DIE is null.
632 DIE *ScopeDIE = NULL;
633 if (Scope->getInlinedAt())
634 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
635 else if (DS.isSubprogram()) {
636 ProcessedSPNodes.insert(DS);
637 if (Scope->isAbstractScope()) {
638 ScopeDIE = TheCU->getDIE(DS);
639 // Note down abstract DIE.
641 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
643 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
645 // Early exit when we know the scope DIE is going to be null.
646 if (isLexicalScopeDIENull(Scope))
649 // We create children here when we know the scope DIE is not going to be
650 // null and the children will be added to the scope DIE.
651 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
652 ChildrenCreated = true;
654 // There is no need to emit empty lexical block DIE.
655 std::pair<ImportedEntityMap::const_iterator,
656 ImportedEntityMap::const_iterator> Range =
658 ScopesWithImportedEntities.begin(),
659 ScopesWithImportedEntities.end(),
660 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
662 if (Children.empty() && Range.first == Range.second)
664 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
665 assert(ScopeDIE && "Scope DIE should not be null.");
666 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
668 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
672 assert(Children.empty() &&
673 "We create children only when the scope DIE is not null.");
676 if (!ChildrenCreated)
677 // We create children when the scope DIE is not null.
678 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
681 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
684 ScopeDIE->addChild(*I);
686 if (DS.isSubprogram() && ObjectPointer != NULL)
687 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
692 // Look up the source id with the given directory and source file names.
693 // If none currently exists, create a new id and insert it in the
694 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
696 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
698 // If we use .loc in assembly, we can't separate .file entries according to
699 // compile units. Thus all files will belong to the default compile unit.
701 // FIXME: add a better feature test than hasRawTextSupport. Even better,
702 // extend .file to support this.
703 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
706 // If FE did not provide a file name, then assume stdin.
707 if (FileName.empty())
708 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
710 // TODO: this might not belong here. See if we can factor this better.
711 if (DirName == CompilationDir)
714 // FileIDCUMap stores the current ID for the given compile unit.
715 unsigned SrcId = FileIDCUMap[CUID] + 1;
717 // We look up the CUID/file/dir by concatenating them with a zero byte.
718 SmallString<128> NamePair;
719 NamePair += utostr(CUID);
722 NamePair += '\0'; // Zero bytes are not allowed in paths.
723 NamePair += FileName;
725 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
726 if (Ent.getValue() != SrcId)
727 return Ent.getValue();
729 FileIDCUMap[CUID] = SrcId;
730 // Print out a .file directive to specify files for .loc directives.
731 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
736 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
737 if (!GenerateGnuPubSections)
740 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
741 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
742 DwarfGnuPubNamesSectionSym);
744 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
745 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
746 DwarfGnuPubTypesSectionSym);
749 // Create new DwarfCompileUnit for the given metadata node with tag
750 // DW_TAG_compile_unit.
751 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
752 StringRef FN = DIUnit.getFilename();
753 CompilationDir = DIUnit.getDirectory();
755 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
756 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
757 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
758 InfoHolder.addUnit(NewCU);
760 FileIDCUMap[NewCU->getUniqueID()] = 0;
761 // Call this to emit a .file directive if it wasn't emitted for the source
762 // file this CU comes from yet.
763 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
765 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
766 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
767 DIUnit.getLanguage());
768 NewCU->addString(Die, dwarf::DW_AT_name, FN);
770 // Define start line table label for each Compile Unit.
771 MCSymbol *LineTableStartSym =
772 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
773 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
774 NewCU->getUniqueID());
776 // Use a single line table if we are using .loc and generating assembly.
778 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
779 (NewCU->getUniqueID() == 0);
781 if (!useSplitDwarf()) {
782 // DW_AT_stmt_list is a offset of line number information for this
783 // compile unit in debug_line section. For split dwarf this is
784 // left in the skeleton CU and so not included.
785 // The line table entries are not always emitted in assembly, so it
786 // is not okay to use line_table_start here.
787 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
788 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
789 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
790 : LineTableStartSym);
791 else if (UseTheFirstCU)
792 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
794 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
795 DwarfLineSectionSym);
797 // If we're using split dwarf the compilation dir is going to be in the
798 // skeleton CU and so we don't need to duplicate it here.
799 if (!CompilationDir.empty())
800 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
802 addGnuPubAttributes(NewCU, Die);
805 if (DIUnit.isOptimized())
806 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
808 StringRef Flags = DIUnit.getFlags();
810 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
812 if (unsigned RVer = DIUnit.getRunTimeVersion())
813 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
814 dwarf::DW_FORM_data1, RVer);
819 if (useSplitDwarf()) {
820 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
821 DwarfInfoDWOSectionSym);
822 NewCU->setSkeleton(constructSkeletonCU(NewCU));
824 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
825 DwarfInfoSectionSym);
827 CUMap.insert(std::make_pair(DIUnit, NewCU));
828 CUDieMap.insert(std::make_pair(Die, NewCU));
832 // Construct subprogram DIE.
833 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
835 // FIXME: We should only call this routine once, however, during LTO if a
836 // program is defined in multiple CUs we could end up calling it out of
837 // beginModule as we walk the CUs.
839 DwarfCompileUnit *&CURef = SPMap[N];
845 if (!SP.isDefinition())
846 // This is a method declaration which will be handled while constructing
850 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
852 // Expose as a global name.
853 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
856 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
858 DIImportedEntity Module(N);
859 if (!Module.Verify())
861 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
862 constructImportedEntityDIE(TheCU, Module, D);
865 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
866 const MDNode *N, DIE *Context) {
867 DIImportedEntity Module(N);
868 if (!Module.Verify())
870 return constructImportedEntityDIE(TheCU, Module, Context);
873 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
874 const DIImportedEntity &Module,
876 assert(Module.Verify() &&
877 "Use one of the MDNode * overloads to handle invalid metadata");
878 assert(Context && "Should always have a context for an imported_module");
879 DIE *IMDie = new DIE(Module.getTag());
880 TheCU->insertDIE(Module, IMDie);
882 DIDescriptor Entity = Module.getEntity();
883 if (Entity.isNameSpace())
884 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
885 else if (Entity.isSubprogram())
886 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
887 else if (Entity.isType())
888 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
890 EntityDie = TheCU->getDIE(Entity);
891 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
892 Module.getContext().getDirectory(),
893 TheCU->getUniqueID());
894 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
895 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
896 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
897 StringRef Name = Module.getName();
899 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
900 Context->addChild(IMDie);
903 // Emit all Dwarf sections that should come prior to the content. Create
904 // global DIEs and emit initial debug info sections. This is invoked by
905 // the target AsmPrinter.
906 void DwarfDebug::beginModule() {
907 if (DisableDebugInfoPrinting)
910 const Module *M = MMI->getModule();
912 // If module has named metadata anchors then use them, otherwise scan the
913 // module using debug info finder to collect debug info.
914 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
917 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
919 // Emit initial sections so we can reference labels later.
922 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
923 DICompileUnit CUNode(CU_Nodes->getOperand(i));
924 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
925 DIArray ImportedEntities = CUNode.getImportedEntities();
926 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
927 ScopesWithImportedEntities.push_back(std::make_pair(
928 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
929 ImportedEntities.getElement(i)));
930 std::sort(ScopesWithImportedEntities.begin(),
931 ScopesWithImportedEntities.end(), less_first());
932 DIArray GVs = CUNode.getGlobalVariables();
933 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
934 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
935 DIArray SPs = CUNode.getSubprograms();
936 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
937 constructSubprogramDIE(CU, SPs.getElement(i));
938 DIArray EnumTypes = CUNode.getEnumTypes();
939 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
940 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
941 DIArray RetainedTypes = CUNode.getRetainedTypes();
942 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
943 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
944 // Emit imported_modules last so that the relevant context is already
946 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
947 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
950 // Tell MMI that we have debug info.
951 MMI->setDebugInfoAvailability(true);
953 // Prime section data.
954 SectionMap[Asm->getObjFileLowering().getTextSection()];
957 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
958 void DwarfDebug::computeInlinedDIEs() {
959 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
960 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
961 AE = InlinedSubprogramDIEs.end();
964 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
966 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
967 AE = AbstractSPDies.end();
969 DIE *ISP = AI->second;
970 if (InlinedSubprogramDIEs.count(ISP))
972 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
976 // Collect info for variables that were optimized out.
977 void DwarfDebug::collectDeadVariables() {
978 const Module *M = MMI->getModule();
980 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
981 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
982 DICompileUnit TheCU(CU_Nodes->getOperand(i));
983 DIArray Subprograms = TheCU.getSubprograms();
984 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
985 DISubprogram SP(Subprograms.getElement(i));
986 if (ProcessedSPNodes.count(SP) != 0)
988 if (!SP.isSubprogram())
990 if (!SP.isDefinition())
992 DIArray Variables = SP.getVariables();
993 if (Variables.getNumElements() == 0)
996 // Construct subprogram DIE and add variables DIEs.
997 DwarfCompileUnit *SPCU =
998 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
999 assert(SPCU && "Unable to find Compile Unit!");
1000 // FIXME: See the comment in constructSubprogramDIE about duplicate
1002 constructSubprogramDIE(SPCU, SP);
1003 DIE *SPDIE = SPCU->getDIE(SP);
1004 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1005 DIVariable DV(Variables.getElement(vi));
1006 if (!DV.isVariable())
1008 DbgVariable NewVar(DV, NULL, this);
1009 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1010 SPDIE->addChild(VariableDIE);
1017 void DwarfDebug::finalizeModuleInfo() {
1018 // Collect info for variables that were optimized out.
1019 collectDeadVariables();
1021 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1022 computeInlinedDIEs();
1024 // Handle anything that needs to be done on a per-unit basis after
1025 // all other generation.
1026 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1027 E = getUnits().end();
1029 DwarfUnit *TheU = *I;
1030 // Emit DW_AT_containing_type attribute to connect types with their
1031 // vtable holding type.
1032 TheU->constructContainingTypeDIEs();
1034 // Add CU specific attributes if we need to add any.
1035 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1036 // If we're splitting the dwarf out now that we've got the entire
1037 // CU then add the dwo id to it.
1038 DwarfCompileUnit *SkCU =
1039 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1040 if (useSplitDwarf()) {
1041 // This should be a unique identifier when we want to build .dwp files.
1043 if (GenerateCUHash) {
1045 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1047 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1048 dwarf::DW_FORM_data8, ID);
1049 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1050 dwarf::DW_FORM_data8, ID);
1053 // If we have code split among multiple sections or we've requested
1054 // it then emit a DW_AT_ranges attribute on the unit that will remain
1055 // in the .o file, otherwise add a DW_AT_low_pc.
1056 // FIXME: Also add a high pc if we can.
1057 // FIXME: We should use ranges if we have multiple compile units or
1058 // allow reordering of code ala .subsections_via_symbols in mach-o.
1059 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1060 if (useCURanges() && TheU->getRanges().size())
1061 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1062 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1063 DwarfDebugRangeSectionSym);
1065 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1070 // Compute DIE offsets and sizes.
1071 InfoHolder.computeSizeAndOffsets();
1072 if (useSplitDwarf())
1073 SkeletonHolder.computeSizeAndOffsets();
1076 void DwarfDebug::endSections() {
1077 // Filter labels by section.
1078 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1079 const SymbolCU &SCU = ArangeLabels[n];
1080 if (SCU.Sym->isInSection()) {
1081 // Make a note of this symbol and it's section.
1082 const MCSection *Section = &SCU.Sym->getSection();
1083 if (!Section->getKind().isMetadata())
1084 SectionMap[Section].push_back(SCU);
1086 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1087 // appear in the output. This sucks as we rely on sections to build
1088 // arange spans. We can do it without, but it's icky.
1089 SectionMap[NULL].push_back(SCU);
1093 // Build a list of sections used.
1094 std::vector<const MCSection *> Sections;
1095 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1097 const MCSection *Section = it->first;
1098 Sections.push_back(Section);
1101 // Sort the sections into order.
1102 // This is only done to ensure consistent output order across different runs.
1103 std::sort(Sections.begin(), Sections.end(), SectionSort);
1105 // Add terminating symbols for each section.
1106 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1107 const MCSection *Section = Sections[ID];
1108 MCSymbol *Sym = NULL;
1111 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1112 // if we know the section name up-front. For user-created sections, the
1114 // label may not be valid to use as a label. (section names can use a
1116 // set of characters on some systems)
1117 Sym = Asm->GetTempSymbol("debug_end", ID);
1118 Asm->OutStreamer.SwitchSection(Section);
1119 Asm->OutStreamer.EmitLabel(Sym);
1122 // Insert a final terminator.
1123 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1126 // For now only turn on CU ranges if we've explicitly asked for it,
1127 // we have -ffunction-sections enabled, or we've emitted a function
1128 // into a unique section. At this point all sections should be finalized
1129 // except for dwarf sections.
1130 HasCURanges = DwarfCURanges || Asm->TM.debugUseUniqueSections() ||
1131 TargetMachine::getFunctionSections();
1134 // Emit all Dwarf sections that should come after the content.
1135 void DwarfDebug::endModule() {
1142 // End any existing sections.
1143 // TODO: Does this need to happen?
1146 // Finalize the debug info for the module.
1147 finalizeModuleInfo();
1151 // Emit all the DIEs into a debug info section.
1154 // Corresponding abbreviations into a abbrev section.
1155 emitAbbreviations();
1157 // Emit info into a debug loc section.
1160 // Emit info into a debug aranges section.
1163 // Emit info into a debug ranges section.
1166 if (useSplitDwarf()) {
1169 emitDebugAbbrevDWO();
1170 // Emit DWO addresses.
1171 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1174 // Emit info into the dwarf accelerator table sections.
1175 if (useDwarfAccelTables()) {
1178 emitAccelNamespaces();
1182 // Emit the pubnames and pubtypes sections if requested.
1183 if (HasDwarfPubSections) {
1184 emitDebugPubNames(GenerateGnuPubSections);
1185 emitDebugPubTypes(GenerateGnuPubSections);
1191 // Reset these for the next Module if we have one.
1195 // Find abstract variable, if any, associated with Var.
1196 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1197 DebugLoc ScopeLoc) {
1198 LLVMContext &Ctx = DV->getContext();
1199 // More then one inlined variable corresponds to one abstract variable.
1200 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1201 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1203 return AbsDbgVariable;
1205 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1209 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1210 addScopeVariable(Scope, AbsDbgVariable);
1211 AbstractVariables[Var] = AbsDbgVariable;
1212 return AbsDbgVariable;
1215 // If Var is a current function argument then add it to CurrentFnArguments list.
1216 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1217 if (!LScopes.isCurrentFunctionScope(Scope))
1219 DIVariable DV = Var->getVariable();
1220 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1222 unsigned ArgNo = DV.getArgNumber();
1226 size_t Size = CurrentFnArguments.size();
1228 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1229 // llvm::Function argument size is not good indicator of how many
1230 // arguments does the function have at source level.
1232 CurrentFnArguments.resize(ArgNo * 2);
1233 CurrentFnArguments[ArgNo - 1] = Var;
1237 // Collect variable information from side table maintained by MMI.
1238 void DwarfDebug::collectVariableInfoFromMMITable(
1239 SmallPtrSet<const MDNode *, 16> &Processed) {
1240 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1241 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1244 const MDNode *Var = VI->first;
1247 Processed.insert(Var);
1249 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1251 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1253 // If variable scope is not found then skip this variable.
1257 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1258 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1259 RegVar->setFrameIndex(VP.first);
1260 if (!addCurrentFnArgument(RegVar, Scope))
1261 addScopeVariable(Scope, RegVar);
1263 AbsDbgVariable->setFrameIndex(VP.first);
1267 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1269 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1270 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1271 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1272 MI->getOperand(0).getReg() &&
1273 (MI->getOperand(1).isImm() ||
1274 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1277 // Get .debug_loc entry for the instruction range starting at MI.
1278 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1279 const MCSymbol *FLabel,
1280 const MCSymbol *SLabel,
1281 const MachineInstr *MI) {
1282 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1284 assert(MI->getNumOperands() == 3);
1285 if (MI->getOperand(0).isReg()) {
1286 MachineLocation MLoc;
1287 // If the second operand is an immediate, this is a
1288 // register-indirect address.
1289 if (!MI->getOperand(1).isImm())
1290 MLoc.set(MI->getOperand(0).getReg());
1292 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1293 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1295 if (MI->getOperand(0).isImm())
1296 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1297 if (MI->getOperand(0).isFPImm())
1298 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1299 if (MI->getOperand(0).isCImm())
1300 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1302 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1305 // Find variables for each lexical scope.
1307 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1309 // Grab the variable info that was squirreled away in the MMI side-table.
1310 collectVariableInfoFromMMITable(Processed);
1312 for (SmallVectorImpl<const MDNode *>::const_iterator
1313 UVI = UserVariables.begin(),
1314 UVE = UserVariables.end();
1315 UVI != UVE; ++UVI) {
1316 const MDNode *Var = *UVI;
1317 if (Processed.count(Var))
1320 // History contains relevant DBG_VALUE instructions for Var and instructions
1322 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1323 if (History.empty())
1325 const MachineInstr *MInsn = History.front();
1328 LexicalScope *Scope = NULL;
1329 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1330 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1331 Scope = LScopes.getCurrentFunctionScope();
1332 else if (MDNode *IA = DV.getInlinedAt())
1333 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1335 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1336 // If variable scope is not found then skip this variable.
1340 Processed.insert(DV);
1341 assert(MInsn->isDebugValue() && "History must begin with debug value");
1342 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1343 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1344 if (!addCurrentFnArgument(RegVar, Scope))
1345 addScopeVariable(Scope, RegVar);
1347 AbsVar->setMInsn(MInsn);
1349 // Simplify ranges that are fully coalesced.
1350 if (History.size() <= 1 ||
1351 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1352 RegVar->setMInsn(MInsn);
1356 // Handle multiple DBG_VALUE instructions describing one variable.
1357 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1359 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1360 HI = History.begin(),
1363 const MachineInstr *Begin = *HI;
1364 assert(Begin->isDebugValue() && "Invalid History entry");
1366 // Check if DBG_VALUE is truncating a range.
1367 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1368 !Begin->getOperand(0).getReg())
1371 // Compute the range for a register location.
1372 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1373 const MCSymbol *SLabel = 0;
1376 // If Begin is the last instruction in History then its value is valid
1377 // until the end of the function.
1378 SLabel = FunctionEndSym;
1380 const MachineInstr *End = HI[1];
1381 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1382 << "\t" << *Begin << "\t" << *End << "\n");
1383 if (End->isDebugValue())
1384 SLabel = getLabelBeforeInsn(End);
1386 // End is a normal instruction clobbering the range.
1387 SLabel = getLabelAfterInsn(End);
1388 assert(SLabel && "Forgot label after clobber instruction");
1393 // The value is valid until the next DBG_VALUE or clobber.
1394 DotDebugLocEntries.push_back(
1395 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1397 DotDebugLocEntries.push_back(DotDebugLocEntry());
1400 // Collect info for variables that were optimized out.
1401 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1402 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1403 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1404 DIVariable DV(Variables.getElement(i));
1405 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1407 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1408 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1412 // Return Label preceding the instruction.
1413 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1414 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1415 assert(Label && "Didn't insert label before instruction");
1419 // Return Label immediately following the instruction.
1420 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1421 return LabelsAfterInsn.lookup(MI);
1424 // Process beginning of an instruction.
1425 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1428 // Check if source location changes, but ignore DBG_VALUE locations.
1429 if (!MI->isDebugValue()) {
1430 DebugLoc DL = MI->getDebugLoc();
1431 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1434 if (DL == PrologEndLoc) {
1435 Flags |= DWARF2_FLAG_PROLOGUE_END;
1436 PrologEndLoc = DebugLoc();
1438 if (PrologEndLoc.isUnknown())
1439 Flags |= DWARF2_FLAG_IS_STMT;
1441 if (!DL.isUnknown()) {
1442 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1443 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1445 recordSourceLine(0, 0, 0, 0);
1449 // Insert labels where requested.
1450 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1451 LabelsBeforeInsn.find(MI);
1454 if (I == LabelsBeforeInsn.end())
1457 // Label already assigned.
1462 PrevLabel = MMI->getContext().CreateTempSymbol();
1463 Asm->OutStreamer.EmitLabel(PrevLabel);
1465 I->second = PrevLabel;
1468 // Process end of an instruction.
1469 void DwarfDebug::endInstruction() {
1471 // Don't create a new label after DBG_VALUE instructions.
1472 // They don't generate code.
1473 if (!CurMI->isDebugValue())
1476 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1477 LabelsAfterInsn.find(CurMI);
1481 if (I == LabelsAfterInsn.end())
1484 // Label already assigned.
1488 // We need a label after this instruction.
1490 PrevLabel = MMI->getContext().CreateTempSymbol();
1491 Asm->OutStreamer.EmitLabel(PrevLabel);
1493 I->second = PrevLabel;
1496 // Each LexicalScope has first instruction and last instruction to mark
1497 // beginning and end of a scope respectively. Create an inverse map that list
1498 // scopes starts (and ends) with an instruction. One instruction may start (or
1499 // end) multiple scopes. Ignore scopes that are not reachable.
1500 void DwarfDebug::identifyScopeMarkers() {
1501 SmallVector<LexicalScope *, 4> WorkList;
1502 WorkList.push_back(LScopes.getCurrentFunctionScope());
1503 while (!WorkList.empty()) {
1504 LexicalScope *S = WorkList.pop_back_val();
1506 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1507 if (!Children.empty())
1508 for (SmallVectorImpl<LexicalScope *>::const_iterator
1509 SI = Children.begin(),
1510 SE = Children.end();
1512 WorkList.push_back(*SI);
1514 if (S->isAbstractScope())
1517 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1520 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1523 assert(RI->first && "InsnRange does not have first instruction!");
1524 assert(RI->second && "InsnRange does not have second instruction!");
1525 requestLabelBeforeInsn(RI->first);
1526 requestLabelAfterInsn(RI->second);
1531 // Get MDNode for DebugLoc's scope.
1532 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1533 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1534 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1535 return DL.getScope(Ctx);
1538 // Walk up the scope chain of given debug loc and find line number info
1539 // for the function.
1540 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1541 const MDNode *Scope = getScopeNode(DL, Ctx);
1542 DISubprogram SP = getDISubprogram(Scope);
1543 if (SP.isSubprogram()) {
1544 // Check for number of operands since the compatibility is
1546 if (SP->getNumOperands() > 19)
1547 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1549 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1555 // Gather pre-function debug information. Assumes being called immediately
1556 // after the function entry point has been emitted.
1557 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1560 // If there's no debug info for the function we're not going to do anything.
1561 if (!MMI->hasDebugInfo())
1564 // Grab the lexical scopes for the function, if we don't have any of those
1565 // then we're not going to be able to do anything.
1566 LScopes.initialize(*MF);
1567 if (LScopes.empty())
1570 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1572 // Make sure that each lexical scope will have a begin/end label.
1573 identifyScopeMarkers();
1575 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1576 // belongs to so that we add to the correct per-cu line table in the
1578 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1579 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1580 assert(TheCU && "Unable to find compile unit!");
1581 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1582 // Use a single line table if we are using .loc and generating assembly.
1583 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1585 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1587 // Emit a label for the function so that we have a beginning address.
1588 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1589 // Assumes in correct section after the entry point.
1590 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1592 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1593 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1594 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1596 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1598 bool AtBlockEntry = true;
1599 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1601 const MachineInstr *MI = II;
1603 if (MI->isDebugValue()) {
1604 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1606 // Keep track of user variables.
1608 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1610 // Variable is in a register, we need to check for clobbers.
1611 if (isDbgValueInDefinedReg(MI))
1612 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1614 // Check the history of this variable.
1615 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1616 if (History.empty()) {
1617 UserVariables.push_back(Var);
1618 // The first mention of a function argument gets the FunctionBeginSym
1619 // label, so arguments are visible when breaking at function entry.
1621 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1622 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1623 LabelsBeforeInsn[MI] = FunctionBeginSym;
1625 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1626 const MachineInstr *Prev = History.back();
1627 if (Prev->isDebugValue()) {
1628 // Coalesce identical entries at the end of History.
1629 if (History.size() >= 2 &&
1630 Prev->isIdenticalTo(History[History.size() - 2])) {
1631 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1632 << "\t" << *Prev << "\t"
1633 << *History[History.size() - 2] << "\n");
1637 // Terminate old register assignments that don't reach MI;
1638 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1639 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1640 isDbgValueInDefinedReg(Prev)) {
1641 // Previous register assignment needs to terminate at the end of
1643 MachineBasicBlock::const_iterator LastMI =
1644 PrevMBB->getLastNonDebugInstr();
1645 if (LastMI == PrevMBB->end()) {
1646 // Drop DBG_VALUE for empty range.
1647 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1648 << "\t" << *Prev << "\n");
1650 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1651 // Terminate after LastMI.
1652 History.push_back(LastMI);
1656 History.push_back(MI);
1658 // Not a DBG_VALUE instruction.
1660 AtBlockEntry = false;
1662 // First known non-DBG_VALUE and non-frame setup location marks
1663 // the beginning of the function body.
1664 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1665 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1666 PrologEndLoc = MI->getDebugLoc();
1668 // Check if the instruction clobbers any registers with debug vars.
1669 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1670 MOE = MI->operands_end();
1671 MOI != MOE; ++MOI) {
1672 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1674 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1677 const MDNode *Var = LiveUserVar[Reg];
1680 // Reg is now clobbered.
1681 LiveUserVar[Reg] = 0;
1683 // Was MD last defined by a DBG_VALUE referring to Reg?
1684 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1685 if (HistI == DbgValues.end())
1687 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1688 if (History.empty())
1690 const MachineInstr *Prev = History.back();
1691 // Sanity-check: Register assignments are terminated at the end of
1693 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1695 // Is the variable still in Reg?
1696 if (!isDbgValueInDefinedReg(Prev) ||
1697 Prev->getOperand(0).getReg() != Reg)
1699 // Var is clobbered. Make sure the next instruction gets a label.
1700 History.push_back(MI);
1707 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1709 SmallVectorImpl<const MachineInstr *> &History = I->second;
1710 if (History.empty())
1713 // Make sure the final register assignments are terminated.
1714 const MachineInstr *Prev = History.back();
1715 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1716 const MachineBasicBlock *PrevMBB = Prev->getParent();
1717 MachineBasicBlock::const_iterator LastMI =
1718 PrevMBB->getLastNonDebugInstr();
1719 if (LastMI == PrevMBB->end())
1720 // Drop DBG_VALUE for empty range.
1722 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1723 // Terminate after LastMI.
1724 History.push_back(LastMI);
1727 // Request labels for the full history.
1728 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1729 const MachineInstr *MI = History[i];
1730 if (MI->isDebugValue())
1731 requestLabelBeforeInsn(MI);
1733 requestLabelAfterInsn(MI);
1737 PrevInstLoc = DebugLoc();
1738 PrevLabel = FunctionBeginSym;
1740 // Record beginning of function.
1741 if (!PrologEndLoc.isUnknown()) {
1742 DebugLoc FnStartDL =
1743 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1745 FnStartDL.getLine(), FnStartDL.getCol(),
1746 FnStartDL.getScope(MF->getFunction()->getContext()),
1747 // We'd like to list the prologue as "not statements" but GDB behaves
1748 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1749 DWARF2_FLAG_IS_STMT);
1753 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1754 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1755 DIVariable DV = Var->getVariable();
1756 // Variables with positive arg numbers are parameters.
1757 if (unsigned ArgNum = DV.getArgNumber()) {
1758 // Keep all parameters in order at the start of the variable list to ensure
1759 // function types are correct (no out-of-order parameters)
1761 // This could be improved by only doing it for optimized builds (unoptimized
1762 // builds have the right order to begin with), searching from the back (this
1763 // would catch the unoptimized case quickly), or doing a binary search
1764 // rather than linear search.
1765 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1766 while (I != Vars.end()) {
1767 unsigned CurNum = (*I)->getVariable().getArgNumber();
1768 // A local (non-parameter) variable has been found, insert immediately
1772 // A later indexed parameter has been found, insert immediately before it.
1773 if (CurNum > ArgNum)
1777 Vars.insert(I, Var);
1781 Vars.push_back(Var);
1784 // Gather and emit post-function debug information.
1785 void DwarfDebug::endFunction(const MachineFunction *MF) {
1786 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1787 // though the beginFunction may not be called at all.
1788 // We should handle both cases.
1792 assert(CurFn == MF);
1795 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1800 // Define end label for subprogram.
1801 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1802 // Assumes in correct section after the entry point.
1803 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1804 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1805 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1807 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1808 collectVariableInfo(ProcessedVars);
1810 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1811 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1812 assert(TheCU && "Unable to find compile unit!");
1814 // Construct abstract scopes.
1815 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1816 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1817 LexicalScope *AScope = AList[i];
1818 DISubprogram SP(AScope->getScopeNode());
1819 if (SP.isSubprogram()) {
1820 // Collect info for variables that were optimized out.
1821 DIArray Variables = SP.getVariables();
1822 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1823 DIVariable DV(Variables.getElement(i));
1824 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1826 // Check that DbgVariable for DV wasn't created earlier, when
1827 // findAbstractVariable() was called for inlined instance of DV.
1828 LLVMContext &Ctx = DV->getContext();
1829 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1830 if (AbstractVariables.lookup(CleanDV))
1832 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1833 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1836 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1837 constructScopeDIE(TheCU, AScope);
1840 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1842 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1843 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1846 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1847 E = ScopeVariables.end();
1849 DeleteContainerPointers(I->second);
1850 ScopeVariables.clear();
1851 DeleteContainerPointers(CurrentFnArguments);
1852 UserVariables.clear();
1854 AbstractVariables.clear();
1855 LabelsBeforeInsn.clear();
1856 LabelsAfterInsn.clear();
1861 // Register a source line with debug info. Returns the unique label that was
1862 // emitted and which provides correspondence to the source line list.
1863 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1869 DIDescriptor Scope(S);
1871 if (Scope.isCompileUnit()) {
1872 DICompileUnit CU(S);
1873 Fn = CU.getFilename();
1874 Dir = CU.getDirectory();
1875 } else if (Scope.isFile()) {
1877 Fn = F.getFilename();
1878 Dir = F.getDirectory();
1879 } else if (Scope.isSubprogram()) {
1881 Fn = SP.getFilename();
1882 Dir = SP.getDirectory();
1883 } else if (Scope.isLexicalBlockFile()) {
1884 DILexicalBlockFile DBF(S);
1885 Fn = DBF.getFilename();
1886 Dir = DBF.getDirectory();
1887 } else if (Scope.isLexicalBlock()) {
1888 DILexicalBlock DB(S);
1889 Fn = DB.getFilename();
1890 Dir = DB.getDirectory();
1892 llvm_unreachable("Unexpected scope info");
1894 Src = getOrCreateSourceID(
1895 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1897 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1900 //===----------------------------------------------------------------------===//
1902 //===----------------------------------------------------------------------===//
1904 // Compute the size and offset of a DIE. The offset is relative to start of the
1905 // CU. It returns the offset after laying out the DIE.
1906 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1907 // Get the children.
1908 const std::vector<DIE *> &Children = Die->getChildren();
1910 // Record the abbreviation.
1911 assignAbbrevNumber(Die->getAbbrev());
1913 // Get the abbreviation for this DIE.
1914 const DIEAbbrev &Abbrev = Die->getAbbrev();
1917 Die->setOffset(Offset);
1919 // Start the size with the size of abbreviation code.
1920 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1922 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1923 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1925 // Size the DIE attribute values.
1926 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1927 // Size attribute value.
1928 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1930 // Size the DIE children if any.
1931 if (!Children.empty()) {
1932 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1933 "Children flag not set");
1935 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1936 Offset = computeSizeAndOffset(Children[j], Offset);
1938 // End of children marker.
1939 Offset += sizeof(int8_t);
1942 Die->setSize(Offset - Die->getOffset());
1946 // Compute the size and offset for each DIE.
1947 void DwarfFile::computeSizeAndOffsets() {
1948 // Offset from the first CU in the debug info section is 0 initially.
1949 unsigned SecOffset = 0;
1951 // Iterate over each compile unit and set the size and offsets for each
1952 // DIE within each compile unit. All offsets are CU relative.
1953 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1956 (*I)->setDebugInfoOffset(SecOffset);
1958 // CU-relative offset is reset to 0 here.
1959 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1960 (*I)->getHeaderSize(); // Unit-specific headers
1962 // EndOffset here is CU-relative, after laying out
1963 // all of the CU DIE.
1964 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1965 SecOffset += EndOffset;
1969 // Emit initial Dwarf sections with a label at the start of each one.
1970 void DwarfDebug::emitSectionLabels() {
1971 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1973 // Dwarf sections base addresses.
1974 DwarfInfoSectionSym =
1975 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1976 if (useSplitDwarf())
1977 DwarfInfoDWOSectionSym =
1978 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1979 DwarfAbbrevSectionSym =
1980 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1981 if (useSplitDwarf())
1982 DwarfAbbrevDWOSectionSym = emitSectionSym(
1983 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1984 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1986 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1987 emitSectionSym(Asm, MacroInfo);
1989 DwarfLineSectionSym =
1990 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1991 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1992 if (GenerateGnuPubSections) {
1993 DwarfGnuPubNamesSectionSym =
1994 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1995 DwarfGnuPubTypesSectionSym =
1996 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1997 } else if (HasDwarfPubSections) {
1998 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1999 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2002 DwarfStrSectionSym =
2003 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2004 if (useSplitDwarf()) {
2005 DwarfStrDWOSectionSym =
2006 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2007 DwarfAddrSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2010 DwarfDebugRangeSectionSym =
2011 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2013 DwarfDebugLocSectionSym =
2014 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2017 // Recursively emits a debug information entry.
2018 void DwarfDebug::emitDIE(DIE *Die) {
2019 // Get the abbreviation for this DIE.
2020 const DIEAbbrev &Abbrev = Die->getAbbrev();
2022 // Emit the code (index) for the abbreviation.
2023 if (Asm->isVerbose())
2024 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2025 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2026 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2027 dwarf::TagString(Abbrev.getTag()));
2028 Asm->EmitULEB128(Abbrev.getNumber());
2030 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2031 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2033 // Emit the DIE attribute values.
2034 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2035 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2036 dwarf::Form Form = AbbrevData[i].getForm();
2037 assert(Form && "Too many attributes for DIE (check abbreviation)");
2039 if (Asm->isVerbose())
2040 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2043 case dwarf::DW_AT_abstract_origin:
2044 case dwarf::DW_AT_type:
2045 case dwarf::DW_AT_friend:
2046 case dwarf::DW_AT_specification:
2047 case dwarf::DW_AT_import:
2048 case dwarf::DW_AT_containing_type: {
2049 DIEEntry *E = cast<DIEEntry>(Values[i]);
2050 DIE *Origin = E->getEntry();
2051 unsigned Addr = Origin->getOffset();
2052 if (Form == dwarf::DW_FORM_ref_addr) {
2053 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2054 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2055 // section. Origin->getOffset() returns the offset from start of the
2057 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2058 assert(CU && "CUDie should belong to a CU.");
2059 Addr += CU->getDebugInfoOffset();
2060 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2061 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2062 DIEEntry::getRefAddrSize(Asm));
2064 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2065 CU->getSectionSym(),
2066 DIEEntry::getRefAddrSize(Asm));
2068 // Make sure Origin belong to the same CU.
2069 assert(Die->getUnit() == Origin->getUnit() &&
2070 "The referenced DIE should belong to the same CU in ref4");
2071 Asm->EmitInt32(Addr);
2075 case dwarf::DW_AT_location: {
2076 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2077 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2078 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2080 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2082 Values[i]->EmitValue(Asm, Form);
2086 case dwarf::DW_AT_accessibility: {
2087 if (Asm->isVerbose()) {
2088 DIEInteger *V = cast<DIEInteger>(Values[i]);
2089 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2091 Values[i]->EmitValue(Asm, Form);
2095 // Emit an attribute using the defined form.
2096 Values[i]->EmitValue(Asm, Form);
2101 // Emit the DIE children if any.
2102 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2103 const std::vector<DIE *> &Children = Die->getChildren();
2105 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2106 emitDIE(Children[j]);
2108 Asm->OutStreamer.AddComment("End Of Children Mark");
2113 // Emit the various dwarf units to the unit section USection with
2114 // the abbreviations going into ASection.
2115 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2116 const MCSymbol *ASectionSym) {
2117 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2119 DwarfUnit *TheU = *I;
2120 DIE *Die = TheU->getUnitDie();
2121 const MCSection *USection = TheU->getSection();
2122 Asm->OutStreamer.SwitchSection(USection);
2124 // Emit the compile units header.
2125 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2127 // Emit size of content not including length itself
2128 Asm->OutStreamer.AddComment("Length of Unit");
2129 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2131 TheU->emitHeader(ASection, ASectionSym);
2134 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2138 // Emit the debug info section.
2139 void DwarfDebug::emitDebugInfo() {
2140 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2142 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2143 DwarfAbbrevSectionSym);
2146 // Emit the abbreviation section.
2147 void DwarfDebug::emitAbbreviations() {
2148 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2150 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2153 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2154 // Check to see if it is worth the effort.
2155 if (!Abbreviations.empty()) {
2156 // Start the debug abbrev section.
2157 Asm->OutStreamer.SwitchSection(Section);
2159 // For each abbrevation.
2160 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2161 // Get abbreviation data
2162 const DIEAbbrev *Abbrev = Abbreviations[i];
2164 // Emit the abbrevations code (base 1 index.)
2165 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2167 // Emit the abbreviations data.
2171 // Mark end of abbreviations.
2172 Asm->EmitULEB128(0, "EOM(3)");
2176 // Emit the last address of the section and the end of the line matrix.
2177 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2178 // Define last address of section.
2179 Asm->OutStreamer.AddComment("Extended Op");
2182 Asm->OutStreamer.AddComment("Op size");
2183 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2184 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2185 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2187 Asm->OutStreamer.AddComment("Section end label");
2189 Asm->OutStreamer.EmitSymbolValue(
2190 Asm->GetTempSymbol("section_end", SectionEnd),
2191 Asm->getDataLayout().getPointerSize());
2193 // Mark end of matrix.
2194 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2200 // Emit visible names into a hashed accelerator table section.
2201 void DwarfDebug::emitAccelNames() {
2203 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2204 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2205 E = getUnits().end();
2207 DwarfUnit *TheU = *I;
2208 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2209 for (StringMap<std::vector<const DIE *> >::const_iterator
2213 StringRef Name = GI->getKey();
2214 const std::vector<const DIE *> &Entities = GI->second;
2215 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2216 DE = Entities.end();
2218 AT.AddName(Name, *DI);
2222 AT.FinalizeTable(Asm, "Names");
2223 Asm->OutStreamer.SwitchSection(
2224 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2225 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2226 Asm->OutStreamer.EmitLabel(SectionBegin);
2228 // Emit the full data.
2229 AT.Emit(Asm, SectionBegin, &InfoHolder);
2232 // Emit objective C classes and categories into a hashed accelerator table
2234 void DwarfDebug::emitAccelObjC() {
2236 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2237 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2238 E = getUnits().end();
2240 DwarfUnit *TheU = *I;
2241 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2242 for (StringMap<std::vector<const DIE *> >::const_iterator
2246 StringRef Name = GI->getKey();
2247 const std::vector<const DIE *> &Entities = GI->second;
2248 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2249 DE = Entities.end();
2251 AT.AddName(Name, *DI);
2255 AT.FinalizeTable(Asm, "ObjC");
2256 Asm->OutStreamer.SwitchSection(
2257 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2258 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2259 Asm->OutStreamer.EmitLabel(SectionBegin);
2261 // Emit the full data.
2262 AT.Emit(Asm, SectionBegin, &InfoHolder);
2265 // Emit namespace dies into a hashed accelerator table.
2266 void DwarfDebug::emitAccelNamespaces() {
2268 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2269 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2270 E = getUnits().end();
2272 DwarfUnit *TheU = *I;
2273 const StringMap<std::vector<const DIE *> > &Names =
2274 TheU->getAccelNamespace();
2275 for (StringMap<std::vector<const DIE *> >::const_iterator
2279 StringRef Name = GI->getKey();
2280 const std::vector<const DIE *> &Entities = GI->second;
2281 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2282 DE = Entities.end();
2284 AT.AddName(Name, *DI);
2288 AT.FinalizeTable(Asm, "namespac");
2289 Asm->OutStreamer.SwitchSection(
2290 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2291 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2292 Asm->OutStreamer.EmitLabel(SectionBegin);
2294 // Emit the full data.
2295 AT.Emit(Asm, SectionBegin, &InfoHolder);
2298 // Emit type dies into a hashed accelerator table.
2299 void DwarfDebug::emitAccelTypes() {
2300 std::vector<DwarfAccelTable::Atom> Atoms;
2302 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2304 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2306 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2307 DwarfAccelTable AT(Atoms);
2308 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2309 E = getUnits().end();
2311 DwarfUnit *TheU = *I;
2312 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2313 TheU->getAccelTypes();
2315 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2319 StringRef Name = GI->getKey();
2320 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2322 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2323 DI = Entities.begin(),
2324 DE = Entities.end();
2326 AT.AddName(Name, DI->first, DI->second);
2330 AT.FinalizeTable(Asm, "types");
2331 Asm->OutStreamer.SwitchSection(
2332 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2333 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2334 Asm->OutStreamer.EmitLabel(SectionBegin);
2336 // Emit the full data.
2337 AT.Emit(Asm, SectionBegin, &InfoHolder);
2340 // Public name handling.
2341 // The format for the various pubnames:
2343 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2344 // for the DIE that is named.
2346 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2347 // into the CU and the index value is computed according to the type of value
2348 // for the DIE that is named.
2350 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2351 // it's the offset within the debug_info/debug_types dwo section, however, the
2352 // reference in the pubname header doesn't change.
2354 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2355 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2357 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2359 // We could have a specification DIE that has our most of our knowledge,
2360 // look for that now.
2361 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2363 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2364 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2365 Linkage = dwarf::GIEL_EXTERNAL;
2366 } else if (Die->findAttribute(dwarf::DW_AT_external))
2367 Linkage = dwarf::GIEL_EXTERNAL;
2369 switch (Die->getTag()) {
2370 case dwarf::DW_TAG_class_type:
2371 case dwarf::DW_TAG_structure_type:
2372 case dwarf::DW_TAG_union_type:
2373 case dwarf::DW_TAG_enumeration_type:
2374 return dwarf::PubIndexEntryDescriptor(
2375 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2376 ? dwarf::GIEL_STATIC
2377 : dwarf::GIEL_EXTERNAL);
2378 case dwarf::DW_TAG_typedef:
2379 case dwarf::DW_TAG_base_type:
2380 case dwarf::DW_TAG_subrange_type:
2381 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2382 case dwarf::DW_TAG_namespace:
2383 return dwarf::GIEK_TYPE;
2384 case dwarf::DW_TAG_subprogram:
2385 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2386 case dwarf::DW_TAG_constant:
2387 case dwarf::DW_TAG_variable:
2388 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2389 case dwarf::DW_TAG_enumerator:
2390 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2391 dwarf::GIEL_STATIC);
2393 return dwarf::GIEK_NONE;
2397 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2399 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2400 const MCSection *PSec =
2401 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2402 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2404 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2405 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2406 for (unsigned i = 0; i != Units.size(); ++i) {
2407 DwarfUnit *TheU = Units[i];
2408 unsigned ID = TheU->getUniqueID();
2410 // Start the dwarf pubnames section.
2411 Asm->OutStreamer.SwitchSection(PSec);
2413 // Emit a label so we can reference the beginning of this pubname section.
2415 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2418 Asm->OutStreamer.AddComment("Length of Public Names Info");
2419 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2420 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2421 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2423 Asm->OutStreamer.EmitLabel(BeginLabel);
2425 Asm->OutStreamer.AddComment("DWARF Version");
2426 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2428 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2429 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2431 Asm->OutStreamer.AddComment("Compilation Unit Length");
2432 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2434 // Emit the pubnames for this compilation unit.
2435 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2436 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2439 const char *Name = GI->getKeyData();
2440 const DIE *Entity = GI->second;
2442 Asm->OutStreamer.AddComment("DIE offset");
2443 Asm->EmitInt32(Entity->getOffset());
2446 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2447 Asm->OutStreamer.AddComment(
2448 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2449 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2450 Asm->EmitInt8(Desc.toBits());
2453 Asm->OutStreamer.AddComment("External Name");
2454 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2457 Asm->OutStreamer.AddComment("End Mark");
2459 Asm->OutStreamer.EmitLabel(EndLabel);
2463 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2464 const MCSection *PSec =
2465 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2466 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2468 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2469 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2470 for (unsigned i = 0; i != Units.size(); ++i) {
2471 DwarfUnit *TheU = Units[i];
2472 unsigned ID = TheU->getUniqueID();
2474 // Start the dwarf pubtypes section.
2475 Asm->OutStreamer.SwitchSection(PSec);
2477 // Emit a label so we can reference the beginning of this pubtype section.
2479 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2482 Asm->OutStreamer.AddComment("Length of Public Types Info");
2483 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2484 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2485 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2487 Asm->OutStreamer.EmitLabel(BeginLabel);
2489 Asm->OutStreamer.AddComment("DWARF Version");
2490 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2492 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2493 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2495 Asm->OutStreamer.AddComment("Compilation Unit Length");
2496 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2498 // Emit the pubtypes.
2499 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2500 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2503 const char *Name = GI->getKeyData();
2504 const DIE *Entity = GI->second;
2506 Asm->OutStreamer.AddComment("DIE offset");
2507 Asm->EmitInt32(Entity->getOffset());
2510 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2511 Asm->OutStreamer.AddComment(
2512 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2513 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2514 Asm->EmitInt8(Desc.toBits());
2517 Asm->OutStreamer.AddComment("External Name");
2519 // Emit the name with a terminating null byte.
2520 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2523 Asm->OutStreamer.AddComment("End Mark");
2525 Asm->OutStreamer.EmitLabel(EndLabel);
2529 // Emit strings into a string section.
2530 void DwarfFile::emitStrings(const MCSection *StrSection,
2531 const MCSection *OffsetSection = NULL,
2532 const MCSymbol *StrSecSym = NULL) {
2534 if (StringPool.empty())
2537 // Start the dwarf str section.
2538 Asm->OutStreamer.SwitchSection(StrSection);
2540 // Get all of the string pool entries and put them in an array by their ID so
2541 // we can sort them.
2543 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2546 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2547 I = StringPool.begin(),
2548 E = StringPool.end();
2550 Entries.push_back(std::make_pair(I->second.second, &*I));
2552 array_pod_sort(Entries.begin(), Entries.end());
2554 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2555 // Emit a label for reference from debug information entries.
2556 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2558 // Emit the string itself with a terminating null byte.
2559 Asm->OutStreamer.EmitBytes(
2560 StringRef(Entries[i].second->getKeyData(),
2561 Entries[i].second->getKeyLength() + 1));
2564 // If we've got an offset section go ahead and emit that now as well.
2565 if (OffsetSection) {
2566 Asm->OutStreamer.SwitchSection(OffsetSection);
2567 unsigned offset = 0;
2568 unsigned size = 4; // FIXME: DWARF64 is 8.
2569 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2570 Asm->OutStreamer.EmitIntValue(offset, size);
2571 offset += Entries[i].second->getKeyLength() + 1;
2576 // Emit addresses into the section given.
2577 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2579 if (AddressPool.empty())
2582 // Start the dwarf addr section.
2583 Asm->OutStreamer.SwitchSection(AddrSection);
2585 // Order the address pool entries by ID
2586 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2588 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2589 E = AddressPool.end();
2591 Entries[I->second] = I->first;
2593 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2594 // Emit an expression for reference from debug information entries.
2595 if (const MCExpr *Expr = Entries[i])
2596 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2598 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2602 // Emit visible names into a debug str section.
2603 void DwarfDebug::emitDebugStr() {
2604 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2605 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2608 // Emit locations into the debug loc section.
2609 void DwarfDebug::emitDebugLoc() {
2610 if (DotDebugLocEntries.empty())
2613 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2614 I = DotDebugLocEntries.begin(),
2615 E = DotDebugLocEntries.end();
2617 DotDebugLocEntry &Entry = *I;
2618 if (I + 1 != DotDebugLocEntries.end())
2622 // Start the dwarf loc section.
2623 Asm->OutStreamer.SwitchSection(
2624 Asm->getObjFileLowering().getDwarfLocSection());
2625 unsigned char Size = Asm->getDataLayout().getPointerSize();
2626 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2628 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2629 I = DotDebugLocEntries.begin(),
2630 E = DotDebugLocEntries.end();
2631 I != E; ++I, ++index) {
2632 DotDebugLocEntry &Entry = *I;
2633 if (Entry.isMerged())
2635 if (Entry.isEmpty()) {
2636 Asm->OutStreamer.EmitIntValue(0, Size);
2637 Asm->OutStreamer.EmitIntValue(0, Size);
2638 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2640 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2641 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2642 DIVariable DV(Entry.getVariable());
2643 Asm->OutStreamer.AddComment("Loc expr size");
2644 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2645 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2646 Asm->EmitLabelDifference(end, begin, 2);
2647 Asm->OutStreamer.EmitLabel(begin);
2648 if (Entry.isInt()) {
2649 DIBasicType BTy(DV.getType());
2650 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2651 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2652 Asm->OutStreamer.AddComment("DW_OP_consts");
2653 Asm->EmitInt8(dwarf::DW_OP_consts);
2654 Asm->EmitSLEB128(Entry.getInt());
2656 Asm->OutStreamer.AddComment("DW_OP_constu");
2657 Asm->EmitInt8(dwarf::DW_OP_constu);
2658 Asm->EmitULEB128(Entry.getInt());
2660 } else if (Entry.isLocation()) {
2661 MachineLocation Loc = Entry.getLoc();
2662 if (!DV.hasComplexAddress())
2664 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2666 // Complex address entry.
2667 unsigned N = DV.getNumAddrElements();
2669 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2670 if (Loc.getOffset()) {
2672 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2673 Asm->OutStreamer.AddComment("DW_OP_deref");
2674 Asm->EmitInt8(dwarf::DW_OP_deref);
2675 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2676 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2677 Asm->EmitSLEB128(DV.getAddrElement(1));
2679 // If first address element is OpPlus then emit
2680 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2681 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2682 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2686 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2689 // Emit remaining complex address elements.
2690 for (; i < N; ++i) {
2691 uint64_t Element = DV.getAddrElement(i);
2692 if (Element == DIBuilder::OpPlus) {
2693 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2694 Asm->EmitULEB128(DV.getAddrElement(++i));
2695 } else if (Element == DIBuilder::OpDeref) {
2697 Asm->EmitInt8(dwarf::DW_OP_deref);
2699 llvm_unreachable("unknown Opcode found in complex address");
2703 // else ... ignore constant fp. There is not any good way to
2704 // to represent them here in dwarf.
2705 Asm->OutStreamer.EmitLabel(end);
2710 struct SymbolCUSorter {
2711 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2712 const MCStreamer &Streamer;
2714 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2715 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2716 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2718 // Symbols with no order assigned should be placed at the end.
2719 // (e.g. section end labels)
2721 IA = (unsigned)(-1);
2723 IB = (unsigned)(-1);
2728 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2729 return (A->getUniqueID() < B->getUniqueID());
2733 const MCSymbol *Start, *End;
2736 // Emit a debug aranges section, containing a CU lookup for any
2737 // address we can tie back to a CU.
2738 void DwarfDebug::emitDebugARanges() {
2739 // Start the dwarf aranges section.
2740 Asm->OutStreamer.SwitchSection(
2741 Asm->getObjFileLowering().getDwarfARangesSection());
2743 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2747 // Build a list of sections used.
2748 std::vector<const MCSection *> Sections;
2749 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2751 const MCSection *Section = it->first;
2752 Sections.push_back(Section);
2755 // Sort the sections into order.
2756 // This is only done to ensure consistent output order across different runs.
2757 std::sort(Sections.begin(), Sections.end(), SectionSort);
2759 // Build a set of address spans, sorted by CU.
2760 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2761 const MCSection *Section = Sections[SecIdx];
2762 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2763 if (List.size() < 2)
2766 // Sort the symbols by offset within the section.
2767 SymbolCUSorter sorter(Asm->OutStreamer);
2768 std::sort(List.begin(), List.end(), sorter);
2770 // If we have no section (e.g. common), just write out
2771 // individual spans for each symbol.
2772 if (Section == NULL) {
2773 for (size_t n = 0; n < List.size(); n++) {
2774 const SymbolCU &Cur = List[n];
2777 Span.Start = Cur.Sym;
2780 Spans[Cur.CU].push_back(Span);
2783 // Build spans between each label.
2784 const MCSymbol *StartSym = List[0].Sym;
2785 for (size_t n = 1; n < List.size(); n++) {
2786 const SymbolCU &Prev = List[n - 1];
2787 const SymbolCU &Cur = List[n];
2789 // Try and build the longest span we can within the same CU.
2790 if (Cur.CU != Prev.CU) {
2792 Span.Start = StartSym;
2794 Spans[Prev.CU].push_back(Span);
2801 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2803 // Build a list of CUs used.
2804 std::vector<DwarfCompileUnit *> CUs;
2805 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2806 DwarfCompileUnit *CU = it->first;
2810 // Sort the CU list (again, to ensure consistent output order).
2811 std::sort(CUs.begin(), CUs.end(), CUSort);
2813 // Emit an arange table for each CU we used.
2814 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2815 DwarfCompileUnit *CU = CUs[CUIdx];
2816 std::vector<ArangeSpan> &List = Spans[CU];
2818 // Emit size of content not including length itself.
2819 unsigned ContentSize =
2820 sizeof(int16_t) + // DWARF ARange version number
2821 sizeof(int32_t) + // Offset of CU in the .debug_info section
2822 sizeof(int8_t) + // Pointer Size (in bytes)
2823 sizeof(int8_t); // Segment Size (in bytes)
2825 unsigned TupleSize = PtrSize * 2;
2827 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2829 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2831 ContentSize += Padding;
2832 ContentSize += (List.size() + 1) * TupleSize;
2834 // For each compile unit, write the list of spans it covers.
2835 Asm->OutStreamer.AddComment("Length of ARange Set");
2836 Asm->EmitInt32(ContentSize);
2837 Asm->OutStreamer.AddComment("DWARF Arange version number");
2838 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2839 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2840 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2841 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2842 Asm->EmitInt8(PtrSize);
2843 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2846 Asm->OutStreamer.EmitFill(Padding, 0xff);
2848 for (unsigned n = 0; n < List.size(); n++) {
2849 const ArangeSpan &Span = List[n];
2850 Asm->EmitLabelReference(Span.Start, PtrSize);
2852 // Calculate the size as being from the span start to it's end.
2854 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2856 // For symbols without an end marker (e.g. common), we
2857 // write a single arange entry containing just that one symbol.
2858 uint64_t Size = SymSize[Span.Start];
2862 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2866 Asm->OutStreamer.AddComment("ARange terminator");
2867 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2868 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2872 // Emit visible names into a debug ranges section.
2873 void DwarfDebug::emitDebugRanges() {
2874 // Start the dwarf ranges section.
2875 Asm->OutStreamer.SwitchSection(
2876 Asm->getObjFileLowering().getDwarfRangesSection());
2878 // Size for our labels.
2879 unsigned char Size = Asm->getDataLayout().getPointerSize();
2881 // Grab the specific ranges for the compile units in the module.
2882 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2885 DwarfCompileUnit *TheCU = I->second;
2887 // Emit a symbol so we can find the beginning of our ranges.
2888 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2890 // Iterate over the misc ranges for the compile units in the module.
2891 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2892 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2893 E = RangeLists.end();
2895 const RangeSpanList &List = *I;
2897 // Emit our symbol so we can find the beginning of the range.
2898 Asm->OutStreamer.EmitLabel(List.getSym());
2900 for (SmallVectorImpl<RangeSpan>::const_iterator
2901 RI = List.getRanges().begin(),
2902 RE = List.getRanges().end();
2904 const RangeSpan &Range = *RI;
2905 const MCSymbol *Begin = Range.getStart();
2906 const MCSymbol *End = Range.getEnd();
2907 assert(Begin && "Range without a begin symbol?");
2908 assert(End && "Range without an end symbol?");
2909 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2910 Asm->OutStreamer.EmitSymbolValue(End, Size);
2913 // And terminate the list with two 0 values.
2914 Asm->OutStreamer.EmitIntValue(0, Size);
2915 Asm->OutStreamer.EmitIntValue(0, Size);
2918 // Now emit a range for the CU itself.
2919 if (useCURanges()) {
2920 Asm->OutStreamer.EmitLabel(
2921 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2922 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2923 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2924 RangeSpan Range = Ranges[i];
2925 const MCSymbol *Begin = Range.getStart();
2926 const MCSymbol *End = Range.getEnd();
2927 assert(Begin && "Range without a begin symbol?");
2928 assert(End && "Range without an end symbol?");
2929 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2930 Asm->OutStreamer.EmitSymbolValue(End, Size);
2932 // And terminate the list with two 0 values.
2933 Asm->OutStreamer.EmitIntValue(0, Size);
2934 Asm->OutStreamer.EmitIntValue(0, Size);
2939 // DWARF5 Experimental Separate Dwarf emitters.
2941 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2943 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2944 U->getCUNode().getSplitDebugFilename());
2946 // Relocate to the beginning of the addr_base section, else 0 for the
2947 // beginning of the one for this compile unit.
2948 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2949 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2951 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2953 if (!CompilationDir.empty())
2954 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2956 addGnuPubAttributes(NewU, Die);
2958 SkeletonHolder.addUnit(NewU);
2961 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2962 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2963 // DW_AT_ranges_base, DW_AT_addr_base.
2964 // TODO: Implement DW_AT_ranges_base.
2965 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2967 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2968 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2969 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2970 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2971 DwarfInfoSectionSym);
2973 // DW_AT_stmt_list is a offset of line number information for this
2974 // compile unit in debug_line section.
2975 // FIXME: Should handle multiple compile units.
2976 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2977 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2979 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2981 initSkeletonUnit(CU, Die, NewCU);
2986 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2988 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
2990 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2991 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2992 TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
2993 NewTU->setTypeSignature(TU->getTypeSignature());
2994 NewTU->setType(NULL);
2996 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2998 initSkeletonUnit(TU, Die, NewTU);
3002 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3003 // compile units that would normally be in debug_info.
3004 void DwarfDebug::emitDebugInfoDWO() {
3005 assert(useSplitDwarf() && "No split dwarf debug info?");
3006 InfoHolder.emitUnits(this,
3007 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3008 DwarfAbbrevDWOSectionSym);
3011 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3012 // abbreviations for the .debug_info.dwo section.
3013 void DwarfDebug::emitDebugAbbrevDWO() {
3014 assert(useSplitDwarf() && "No split dwarf?");
3015 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3018 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3019 // string section and is identical in format to traditional .debug_str
3021 void DwarfDebug::emitDebugStrDWO() {
3022 assert(useSplitDwarf() && "No split dwarf?");
3023 const MCSection *OffSec =
3024 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3025 const MCSymbol *StrSym = DwarfStrSectionSym;
3026 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3030 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3031 StringRef Identifier, DIE *RefDie,
3032 DICompositeType CTy) {
3034 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3036 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3040 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3041 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3042 InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3044 InfoHolder.addUnit(NewTU);
3046 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3047 CUNode.getLanguage());
3050 Hash.update(Identifier);
3051 // ... take the least significant 8 bytes and return those. Our MD5
3052 // implementation always returns its results in little endian, swap bytes
3054 MD5::MD5Result Result;
3056 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3057 NewTU->setTypeSignature(Signature);
3058 if (useSplitDwarf())
3059 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3061 NewTU->setType(NewTU->createTypeDIE(CTy));
3065 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3066 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3068 CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);