1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
66 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
67 cl::desc("Add the CU hash as the dwo_id."),
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72 cl::desc("Generate GNU-style pubnames and pubtypes"),
83 static cl::opt<DefaultOnOff>
84 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
85 cl::desc("Output prototype dwarf accelerator tables."),
86 cl::values(clEnumVal(Default, "Default for platform"),
87 clEnumVal(Enable, "Enabled"),
88 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 static cl::opt<DefaultOnOff>
92 SplitDwarf("split-dwarf", cl::Hidden,
93 cl::desc("Output prototype dwarf split debug info."),
94 cl::values(clEnumVal(Default, "Default for platform"),
95 clEnumVal(Enable, "Enabled"),
96 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 static cl::opt<DefaultOnOff>
100 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
101 cl::desc("Generate DWARF pubnames and pubtypes sections"),
102 cl::values(clEnumVal(Default, "Default for platform"),
103 clEnumVal(Enable, "Enabled"),
104 clEnumVal(Disable, "Disabled"), clEnumValEnd),
107 static cl::opt<unsigned>
108 DwarfVersionNumber("dwarf-version", cl::Hidden,
109 cl::desc("Generate DWARF for dwarf version."),
112 static const char *const DWARFGroupName = "DWARF Emission";
113 static const char *const DbgTimerName = "DWARF Debug Writer";
115 //===----------------------------------------------------------------------===//
117 // Configuration values for initial hash set sizes (log2).
119 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
123 /// resolve - Look in the DwarfDebug map for the MDNode that
124 /// corresponds to the reference.
125 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
126 return DD->resolve(Ref);
129 DIType DbgVariable::getType() const {
130 DIType Ty = Var.getType();
131 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
132 // addresses instead.
133 if (Var.isBlockByrefVariable()) {
134 /* Byref variables, in Blocks, are declared by the programmer as
135 "SomeType VarName;", but the compiler creates a
136 __Block_byref_x_VarName struct, and gives the variable VarName
137 either the struct, or a pointer to the struct, as its type. This
138 is necessary for various behind-the-scenes things the compiler
139 needs to do with by-reference variables in blocks.
141 However, as far as the original *programmer* is concerned, the
142 variable should still have type 'SomeType', as originally declared.
144 The following function dives into the __Block_byref_x_VarName
145 struct to find the original type of the variable. This will be
146 passed back to the code generating the type for the Debug
147 Information Entry for the variable 'VarName'. 'VarName' will then
148 have the original type 'SomeType' in its debug information.
150 The original type 'SomeType' will be the type of the field named
151 'VarName' inside the __Block_byref_x_VarName struct.
153 NOTE: In order for this to not completely fail on the debugger
154 side, the Debug Information Entry for the variable VarName needs to
155 have a DW_AT_location that tells the debugger how to unwind through
156 the pointers and __Block_byref_x_VarName struct to find the actual
157 value of the variable. The function addBlockByrefType does this. */
159 uint16_t tag = Ty.getTag();
161 if (tag == dwarf::DW_TAG_pointer_type)
162 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
164 DIArray Elements = DICompositeType(subType).getTypeArray();
165 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
166 DIDerivedType DT(Elements.getElement(i));
167 if (getName() == DT.getName())
168 return (resolve(DT.getTypeDerivedFrom()));
174 } // end llvm namespace
176 /// Return Dwarf Version by checking module flags.
177 static unsigned getDwarfVersionFromModule(const Module *M) {
178 Value *Val = M->getModuleFlag("Dwarf Version");
180 return dwarf::DWARF_VERSION;
181 return cast<ConstantInt>(Val)->getZExtValue();
184 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
185 : Asm(A), MMI(Asm->MMI), FirstCU(0),
186 AbbreviationsSet(InitAbbreviationsSetSize),
187 SourceIdMap(DIEValueAllocator), PrevLabel(NULL), GlobalCUIndexCount(0),
188 GlobalRangeCount(0), InfoHolder(A, &AbbreviationsSet, Abbreviations,
189 "info_string", DIEValueAllocator),
190 SkeletonAbbrevSet(InitAbbreviationsSetSize),
191 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
194 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
195 DwarfStrSectionSym = TextSectionSym = 0;
196 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
197 DwarfAddrSectionSym = 0;
198 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
199 FunctionBeginSym = FunctionEndSym = 0;
201 // Turn on accelerator tables for Darwin by default, pubnames by
202 // default for non-Darwin, and handle split dwarf.
203 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
205 if (DwarfAccelTables == Default)
206 HasDwarfAccelTables = IsDarwin;
208 HasDwarfAccelTables = DwarfAccelTables == Enable;
210 if (SplitDwarf == Default)
211 HasSplitDwarf = false;
213 HasSplitDwarf = SplitDwarf == Enable;
215 if (DwarfPubSections == Default)
216 HasDwarfPubSections = !IsDarwin;
218 HasDwarfPubSections = DwarfPubSections == Enable;
220 DwarfVersion = DwarfVersionNumber
222 : getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
230 // Switch to the specified MCSection and emit an assembler
231 // temporary label to it if SymbolStem is specified.
232 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
233 const char *SymbolStem = 0) {
234 Asm->OutStreamer.SwitchSection(Section);
238 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
239 Asm->OutStreamer.EmitLabel(TmpSym);
243 DwarfUnits::~DwarfUnits() {
244 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
249 MCSymbol *DwarfUnits::getStringPoolSym() {
250 return Asm->GetTempSymbol(StringPref);
253 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
254 std::pair<MCSymbol *, unsigned> &Entry =
255 StringPool.GetOrCreateValue(Str).getValue();
259 Entry.second = NextStringPoolNumber++;
260 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
263 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
264 std::pair<MCSymbol *, unsigned> &Entry =
265 StringPool.GetOrCreateValue(Str).getValue();
269 Entry.second = NextStringPoolNumber++;
270 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
274 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
275 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
278 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
279 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
280 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
282 ++NextAddrPoolNumber;
283 return P.first->second;
286 // Define a unique number for the abbreviation.
288 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
289 // Check the set for priors.
290 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
292 // If it's newly added.
293 if (InSet == &Abbrev) {
294 // Add to abbreviation list.
295 Abbreviations.push_back(&Abbrev);
297 // Assign the vector position + 1 as its number.
298 Abbrev.setNumber(Abbreviations.size());
300 // Assign existing abbreviation number.
301 Abbrev.setNumber(InSet->getNumber());
305 static bool isObjCClass(StringRef Name) {
306 return Name.startswith("+") || Name.startswith("-");
309 static bool hasObjCCategory(StringRef Name) {
310 if (!isObjCClass(Name))
313 return Name.find(") ") != StringRef::npos;
316 static void getObjCClassCategory(StringRef In, StringRef &Class,
317 StringRef &Category) {
318 if (!hasObjCCategory(In)) {
319 Class = In.slice(In.find('[') + 1, In.find(' '));
324 Class = In.slice(In.find('[') + 1, In.find('('));
325 Category = In.slice(In.find('[') + 1, In.find(' '));
329 static StringRef getObjCMethodName(StringRef In) {
330 return In.slice(In.find(' ') + 1, In.find(']'));
333 // Helper for sorting sections into a stable output order.
334 static bool SectionSort(const MCSection *A, const MCSection *B) {
335 std::string LA = (A ? A->getLabelBeginName() : "");
336 std::string LB = (B ? B->getLabelBeginName() : "");
340 // Add the various names to the Dwarf accelerator table names.
341 // TODO: Determine whether or not we should add names for programs
342 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
343 // is only slightly different than the lookup of non-standard ObjC names.
344 static void addSubprogramNames(Unit *TheU, DISubprogram SP, DIE *Die) {
345 if (!SP.isDefinition())
347 TheU->addAccelName(SP.getName(), Die);
349 // If the linkage name is different than the name, go ahead and output
350 // that as well into the name table.
351 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
352 TheU->addAccelName(SP.getLinkageName(), Die);
354 // If this is an Objective-C selector name add it to the ObjC accelerator
356 if (isObjCClass(SP.getName())) {
357 StringRef Class, Category;
358 getObjCClassCategory(SP.getName(), Class, Category);
359 TheU->addAccelObjC(Class, Die);
361 TheU->addAccelObjC(Category, Die);
362 // Also add the base method name to the name table.
363 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
367 /// isSubprogramContext - Return true if Context is either a subprogram
368 /// or another context nested inside a subprogram.
369 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
372 DIDescriptor D(Context);
373 if (D.isSubprogram())
376 return isSubprogramContext(resolve(DIType(Context).getContext()));
380 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
381 // and DW_AT_high_pc attributes. If there are global variables in this
382 // scope then create and insert DIEs for these variables.
383 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
384 DIE *SPDie = SPCU->getDIE(SP);
386 assert(SPDie && "Unable to find subprogram DIE!");
388 // If we're updating an abstract DIE, then we will be adding the children and
389 // object pointer later on. But what we don't want to do is process the
390 // concrete DIE twice.
391 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
392 // Pick up abstract subprogram DIE.
394 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
395 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
397 DISubprogram SPDecl = SP.getFunctionDeclaration();
398 if (!SPDecl.isSubprogram()) {
399 // There is not any need to generate specification DIE for a function
400 // defined at compile unit level. If a function is defined inside another
401 // function then gdb prefers the definition at top level and but does not
402 // expect specification DIE in parent function. So avoid creating
403 // specification DIE for a function defined inside a function.
404 DIScope SPContext = resolve(SP.getContext());
405 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
406 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
407 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
410 DICompositeType SPTy = SP.getType();
411 DIArray Args = SPTy.getTypeArray();
412 uint16_t SPTag = SPTy.getTag();
413 if (SPTag == dwarf::DW_TAG_subroutine_type)
414 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
416 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
417 DIType ATy(Args.getElement(i));
418 SPCU->addType(Arg, ATy);
419 if (ATy.isArtificial())
420 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
421 if (ATy.isObjectPointer())
422 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
424 DIE *SPDeclDie = SPDie;
425 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
426 *SPCU->getUnitDie());
427 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
432 MCSymbol *FuncBegin =
433 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
434 MCSymbol *FuncEnd = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
435 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FuncBegin);
436 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FuncEnd);
438 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
439 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
440 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
442 // Add name to the name table, we do this here because we're guaranteed
443 // to have concrete versions of our DW_TAG_subprogram nodes.
444 addSubprogramNames(SPCU, SP, SPDie);
449 /// Check whether we should create a DIE for the given Scope, return true
450 /// if we don't create a DIE (the corresponding DIE is null).
451 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
452 if (Scope->isAbstractScope())
455 // We don't create a DIE if there is no Range.
456 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
460 if (Ranges.size() > 1)
463 // We don't create a DIE if we have a single Range and the end label
465 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
466 MCSymbol *End = getLabelAfterInsn(RI->second);
470 // Construct new DW_TAG_lexical_block for this scope and attach
471 // DW_AT_low_pc/DW_AT_high_pc labels.
472 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
473 LexicalScope *Scope) {
474 if (isLexicalScopeDIENull(Scope))
477 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
478 if (Scope->isAbstractScope())
481 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
482 // If we have multiple ranges, emit them into the range section.
483 if (ScopeRanges.size() > 1) {
484 // .debug_range section has not been laid out yet. Emit offset in
485 // .debug_range as a relocatable label. emitDIE will handle
486 // emitting it appropriately.
487 TheCU->addSectionLabel(
488 ScopeDIE, dwarf::DW_AT_ranges,
489 Asm->GetTempSymbol("debug_ranges", GlobalRangeCount));
490 RangeSpanList *List = new RangeSpanList(GlobalRangeCount++);
491 for (SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin(),
492 RE = ScopeRanges.end();
494 RangeSpan Range(getLabelBeforeInsn(RI->first),
495 getLabelAfterInsn(RI->second));
496 List->addRange(Range);
499 // Add the range list to the set of ranges to be emitted.
500 TheCU->addRangeList(List);
504 // Construct the address range for this DIE.
505 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
506 MCSymbol *Start = getLabelBeforeInsn(RI->first);
507 MCSymbol *End = getLabelAfterInsn(RI->second);
508 assert(End && "End label should not be null!");
510 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
511 assert(End->isDefined() && "Invalid end label for an inlined scope!");
513 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
514 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
519 // This scope represents inlined body of a function. Construct DIE to
520 // represent this concrete inlined copy of the function.
521 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
522 LexicalScope *Scope) {
523 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
524 assert(ScopeRanges.empty() == false &&
525 "LexicalScope does not have instruction markers!");
527 if (!Scope->getScopeNode())
529 DIScope DS(Scope->getScopeNode());
530 DISubprogram InlinedSP = getDISubprogram(DS);
531 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
533 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
537 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
538 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
540 if (ScopeRanges.size() > 1) {
541 // .debug_range section has not been laid out yet. Emit offset in
542 // .debug_range as a relocatable label. emitDIE will handle
543 // emitting it appropriately.
544 TheCU->addSectionLabel(
545 ScopeDIE, dwarf::DW_AT_ranges,
546 Asm->GetTempSymbol("debug_ranges", GlobalRangeCount));
547 RangeSpanList *List = new RangeSpanList(GlobalRangeCount++);
548 for (SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin(),
549 RE = ScopeRanges.end();
551 RangeSpan Range(getLabelBeforeInsn(RI->first),
552 getLabelAfterInsn(RI->second));
553 List->addRange(Range);
556 // Add the range list to the set of ranges to be emitted.
557 TheCU->addRangeList(List);
559 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
560 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
561 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
563 if (StartLabel == 0 || EndLabel == 0)
564 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
566 assert(StartLabel->isDefined() &&
567 "Invalid starting label for an inlined scope!");
568 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
570 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
571 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
574 InlinedSubprogramDIEs.insert(OriginDIE);
576 // Add the call site information to the DIE.
577 DILocation DL(Scope->getInlinedAt());
578 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
579 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
580 TheCU->getUniqueID()));
581 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
583 // Add name to the name table, we do this here because we're guaranteed
584 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
585 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
590 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
591 SmallVectorImpl<DIE *> &Children) {
592 DIE *ObjectPointer = NULL;
594 // Collect arguments for current function.
595 if (LScopes.isCurrentFunctionScope(Scope))
596 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
597 if (DbgVariable *ArgDV = CurrentFnArguments[i])
599 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
600 Children.push_back(Arg);
601 if (ArgDV->isObjectPointer())
605 // Collect lexical scope children first.
606 const SmallVectorImpl<DbgVariable *> &Variables =
607 ScopeVariables.lookup(Scope);
608 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
609 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
610 Scope->isAbstractScope())) {
611 Children.push_back(Variable);
612 if (Variables[i]->isObjectPointer())
613 ObjectPointer = Variable;
615 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
616 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
617 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
618 Children.push_back(Nested);
619 return ObjectPointer;
622 // Construct a DIE for this scope.
623 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
624 if (!Scope || !Scope->getScopeNode())
627 DIScope DS(Scope->getScopeNode());
629 SmallVector<DIE *, 8> Children;
630 DIE *ObjectPointer = NULL;
631 bool ChildrenCreated = false;
633 // We try to create the scope DIE first, then the children DIEs. This will
634 // avoid creating un-used children then removing them later when we find out
635 // the scope DIE is null.
636 DIE *ScopeDIE = NULL;
637 if (Scope->getInlinedAt())
638 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
639 else if (DS.isSubprogram()) {
640 ProcessedSPNodes.insert(DS);
641 if (Scope->isAbstractScope()) {
642 ScopeDIE = TheCU->getDIE(DS);
643 // Note down abstract DIE.
645 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
647 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
649 // Early exit when we know the scope DIE is going to be null.
650 if (isLexicalScopeDIENull(Scope))
653 // We create children here when we know the scope DIE is not going to be
654 // null and the children will be added to the scope DIE.
655 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
656 ChildrenCreated = true;
658 // There is no need to emit empty lexical block DIE.
659 std::pair<ImportedEntityMap::const_iterator,
660 ImportedEntityMap::const_iterator> Range =
662 ScopesWithImportedEntities.begin(),
663 ScopesWithImportedEntities.end(),
664 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
666 if (Children.empty() && Range.first == Range.second)
668 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
669 assert(ScopeDIE && "Scope DIE should not be null.");
670 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
672 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
676 assert(Children.empty() &&
677 "We create children only when the scope DIE is not null.");
680 if (!ChildrenCreated)
681 // We create children when the scope DIE is not null.
682 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
685 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
688 ScopeDIE->addChild(*I);
690 if (DS.isSubprogram() && ObjectPointer != NULL)
691 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
696 // Look up the source id with the given directory and source file names.
697 // If none currently exists, create a new id and insert it in the
698 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
700 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
702 // If we use .loc in assembly, we can't separate .file entries according to
703 // compile units. Thus all files will belong to the default compile unit.
705 // FIXME: add a better feature test than hasRawTextSupport. Even better,
706 // extend .file to support this.
707 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
710 // If FE did not provide a file name, then assume stdin.
711 if (FileName.empty())
712 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
714 // TODO: this might not belong here. See if we can factor this better.
715 if (DirName == CompilationDir)
718 // FileIDCUMap stores the current ID for the given compile unit.
719 unsigned SrcId = FileIDCUMap[CUID] + 1;
721 // We look up the CUID/file/dir by concatenating them with a zero byte.
722 SmallString<128> NamePair;
723 NamePair += utostr(CUID);
726 NamePair += '\0'; // Zero bytes are not allowed in paths.
727 NamePair += FileName;
729 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
730 if (Ent.getValue() != SrcId)
731 return Ent.getValue();
733 FileIDCUMap[CUID] = SrcId;
734 // Print out a .file directive to specify files for .loc directives.
735 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
740 // Create new CompileUnit for the given metadata node with tag
741 // DW_TAG_compile_unit.
742 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
743 StringRef FN = DIUnit.getFilename();
744 CompilationDir = DIUnit.getDirectory();
746 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
747 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
750 FileIDCUMap[NewCU->getUniqueID()] = 0;
751 // Call this to emit a .file directive if it wasn't emitted for the source
752 // file this CU comes from yet.
753 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
755 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
756 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
757 DIUnit.getLanguage());
758 NewCU->addString(Die, dwarf::DW_AT_name, FN);
760 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
761 // into an entity. We're using 0 (or a NULL label) for this. For
762 // split dwarf it's in the skeleton CU so omit it here.
763 if (!useSplitDwarf())
764 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
766 // Define start line table label for each Compile Unit.
767 MCSymbol *LineTableStartSym =
768 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
769 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
770 NewCU->getUniqueID());
772 // Use a single line table if we are using .loc and generating assembly.
774 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
775 (NewCU->getUniqueID() == 0);
777 if (!useSplitDwarf()) {
778 // DW_AT_stmt_list is a offset of line number information for this
779 // compile unit in debug_line section. For split dwarf this is
780 // left in the skeleton CU and so not included.
781 // The line table entries are not always emitted in assembly, so it
782 // is not okay to use line_table_start here.
783 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
784 NewCU->addSectionLabel(
785 Die, dwarf::DW_AT_stmt_list,
786 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
787 : LineTableStartSym);
788 else if (UseTheFirstCU)
789 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
791 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
792 LineTableStartSym, DwarfLineSectionSym);
794 // If we're using split dwarf the compilation dir is going to be in the
795 // skeleton CU and so we don't need to duplicate it here.
796 if (!CompilationDir.empty())
797 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
799 // Flags to let the linker know we have emitted new style pubnames. Only
800 // emit it here if we don't have a skeleton CU for split dwarf.
801 if (GenerateGnuPubSections) {
802 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
803 NewCU->addSectionLabel(
804 Die, dwarf::DW_AT_GNU_pubnames,
805 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
807 NewCU->addSectionDelta(
808 Die, dwarf::DW_AT_GNU_pubnames,
809 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
810 DwarfGnuPubNamesSectionSym);
812 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
813 NewCU->addSectionLabel(
814 Die, dwarf::DW_AT_GNU_pubtypes,
815 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
817 NewCU->addSectionDelta(
818 Die, dwarf::DW_AT_GNU_pubtypes,
819 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
820 DwarfGnuPubTypesSectionSym);
824 if (DIUnit.isOptimized())
825 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
827 StringRef Flags = DIUnit.getFlags();
829 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
831 if (unsigned RVer = DIUnit.getRunTimeVersion())
832 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
833 dwarf::DW_FORM_data1, RVer);
838 InfoHolder.addUnit(NewCU);
840 CUMap.insert(std::make_pair(DIUnit, NewCU));
841 CUDieMap.insert(std::make_pair(Die, NewCU));
845 // Construct subprogram DIE.
846 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
847 // FIXME: We should only call this routine once, however, during LTO if a
848 // program is defined in multiple CUs we could end up calling it out of
849 // beginModule as we walk the CUs.
851 CompileUnit *&CURef = SPMap[N];
857 if (!SP.isDefinition())
858 // This is a method declaration which will be handled while constructing
862 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
864 // Expose as a global name.
865 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
868 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
870 DIImportedEntity Module(N);
871 if (!Module.Verify())
873 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
874 constructImportedEntityDIE(TheCU, Module, D);
877 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
879 DIImportedEntity Module(N);
880 if (!Module.Verify())
882 return constructImportedEntityDIE(TheCU, Module, Context);
885 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
886 const DIImportedEntity &Module,
888 assert(Module.Verify() &&
889 "Use one of the MDNode * overloads to handle invalid metadata");
890 assert(Context && "Should always have a context for an imported_module");
891 DIE *IMDie = new DIE(Module.getTag());
892 TheCU->insertDIE(Module, IMDie);
894 DIDescriptor Entity = Module.getEntity();
895 if (Entity.isNameSpace())
896 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
897 else if (Entity.isSubprogram())
898 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
899 else if (Entity.isType())
900 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
902 EntityDie = TheCU->getDIE(Entity);
903 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
904 Module.getContext().getDirectory(),
905 TheCU->getUniqueID());
906 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
907 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
908 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
909 StringRef Name = Module.getName();
911 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
912 Context->addChild(IMDie);
915 // Emit all Dwarf sections that should come prior to the content. Create
916 // global DIEs and emit initial debug info sections. This is invoked by
917 // the target AsmPrinter.
918 void DwarfDebug::beginModule() {
919 if (DisableDebugInfoPrinting)
922 const Module *M = MMI->getModule();
924 // If module has named metadata anchors then use them, otherwise scan the
925 // module using debug info finder to collect debug info.
926 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
929 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
931 // Emit initial sections so we can reference labels later.
934 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
935 DICompileUnit CUNode(CU_Nodes->getOperand(i));
936 CompileUnit *CU = constructCompileUnit(CUNode);
937 DIArray ImportedEntities = CUNode.getImportedEntities();
938 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
939 ScopesWithImportedEntities.push_back(std::make_pair(
940 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
941 ImportedEntities.getElement(i)));
942 std::sort(ScopesWithImportedEntities.begin(),
943 ScopesWithImportedEntities.end(), less_first());
944 DIArray GVs = CUNode.getGlobalVariables();
945 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
946 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
947 DIArray SPs = CUNode.getSubprograms();
948 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
949 constructSubprogramDIE(CU, SPs.getElement(i));
950 DIArray EnumTypes = CUNode.getEnumTypes();
951 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
952 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
953 DIArray RetainedTypes = CUNode.getRetainedTypes();
954 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
955 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
956 // Emit imported_modules last so that the relevant context is already
958 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
959 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
962 // Tell MMI that we have debug info.
963 MMI->setDebugInfoAvailability(true);
965 // Prime section data.
966 SectionMap[Asm->getObjFileLowering().getTextSection()];
969 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
970 void DwarfDebug::computeInlinedDIEs() {
971 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
972 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
973 AE = InlinedSubprogramDIEs.end();
976 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
978 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
979 AE = AbstractSPDies.end();
981 DIE *ISP = AI->second;
982 if (InlinedSubprogramDIEs.count(ISP))
984 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
988 // Collect info for variables that were optimized out.
989 void DwarfDebug::collectDeadVariables() {
990 const Module *M = MMI->getModule();
992 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
993 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
994 DICompileUnit TheCU(CU_Nodes->getOperand(i));
995 DIArray Subprograms = TheCU.getSubprograms();
996 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
997 DISubprogram SP(Subprograms.getElement(i));
998 if (ProcessedSPNodes.count(SP) != 0)
1000 if (!SP.isSubprogram())
1002 if (!SP.isDefinition())
1004 DIArray Variables = SP.getVariables();
1005 if (Variables.getNumElements() == 0)
1008 // Construct subprogram DIE and add variables DIEs.
1009 CompileUnit *SPCU = static_cast<CompileUnit *>(CUMap.lookup(TheCU));
1010 assert(SPCU && "Unable to find Compile Unit!");
1011 // FIXME: See the comment in constructSubprogramDIE about duplicate
1013 constructSubprogramDIE(SPCU, SP);
1014 DIE *SPDIE = SPCU->getDIE(SP);
1015 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1016 DIVariable DV(Variables.getElement(vi));
1017 if (!DV.isVariable())
1019 DbgVariable NewVar(DV, NULL, this);
1020 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1021 SPDIE->addChild(VariableDIE);
1028 // Type Signature [7.27] and ODR Hash code.
1030 /// \brief Grabs the string in whichever attribute is passed in and returns
1031 /// a reference to it. Returns "" if the attribute doesn't exist.
1032 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1033 DIEValue *V = Die->findAttribute(Attr);
1035 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1036 return S->getString();
1038 return StringRef("");
1041 /// Return true if the current DIE is contained within an anonymous namespace.
1042 static bool isContainedInAnonNamespace(DIE *Die) {
1043 DIE *Parent = Die->getParent();
1046 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1047 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1049 Parent = Parent->getParent();
1055 /// Test if the current CU language is C++ and that we have
1056 /// a named type that is not contained in an anonymous namespace.
1057 static bool shouldAddODRHash(TypeUnit *CU, DIE *Die) {
1058 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1059 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1060 !isContainedInAnonNamespace(Die);
1063 void DwarfDebug::finalizeModuleInfo() {
1064 // Collect info for variables that were optimized out.
1065 collectDeadVariables();
1067 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1068 computeInlinedDIEs();
1070 // Handle anything that needs to be done on a per-cu basis.
1071 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
1072 E = getUnits().end();
1075 // Emit DW_AT_containing_type attribute to connect types with their
1076 // vtable holding type.
1077 TheU->constructContainingTypeDIEs();
1079 // If we're splitting the dwarf out now that we've got the entire
1080 // CU then construct a skeleton CU based upon it.
1081 if (useSplitDwarf() &&
1082 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1084 if (GenerateCUHash) {
1086 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1088 // This should be a unique identifier when we want to build .dwp files.
1089 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1090 dwarf::DW_FORM_data8, ID);
1091 // Now construct the skeleton CU associated.
1092 CompileUnit *SkCU = constructSkeletonCU(static_cast<CompileUnit *>(TheU));
1093 // This should be a unique identifier when we want to build .dwp files.
1094 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1095 dwarf::DW_FORM_data8, ID);
1099 // Compute DIE offsets and sizes.
1100 InfoHolder.computeSizeAndOffsets();
1101 if (useSplitDwarf())
1102 SkeletonHolder.computeSizeAndOffsets();
1105 void DwarfDebug::endSections() {
1106 // Filter labels by section.
1107 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1108 const SymbolCU &SCU = ArangeLabels[n];
1109 if (SCU.Sym->isInSection()) {
1110 // Make a note of this symbol and it's section.
1111 const MCSection *Section = &SCU.Sym->getSection();
1112 if (!Section->getKind().isMetadata())
1113 SectionMap[Section].push_back(SCU);
1115 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1116 // appear in the output. This sucks as we rely on sections to build
1117 // arange spans. We can do it without, but it's icky.
1118 SectionMap[NULL].push_back(SCU);
1122 // Build a list of sections used.
1123 std::vector<const MCSection *> Sections;
1124 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1126 const MCSection *Section = it->first;
1127 Sections.push_back(Section);
1130 // Sort the sections into order.
1131 // This is only done to ensure consistent output order across different runs.
1132 std::sort(Sections.begin(), Sections.end(), SectionSort);
1134 // Add terminating symbols for each section.
1135 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1136 const MCSection *Section = Sections[ID];
1137 MCSymbol *Sym = NULL;
1140 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1141 // if we know the section name up-front. For user-created sections, the
1143 // label may not be valid to use as a label. (section names can use a
1145 // set of characters on some systems)
1146 Sym = Asm->GetTempSymbol("debug_end", ID);
1147 Asm->OutStreamer.SwitchSection(Section);
1148 Asm->OutStreamer.EmitLabel(Sym);
1151 // Insert a final terminator.
1152 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1156 // Emit all Dwarf sections that should come after the content.
1157 void DwarfDebug::endModule() {
1162 // End any existing sections.
1163 // TODO: Does this need to happen?
1166 // Finalize the debug info for the module.
1167 finalizeModuleInfo();
1171 // Emit all the DIEs into a debug info section.
1174 // Corresponding abbreviations into a abbrev section.
1175 emitAbbreviations();
1177 // Emit info into a debug loc section.
1180 // Emit info into a debug aranges section.
1183 // Emit info into a debug ranges section.
1186 // Emit info into a debug macinfo section.
1189 if (useSplitDwarf()) {
1192 emitDebugAbbrevDWO();
1193 // Emit DWO addresses.
1194 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1197 // Emit info into the dwarf accelerator table sections.
1198 if (useDwarfAccelTables()) {
1201 emitAccelNamespaces();
1205 // Emit the pubnames and pubtypes sections if requested.
1206 if (HasDwarfPubSections) {
1207 emitDebugPubNames(GenerateGnuPubSections);
1208 emitDebugPubTypes(GenerateGnuPubSections);
1214 // Reset these for the next Module if we have one.
1218 // Find abstract variable, if any, associated with Var.
1219 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1220 DebugLoc ScopeLoc) {
1221 LLVMContext &Ctx = DV->getContext();
1222 // More then one inlined variable corresponds to one abstract variable.
1223 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1224 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1226 return AbsDbgVariable;
1228 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1232 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1233 addScopeVariable(Scope, AbsDbgVariable);
1234 AbstractVariables[Var] = AbsDbgVariable;
1235 return AbsDbgVariable;
1238 // If Var is a current function argument then add it to CurrentFnArguments list.
1239 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1240 DbgVariable *Var, LexicalScope *Scope) {
1241 if (!LScopes.isCurrentFunctionScope(Scope))
1243 DIVariable DV = Var->getVariable();
1244 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1246 unsigned ArgNo = DV.getArgNumber();
1250 size_t Size = CurrentFnArguments.size();
1252 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1253 // llvm::Function argument size is not good indicator of how many
1254 // arguments does the function have at source level.
1256 CurrentFnArguments.resize(ArgNo * 2);
1257 CurrentFnArguments[ArgNo - 1] = Var;
1261 // Collect variable information from side table maintained by MMI.
1262 void DwarfDebug::collectVariableInfoFromMMITable(
1263 const MachineFunction *MF, SmallPtrSet<const MDNode *, 16> &Processed) {
1264 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1265 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1268 const MDNode *Var = VI->first;
1271 Processed.insert(Var);
1273 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1275 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1277 // If variable scope is not found then skip this variable.
1281 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1282 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1283 RegVar->setFrameIndex(VP.first);
1284 if (!addCurrentFnArgument(MF, RegVar, Scope))
1285 addScopeVariable(Scope, RegVar);
1287 AbsDbgVariable->setFrameIndex(VP.first);
1291 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1293 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1294 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1295 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1296 MI->getOperand(0).getReg() &&
1297 (MI->getOperand(1).isImm() ||
1298 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1301 // Get .debug_loc entry for the instruction range starting at MI.
1302 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1303 const MCSymbol *FLabel,
1304 const MCSymbol *SLabel,
1305 const MachineInstr *MI) {
1306 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1308 assert(MI->getNumOperands() == 3);
1309 if (MI->getOperand(0).isReg()) {
1310 MachineLocation MLoc;
1311 // If the second operand is an immediate, this is a
1312 // register-indirect address.
1313 if (!MI->getOperand(1).isImm())
1314 MLoc.set(MI->getOperand(0).getReg());
1316 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1317 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1319 if (MI->getOperand(0).isImm())
1320 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1321 if (MI->getOperand(0).isFPImm())
1322 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1323 if (MI->getOperand(0).isCImm())
1324 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1326 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1329 // Find variables for each lexical scope.
1331 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1332 SmallPtrSet<const MDNode *, 16> &Processed) {
1334 // Grab the variable info that was squirreled away in the MMI side-table.
1335 collectVariableInfoFromMMITable(MF, Processed);
1337 for (SmallVectorImpl<const MDNode *>::const_iterator
1338 UVI = UserVariables.begin(),
1339 UVE = UserVariables.end();
1340 UVI != UVE; ++UVI) {
1341 const MDNode *Var = *UVI;
1342 if (Processed.count(Var))
1345 // History contains relevant DBG_VALUE instructions for Var and instructions
1347 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1348 if (History.empty())
1350 const MachineInstr *MInsn = History.front();
1353 LexicalScope *Scope = NULL;
1354 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1355 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1356 Scope = LScopes.getCurrentFunctionScope();
1357 else if (MDNode *IA = DV.getInlinedAt())
1358 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1360 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1361 // If variable scope is not found then skip this variable.
1365 Processed.insert(DV);
1366 assert(MInsn->isDebugValue() && "History must begin with debug value");
1367 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1368 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1369 if (!addCurrentFnArgument(MF, RegVar, Scope))
1370 addScopeVariable(Scope, RegVar);
1372 AbsVar->setMInsn(MInsn);
1374 // Simplify ranges that are fully coalesced.
1375 if (History.size() <= 1 ||
1376 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1377 RegVar->setMInsn(MInsn);
1381 // Handle multiple DBG_VALUE instructions describing one variable.
1382 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1384 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1385 HI = History.begin(),
1388 const MachineInstr *Begin = *HI;
1389 assert(Begin->isDebugValue() && "Invalid History entry");
1391 // Check if DBG_VALUE is truncating a range.
1392 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1393 !Begin->getOperand(0).getReg())
1396 // Compute the range for a register location.
1397 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1398 const MCSymbol *SLabel = 0;
1401 // If Begin is the last instruction in History then its value is valid
1402 // until the end of the function.
1403 SLabel = FunctionEndSym;
1405 const MachineInstr *End = HI[1];
1406 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1407 << "\t" << *Begin << "\t" << *End << "\n");
1408 if (End->isDebugValue())
1409 SLabel = getLabelBeforeInsn(End);
1411 // End is a normal instruction clobbering the range.
1412 SLabel = getLabelAfterInsn(End);
1413 assert(SLabel && "Forgot label after clobber instruction");
1418 // The value is valid until the next DBG_VALUE or clobber.
1419 DotDebugLocEntries.push_back(
1420 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1422 DotDebugLocEntries.push_back(DotDebugLocEntry());
1425 // Collect info for variables that were optimized out.
1426 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1427 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1428 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1429 DIVariable DV(Variables.getElement(i));
1430 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1432 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1433 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1437 // Return Label preceding the instruction.
1438 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1439 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1440 assert(Label && "Didn't insert label before instruction");
1444 // Return Label immediately following the instruction.
1445 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1446 return LabelsAfterInsn.lookup(MI);
1449 // Process beginning of an instruction.
1450 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1451 // Check if source location changes, but ignore DBG_VALUE locations.
1452 if (!MI->isDebugValue()) {
1453 DebugLoc DL = MI->getDebugLoc();
1454 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1457 if (DL == PrologEndLoc) {
1458 Flags |= DWARF2_FLAG_PROLOGUE_END;
1459 PrologEndLoc = DebugLoc();
1461 if (PrologEndLoc.isUnknown())
1462 Flags |= DWARF2_FLAG_IS_STMT;
1464 if (!DL.isUnknown()) {
1465 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1466 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1468 recordSourceLine(0, 0, 0, 0);
1472 // Insert labels where requested.
1473 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1474 LabelsBeforeInsn.find(MI);
1477 if (I == LabelsBeforeInsn.end())
1480 // Label already assigned.
1485 PrevLabel = MMI->getContext().CreateTempSymbol();
1486 Asm->OutStreamer.EmitLabel(PrevLabel);
1488 I->second = PrevLabel;
1491 // Process end of an instruction.
1492 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1493 // Don't create a new label after DBG_VALUE instructions.
1494 // They don't generate code.
1495 if (!MI->isDebugValue())
1498 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1499 LabelsAfterInsn.find(MI);
1502 if (I == LabelsAfterInsn.end())
1505 // Label already assigned.
1509 // We need a label after this instruction.
1511 PrevLabel = MMI->getContext().CreateTempSymbol();
1512 Asm->OutStreamer.EmitLabel(PrevLabel);
1514 I->second = PrevLabel;
1517 // Each LexicalScope has first instruction and last instruction to mark
1518 // beginning and end of a scope respectively. Create an inverse map that list
1519 // scopes starts (and ends) with an instruction. One instruction may start (or
1520 // end) multiple scopes. Ignore scopes that are not reachable.
1521 void DwarfDebug::identifyScopeMarkers() {
1522 SmallVector<LexicalScope *, 4> WorkList;
1523 WorkList.push_back(LScopes.getCurrentFunctionScope());
1524 while (!WorkList.empty()) {
1525 LexicalScope *S = WorkList.pop_back_val();
1527 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1528 if (!Children.empty())
1529 for (SmallVectorImpl<LexicalScope *>::const_iterator
1530 SI = Children.begin(),
1531 SE = Children.end();
1533 WorkList.push_back(*SI);
1535 if (S->isAbstractScope())
1538 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1541 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1544 assert(RI->first && "InsnRange does not have first instruction!");
1545 assert(RI->second && "InsnRange does not have second instruction!");
1546 requestLabelBeforeInsn(RI->first);
1547 requestLabelAfterInsn(RI->second);
1552 // Get MDNode for DebugLoc's scope.
1553 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1554 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1555 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1556 return DL.getScope(Ctx);
1559 // Walk up the scope chain of given debug loc and find line number info
1560 // for the function.
1561 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1562 const MDNode *Scope = getScopeNode(DL, Ctx);
1563 DISubprogram SP = getDISubprogram(Scope);
1564 if (SP.isSubprogram()) {
1565 // Check for number of operands since the compatibility is
1567 if (SP->getNumOperands() > 19)
1568 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1570 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1576 // Gather pre-function debug information. Assumes being called immediately
1577 // after the function entry point has been emitted.
1578 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1580 // If there's no debug info for the function we're not going to do anything.
1581 if (!MMI->hasDebugInfo())
1584 // Grab the lexical scopes for the function, if we don't have any of those
1585 // then we're not going to be able to do anything.
1586 LScopes.initialize(*MF);
1587 if (LScopes.empty())
1590 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1592 // Make sure that each lexical scope will have a begin/end label.
1593 identifyScopeMarkers();
1595 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1596 // belongs to so that we add to the correct per-cu line table in the
1598 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1599 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1600 assert(TheCU && "Unable to find compile unit!");
1601 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1602 // Use a single line table if we are using .loc and generating assembly.
1603 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1605 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1607 // Emit a label for the function so that we have a beginning address.
1608 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1609 // Assumes in correct section after the entry point.
1610 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1612 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1613 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1614 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1616 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1618 bool AtBlockEntry = true;
1619 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1621 const MachineInstr *MI = II;
1623 if (MI->isDebugValue()) {
1624 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1626 // Keep track of user variables.
1628 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1630 // Variable is in a register, we need to check for clobbers.
1631 if (isDbgValueInDefinedReg(MI))
1632 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1634 // Check the history of this variable.
1635 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1636 if (History.empty()) {
1637 UserVariables.push_back(Var);
1638 // The first mention of a function argument gets the FunctionBeginSym
1639 // label, so arguments are visible when breaking at function entry.
1641 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1642 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1643 LabelsBeforeInsn[MI] = FunctionBeginSym;
1645 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1646 const MachineInstr *Prev = History.back();
1647 if (Prev->isDebugValue()) {
1648 // Coalesce identical entries at the end of History.
1649 if (History.size() >= 2 &&
1650 Prev->isIdenticalTo(History[History.size() - 2])) {
1651 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1652 << "\t" << *Prev << "\t"
1653 << *History[History.size() - 2] << "\n");
1657 // Terminate old register assignments that don't reach MI;
1658 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1659 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1660 isDbgValueInDefinedReg(Prev)) {
1661 // Previous register assignment needs to terminate at the end of
1663 MachineBasicBlock::const_iterator LastMI =
1664 PrevMBB->getLastNonDebugInstr();
1665 if (LastMI == PrevMBB->end()) {
1666 // Drop DBG_VALUE for empty range.
1667 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1668 << "\t" << *Prev << "\n");
1670 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1671 // Terminate after LastMI.
1672 History.push_back(LastMI);
1676 History.push_back(MI);
1678 // Not a DBG_VALUE instruction.
1680 AtBlockEntry = false;
1682 // First known non-DBG_VALUE and non-frame setup location marks
1683 // the beginning of the function body.
1684 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1685 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1686 PrologEndLoc = MI->getDebugLoc();
1688 // Check if the instruction clobbers any registers with debug vars.
1689 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1690 MOE = MI->operands_end();
1691 MOI != MOE; ++MOI) {
1692 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1694 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1697 const MDNode *Var = LiveUserVar[Reg];
1700 // Reg is now clobbered.
1701 LiveUserVar[Reg] = 0;
1703 // Was MD last defined by a DBG_VALUE referring to Reg?
1704 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1705 if (HistI == DbgValues.end())
1707 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1708 if (History.empty())
1710 const MachineInstr *Prev = History.back();
1711 // Sanity-check: Register assignments are terminated at the end of
1713 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1715 // Is the variable still in Reg?
1716 if (!isDbgValueInDefinedReg(Prev) ||
1717 Prev->getOperand(0).getReg() != Reg)
1719 // Var is clobbered. Make sure the next instruction gets a label.
1720 History.push_back(MI);
1727 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1729 SmallVectorImpl<const MachineInstr *> &History = I->second;
1730 if (History.empty())
1733 // Make sure the final register assignments are terminated.
1734 const MachineInstr *Prev = History.back();
1735 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1736 const MachineBasicBlock *PrevMBB = Prev->getParent();
1737 MachineBasicBlock::const_iterator LastMI =
1738 PrevMBB->getLastNonDebugInstr();
1739 if (LastMI == PrevMBB->end())
1740 // Drop DBG_VALUE for empty range.
1742 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1743 // Terminate after LastMI.
1744 History.push_back(LastMI);
1747 // Request labels for the full history.
1748 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1749 const MachineInstr *MI = History[i];
1750 if (MI->isDebugValue())
1751 requestLabelBeforeInsn(MI);
1753 requestLabelAfterInsn(MI);
1757 PrevInstLoc = DebugLoc();
1758 PrevLabel = FunctionBeginSym;
1760 // Record beginning of function.
1761 if (!PrologEndLoc.isUnknown()) {
1762 DebugLoc FnStartDL =
1763 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1765 FnStartDL.getLine(), FnStartDL.getCol(),
1766 FnStartDL.getScope(MF->getFunction()->getContext()),
1767 // We'd like to list the prologue as "not statements" but GDB behaves
1768 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1769 DWARF2_FLAG_IS_STMT);
1773 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1774 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1775 DIVariable DV = Var->getVariable();
1776 // Variables with positive arg numbers are parameters.
1777 if (unsigned ArgNum = DV.getArgNumber()) {
1778 // Keep all parameters in order at the start of the variable list to ensure
1779 // function types are correct (no out-of-order parameters)
1781 // This could be improved by only doing it for optimized builds (unoptimized
1782 // builds have the right order to begin with), searching from the back (this
1783 // would catch the unoptimized case quickly), or doing a binary search
1784 // rather than linear search.
1785 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1786 while (I != Vars.end()) {
1787 unsigned CurNum = (*I)->getVariable().getArgNumber();
1788 // A local (non-parameter) variable has been found, insert immediately
1792 // A later indexed parameter has been found, insert immediately before it.
1793 if (CurNum > ArgNum)
1797 Vars.insert(I, Var);
1801 Vars.push_back(Var);
1804 // Gather and emit post-function debug information.
1805 void DwarfDebug::endFunction(const MachineFunction *MF) {
1806 if (!MMI->hasDebugInfo() || LScopes.empty())
1809 // Define end label for subprogram.
1810 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1811 // Assumes in correct section after the entry point.
1812 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1813 // Set DwarfCompileUnitID in MCContext to default value.
1814 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1816 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1817 collectVariableInfo(MF, ProcessedVars);
1819 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1820 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1821 assert(TheCU && "Unable to find compile unit!");
1823 // Construct abstract scopes.
1824 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1825 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1826 LexicalScope *AScope = AList[i];
1827 DISubprogram SP(AScope->getScopeNode());
1828 if (SP.isSubprogram()) {
1829 // Collect info for variables that were optimized out.
1830 DIArray Variables = SP.getVariables();
1831 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1832 DIVariable DV(Variables.getElement(i));
1833 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1835 // Check that DbgVariable for DV wasn't created earlier, when
1836 // findAbstractVariable() was called for inlined instance of DV.
1837 LLVMContext &Ctx = DV->getContext();
1838 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1839 if (AbstractVariables.lookup(CleanDV))
1841 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1842 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1845 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1846 constructScopeDIE(TheCU, AScope);
1849 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1851 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1852 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1855 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1856 E = ScopeVariables.end();
1858 DeleteContainerPointers(I->second);
1859 ScopeVariables.clear();
1860 DeleteContainerPointers(CurrentFnArguments);
1861 UserVariables.clear();
1863 AbstractVariables.clear();
1864 LabelsBeforeInsn.clear();
1865 LabelsAfterInsn.clear();
1869 // Register a source line with debug info. Returns the unique label that was
1870 // emitted and which provides correspondence to the source line list.
1871 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1877 DIDescriptor Scope(S);
1879 if (Scope.isCompileUnit()) {
1880 DICompileUnit CU(S);
1881 Fn = CU.getFilename();
1882 Dir = CU.getDirectory();
1883 } else if (Scope.isFile()) {
1885 Fn = F.getFilename();
1886 Dir = F.getDirectory();
1887 } else if (Scope.isSubprogram()) {
1889 Fn = SP.getFilename();
1890 Dir = SP.getDirectory();
1891 } else if (Scope.isLexicalBlockFile()) {
1892 DILexicalBlockFile DBF(S);
1893 Fn = DBF.getFilename();
1894 Dir = DBF.getDirectory();
1895 } else if (Scope.isLexicalBlock()) {
1896 DILexicalBlock DB(S);
1897 Fn = DB.getFilename();
1898 Dir = DB.getDirectory();
1900 llvm_unreachable("Unexpected scope info");
1902 Src = getOrCreateSourceID(
1903 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1905 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1908 //===----------------------------------------------------------------------===//
1910 //===----------------------------------------------------------------------===//
1912 // Compute the size and offset of a DIE. The offset is relative to start of the
1913 // CU. It returns the offset after laying out the DIE.
1914 unsigned DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1915 // Get the children.
1916 const std::vector<DIE *> &Children = Die->getChildren();
1918 // Record the abbreviation.
1919 assignAbbrevNumber(Die->getAbbrev());
1921 // Get the abbreviation for this DIE.
1922 unsigned AbbrevNumber = Die->getAbbrevNumber();
1923 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1926 Die->setOffset(Offset);
1928 // Start the size with the size of abbreviation code.
1929 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1931 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1932 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1934 // Size the DIE attribute values.
1935 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1936 // Size attribute value.
1937 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1939 // Size the DIE children if any.
1940 if (!Children.empty()) {
1941 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1942 "Children flag not set");
1944 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1945 Offset = computeSizeAndOffset(Children[j], Offset);
1947 // End of children marker.
1948 Offset += sizeof(int8_t);
1951 Die->setSize(Offset - Die->getOffset());
1955 // Compute the size and offset for each DIE.
1956 void DwarfUnits::computeSizeAndOffsets() {
1957 // Offset from the first CU in the debug info section is 0 initially.
1958 unsigned SecOffset = 0;
1960 // Iterate over each compile unit and set the size and offsets for each
1961 // DIE within each compile unit. All offsets are CU relative.
1962 for (SmallVectorImpl<Unit *>::const_iterator I = CUs.begin(), E = CUs.end();
1964 (*I)->setDebugInfoOffset(SecOffset);
1966 // CU-relative offset is reset to 0 here.
1967 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1968 (*I)->getHeaderSize(); // Unit-specific headers
1970 // EndOffset here is CU-relative, after laying out
1971 // all of the CU DIE.
1972 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1973 SecOffset += EndOffset;
1977 // Emit initial Dwarf sections with a label at the start of each one.
1978 void DwarfDebug::emitSectionLabels() {
1979 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1981 // Dwarf sections base addresses.
1982 DwarfInfoSectionSym =
1983 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1984 DwarfAbbrevSectionSym =
1985 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1986 if (useSplitDwarf())
1987 DwarfAbbrevDWOSectionSym = emitSectionSym(
1988 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1989 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1991 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1992 emitSectionSym(Asm, MacroInfo);
1994 DwarfLineSectionSym =
1995 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1996 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1997 if (GenerateGnuPubSections) {
1998 DwarfGnuPubNamesSectionSym =
1999 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2000 DwarfGnuPubTypesSectionSym =
2001 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2002 } else if (HasDwarfPubSections) {
2003 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2004 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2007 DwarfStrSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2009 if (useSplitDwarf()) {
2010 DwarfStrDWOSectionSym =
2011 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2012 DwarfAddrSectionSym =
2013 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2015 DwarfDebugRangeSectionSym =
2016 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2018 DwarfDebugLocSectionSym =
2019 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2021 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2022 emitSectionSym(Asm, TLOF.getDataSection());
2025 // Recursively emits a debug information entry.
2026 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2027 // Get the abbreviation for this DIE.
2028 unsigned AbbrevNumber = Die->getAbbrevNumber();
2029 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2031 // Emit the code (index) for the abbreviation.
2032 if (Asm->isVerbose())
2033 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2034 Twine::utohexstr(Die->getOffset()) + ":0x" +
2035 Twine::utohexstr(Die->getSize()) + " " +
2036 dwarf::TagString(Abbrev->getTag()));
2037 Asm->EmitULEB128(AbbrevNumber);
2039 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2040 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2042 // Emit the DIE attribute values.
2043 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2044 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2045 dwarf::Form Form = AbbrevData[i].getForm();
2046 assert(Form && "Too many attributes for DIE (check abbreviation)");
2048 if (Asm->isVerbose())
2049 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2052 case dwarf::DW_AT_abstract_origin:
2053 case dwarf::DW_AT_type:
2054 case dwarf::DW_AT_friend:
2055 case dwarf::DW_AT_specification:
2056 case dwarf::DW_AT_import:
2057 case dwarf::DW_AT_containing_type: {
2058 DIEEntry *E = cast<DIEEntry>(Values[i]);
2059 DIE *Origin = E->getEntry();
2060 unsigned Addr = Origin->getOffset();
2061 if (Form == dwarf::DW_FORM_ref_addr) {
2062 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2063 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2064 // section. Origin->getOffset() returns the offset from start of the
2066 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2067 assert(CU && "CUDie should belong to a CU.");
2068 Addr += CU->getDebugInfoOffset();
2069 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2070 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2071 DIEEntry::getRefAddrSize(Asm));
2073 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2074 DwarfInfoSectionSym,
2075 DIEEntry::getRefAddrSize(Asm));
2077 // Make sure Origin belong to the same CU.
2078 assert(Die->getUnit() == Origin->getUnit() &&
2079 "The referenced DIE should belong to the same CU in ref4");
2080 Asm->EmitInt32(Addr);
2084 case dwarf::DW_AT_ranges: {
2085 // DW_AT_range Value encodes offset in debug_range section.
2086 DIELabel *V = cast<DIELabel>(Values[i]);
2088 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2089 Asm->EmitSectionOffset(V->getValue(), DwarfDebugRangeSectionSym);
2091 Asm->EmitLabelDifference(V->getValue(), DwarfDebugRangeSectionSym, 4);
2094 case dwarf::DW_AT_location: {
2095 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2096 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2097 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2099 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2101 Values[i]->EmitValue(Asm, Form);
2105 case dwarf::DW_AT_accessibility: {
2106 if (Asm->isVerbose()) {
2107 DIEInteger *V = cast<DIEInteger>(Values[i]);
2108 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2110 Values[i]->EmitValue(Asm, Form);
2114 // Emit an attribute using the defined form.
2115 Values[i]->EmitValue(Asm, Form);
2120 // Emit the DIE children if any.
2121 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2122 const std::vector<DIE *> &Children = Die->getChildren();
2124 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2125 emitDIE(Children[j], Abbrevs);
2127 if (Asm->isVerbose())
2128 Asm->OutStreamer.AddComment("End Of Children Mark");
2133 // Emit the various dwarf units to the unit section USection with
2134 // the abbreviations going into ASection.
2135 void DwarfUnits::emitUnits(DwarfDebug *DD, const MCSection *USection,
2136 const MCSection *ASection,
2137 const MCSymbol *ASectionSym) {
2138 Asm->OutStreamer.SwitchSection(USection);
2139 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
2142 DIE *Die = TheU->getUnitDie();
2144 // Emit the compile units header.
2145 Asm->OutStreamer.EmitLabel(
2146 Asm->GetTempSymbol(USection->getLabelBeginName(), TheU->getUniqueID()));
2148 // Emit size of content not including length itself
2149 Asm->OutStreamer.AddComment("Length of Unit");
2150 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2152 TheU->emitHeader(ASection, ASectionSym);
2154 DD->emitDIE(Die, Abbreviations);
2155 Asm->OutStreamer.EmitLabel(
2156 Asm->GetTempSymbol(USection->getLabelEndName(), TheU->getUniqueID()));
2160 // Emit the debug info section.
2161 void DwarfDebug::emitDebugInfo() {
2162 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2164 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2165 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2166 DwarfAbbrevSectionSym);
2169 // Emit the abbreviation section.
2170 void DwarfDebug::emitAbbreviations() {
2171 if (!useSplitDwarf())
2172 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2175 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2178 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2179 std::vector<DIEAbbrev *> *Abbrevs) {
2180 // Check to see if it is worth the effort.
2181 if (!Abbrevs->empty()) {
2182 // Start the debug abbrev section.
2183 Asm->OutStreamer.SwitchSection(Section);
2185 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2186 Asm->OutStreamer.EmitLabel(Begin);
2188 // For each abbrevation.
2189 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2190 // Get abbreviation data
2191 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2193 // Emit the abbrevations code (base 1 index.)
2194 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2196 // Emit the abbreviations data.
2200 // Mark end of abbreviations.
2201 Asm->EmitULEB128(0, "EOM(3)");
2203 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2204 Asm->OutStreamer.EmitLabel(End);
2208 // Emit the last address of the section and the end of the line matrix.
2209 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2210 // Define last address of section.
2211 Asm->OutStreamer.AddComment("Extended Op");
2214 Asm->OutStreamer.AddComment("Op size");
2215 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2216 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2217 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2219 Asm->OutStreamer.AddComment("Section end label");
2221 Asm->OutStreamer.EmitSymbolValue(
2222 Asm->GetTempSymbol("section_end", SectionEnd),
2223 Asm->getDataLayout().getPointerSize());
2225 // Mark end of matrix.
2226 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2232 // Emit visible names into a hashed accelerator table section.
2233 void DwarfDebug::emitAccelNames() {
2235 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2236 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2237 E = getUnits().end();
2240 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2241 for (StringMap<std::vector<const DIE *> >::const_iterator
2245 StringRef Name = GI->getKey();
2246 const std::vector<const DIE *> &Entities = GI->second;
2247 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2248 DE = Entities.end();
2250 AT.AddName(Name, *DI);
2254 AT.FinalizeTable(Asm, "Names");
2255 Asm->OutStreamer.SwitchSection(
2256 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2257 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2258 Asm->OutStreamer.EmitLabel(SectionBegin);
2260 // Emit the full data.
2261 AT.Emit(Asm, SectionBegin, &InfoHolder);
2264 // Emit objective C classes and categories into a hashed accelerator table
2266 void DwarfDebug::emitAccelObjC() {
2268 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2269 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2270 E = getUnits().end();
2273 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2274 for (StringMap<std::vector<const DIE *> >::const_iterator
2278 StringRef Name = GI->getKey();
2279 const std::vector<const DIE *> &Entities = GI->second;
2280 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2281 DE = Entities.end();
2283 AT.AddName(Name, *DI);
2287 AT.FinalizeTable(Asm, "ObjC");
2288 Asm->OutStreamer.SwitchSection(
2289 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2290 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2291 Asm->OutStreamer.EmitLabel(SectionBegin);
2293 // Emit the full data.
2294 AT.Emit(Asm, SectionBegin, &InfoHolder);
2297 // Emit namespace dies into a hashed accelerator table.
2298 void DwarfDebug::emitAccelNamespaces() {
2300 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2301 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2302 E = getUnits().end();
2305 const StringMap<std::vector<const DIE *> > &Names =
2306 TheU->getAccelNamespace();
2307 for (StringMap<std::vector<const DIE *> >::const_iterator
2311 StringRef Name = GI->getKey();
2312 const std::vector<const DIE *> &Entities = GI->second;
2313 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2314 DE = Entities.end();
2316 AT.AddName(Name, *DI);
2320 AT.FinalizeTable(Asm, "namespac");
2321 Asm->OutStreamer.SwitchSection(
2322 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2323 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2324 Asm->OutStreamer.EmitLabel(SectionBegin);
2326 // Emit the full data.
2327 AT.Emit(Asm, SectionBegin, &InfoHolder);
2330 // Emit type dies into a hashed accelerator table.
2331 void DwarfDebug::emitAccelTypes() {
2332 std::vector<DwarfAccelTable::Atom> Atoms;
2334 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2336 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2338 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2339 DwarfAccelTable AT(Atoms);
2340 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2341 E = getUnits().end();
2344 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2345 TheU->getAccelTypes();
2347 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2351 StringRef Name = GI->getKey();
2352 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2354 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2355 DI = Entities.begin(),
2356 DE = Entities.end();
2358 AT.AddName(Name, DI->first, DI->second);
2362 AT.FinalizeTable(Asm, "types");
2363 Asm->OutStreamer.SwitchSection(
2364 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2365 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2366 Asm->OutStreamer.EmitLabel(SectionBegin);
2368 // Emit the full data.
2369 AT.Emit(Asm, SectionBegin, &InfoHolder);
2372 // Public name handling.
2373 // The format for the various pubnames:
2375 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2376 // for the DIE that is named.
2378 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2379 // into the CU and the index value is computed according to the type of value
2380 // for the DIE that is named.
2382 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2383 // it's the offset within the debug_info/debug_types dwo section, however, the
2384 // reference in the pubname header doesn't change.
2386 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2387 static dwarf::PubIndexEntryDescriptor computeIndexValue(Unit *CU,
2389 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2391 // We could have a specification DIE that has our most of our knowledge,
2392 // look for that now.
2393 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2395 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2396 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2397 Linkage = dwarf::GIEL_EXTERNAL;
2398 } else if (Die->findAttribute(dwarf::DW_AT_external))
2399 Linkage = dwarf::GIEL_EXTERNAL;
2401 switch (Die->getTag()) {
2402 case dwarf::DW_TAG_class_type:
2403 case dwarf::DW_TAG_structure_type:
2404 case dwarf::DW_TAG_union_type:
2405 case dwarf::DW_TAG_enumeration_type:
2406 return dwarf::PubIndexEntryDescriptor(
2407 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2408 ? dwarf::GIEL_STATIC
2409 : dwarf::GIEL_EXTERNAL);
2410 case dwarf::DW_TAG_typedef:
2411 case dwarf::DW_TAG_base_type:
2412 case dwarf::DW_TAG_subrange_type:
2413 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2414 case dwarf::DW_TAG_namespace:
2415 return dwarf::GIEK_TYPE;
2416 case dwarf::DW_TAG_subprogram:
2417 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2418 case dwarf::DW_TAG_constant:
2419 case dwarf::DW_TAG_variable:
2420 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2421 case dwarf::DW_TAG_enumerator:
2422 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2423 dwarf::GIEL_STATIC);
2425 return dwarf::GIEK_NONE;
2429 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2431 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2432 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2433 const MCSection *PSec =
2434 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2435 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2437 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2438 E = getUnits().end();
2441 unsigned ID = TheU->getUniqueID();
2443 // Start the dwarf pubnames section.
2444 Asm->OutStreamer.SwitchSection(PSec);
2446 // Emit a label so we can reference the beginning of this pubname section.
2448 Asm->OutStreamer.EmitLabel(
2449 Asm->GetTempSymbol("gnu_pubnames", TheU->getUniqueID()));
2452 Asm->OutStreamer.AddComment("Length of Public Names Info");
2453 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2454 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2456 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2458 Asm->OutStreamer.AddComment("DWARF Version");
2459 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2461 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2462 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2463 DwarfInfoSectionSym);
2465 Asm->OutStreamer.AddComment("Compilation Unit Length");
2466 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2467 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2470 // Emit the pubnames for this compilation unit.
2471 const StringMap<const DIE *> &Globals = TheU->getGlobalNames();
2472 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2475 const char *Name = GI->getKeyData();
2476 const DIE *Entity = GI->second;
2478 Asm->OutStreamer.AddComment("DIE offset");
2479 Asm->EmitInt32(Entity->getOffset());
2482 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2483 Asm->OutStreamer.AddComment(
2484 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2485 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2486 Asm->EmitInt8(Desc.toBits());
2489 if (Asm->isVerbose())
2490 Asm->OutStreamer.AddComment("External Name");
2491 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2494 Asm->OutStreamer.AddComment("End Mark");
2496 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2500 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2501 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2502 const MCSection *PSec =
2503 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2504 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2506 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2507 E = getUnits().end();
2510 // Start the dwarf pubtypes section.
2511 Asm->OutStreamer.SwitchSection(PSec);
2513 // Emit a label so we can reference the beginning of this pubtype section.
2515 Asm->OutStreamer.EmitLabel(
2516 Asm->GetTempSymbol("gnu_pubtypes", TheU->getUniqueID()));
2519 Asm->OutStreamer.AddComment("Length of Public Types Info");
2520 Asm->EmitLabelDifference(
2521 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()),
2522 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()), 4);
2524 Asm->OutStreamer.EmitLabel(
2525 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()));
2527 if (Asm->isVerbose())
2528 Asm->OutStreamer.AddComment("DWARF Version");
2529 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2531 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2532 Asm->EmitSectionOffset(
2533 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()),
2534 DwarfInfoSectionSym);
2536 Asm->OutStreamer.AddComment("Compilation Unit Length");
2537 Asm->EmitLabelDifference(
2538 Asm->GetTempSymbol(ISec->getLabelEndName(), TheU->getUniqueID()),
2539 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()), 4);
2541 // Emit the pubtypes.
2542 const StringMap<const DIE *> &Globals = TheU->getGlobalTypes();
2543 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2546 const char *Name = GI->getKeyData();
2547 const DIE *Entity = GI->second;
2549 if (Asm->isVerbose())
2550 Asm->OutStreamer.AddComment("DIE offset");
2551 Asm->EmitInt32(Entity->getOffset());
2554 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2555 Asm->OutStreamer.AddComment(
2556 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2557 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2558 Asm->EmitInt8(Desc.toBits());
2561 if (Asm->isVerbose())
2562 Asm->OutStreamer.AddComment("External Name");
2564 // Emit the name with a terminating null byte.
2565 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2568 Asm->OutStreamer.AddComment("End Mark");
2570 Asm->OutStreamer.EmitLabel(
2571 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()));
2575 // Emit strings into a string section.
2576 void DwarfUnits::emitStrings(const MCSection *StrSection,
2577 const MCSection *OffsetSection = NULL,
2578 const MCSymbol *StrSecSym = NULL) {
2580 if (StringPool.empty())
2583 // Start the dwarf str section.
2584 Asm->OutStreamer.SwitchSection(StrSection);
2586 // Get all of the string pool entries and put them in an array by their ID so
2587 // we can sort them.
2589 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2592 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2593 I = StringPool.begin(),
2594 E = StringPool.end();
2596 Entries.push_back(std::make_pair(I->second.second, &*I));
2598 array_pod_sort(Entries.begin(), Entries.end());
2600 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2601 // Emit a label for reference from debug information entries.
2602 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2604 // Emit the string itself with a terminating null byte.
2605 Asm->OutStreamer.EmitBytes(
2606 StringRef(Entries[i].second->getKeyData(),
2607 Entries[i].second->getKeyLength() + 1));
2610 // If we've got an offset section go ahead and emit that now as well.
2611 if (OffsetSection) {
2612 Asm->OutStreamer.SwitchSection(OffsetSection);
2613 unsigned offset = 0;
2614 unsigned size = 4; // FIXME: DWARF64 is 8.
2615 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2616 Asm->OutStreamer.EmitIntValue(offset, size);
2617 offset += Entries[i].second->getKeyLength() + 1;
2623 // Emit addresses into the section given.
2624 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2626 if (AddressPool.empty())
2629 // Start the dwarf addr section.
2630 Asm->OutStreamer.SwitchSection(AddrSection);
2632 // Order the address pool entries by ID
2633 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2635 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2636 E = AddressPool.end();
2638 Entries[I->second] = I->first;
2640 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2641 // Emit an expression for reference from debug information entries.
2642 if (const MCExpr *Expr = Entries[i])
2643 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2645 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2649 // Emit visible names into a debug str section.
2650 void DwarfDebug::emitDebugStr() {
2651 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2652 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2655 // Emit locations into the debug loc section.
2656 void DwarfDebug::emitDebugLoc() {
2657 if (DotDebugLocEntries.empty())
2660 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2661 I = DotDebugLocEntries.begin(),
2662 E = DotDebugLocEntries.end();
2664 DotDebugLocEntry &Entry = *I;
2665 if (I + 1 != DotDebugLocEntries.end())
2669 // Start the dwarf loc section.
2670 Asm->OutStreamer.SwitchSection(
2671 Asm->getObjFileLowering().getDwarfLocSection());
2672 unsigned char Size = Asm->getDataLayout().getPointerSize();
2673 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2675 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2676 I = DotDebugLocEntries.begin(),
2677 E = DotDebugLocEntries.end();
2678 I != E; ++I, ++index) {
2679 DotDebugLocEntry &Entry = *I;
2680 if (Entry.isMerged())
2682 if (Entry.isEmpty()) {
2683 Asm->OutStreamer.EmitIntValue(0, Size);
2684 Asm->OutStreamer.EmitIntValue(0, Size);
2685 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2687 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2688 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2689 DIVariable DV(Entry.getVariable());
2690 Asm->OutStreamer.AddComment("Loc expr size");
2691 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2692 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2693 Asm->EmitLabelDifference(end, begin, 2);
2694 Asm->OutStreamer.EmitLabel(begin);
2695 if (Entry.isInt()) {
2696 DIBasicType BTy(DV.getType());
2697 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2698 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2699 Asm->OutStreamer.AddComment("DW_OP_consts");
2700 Asm->EmitInt8(dwarf::DW_OP_consts);
2701 Asm->EmitSLEB128(Entry.getInt());
2703 Asm->OutStreamer.AddComment("DW_OP_constu");
2704 Asm->EmitInt8(dwarf::DW_OP_constu);
2705 Asm->EmitULEB128(Entry.getInt());
2707 } else if (Entry.isLocation()) {
2708 MachineLocation Loc = Entry.getLoc();
2709 if (!DV.hasComplexAddress())
2711 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2713 // Complex address entry.
2714 unsigned N = DV.getNumAddrElements();
2716 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2717 if (Loc.getOffset()) {
2719 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2720 Asm->OutStreamer.AddComment("DW_OP_deref");
2721 Asm->EmitInt8(dwarf::DW_OP_deref);
2722 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2723 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2724 Asm->EmitSLEB128(DV.getAddrElement(1));
2726 // If first address element is OpPlus then emit
2727 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2728 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2729 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2733 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2736 // Emit remaining complex address elements.
2737 for (; i < N; ++i) {
2738 uint64_t Element = DV.getAddrElement(i);
2739 if (Element == DIBuilder::OpPlus) {
2740 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2741 Asm->EmitULEB128(DV.getAddrElement(++i));
2742 } else if (Element == DIBuilder::OpDeref) {
2744 Asm->EmitInt8(dwarf::DW_OP_deref);
2746 llvm_unreachable("unknown Opcode found in complex address");
2750 // else ... ignore constant fp. There is not any good way to
2751 // to represent them here in dwarf.
2752 Asm->OutStreamer.EmitLabel(end);
2757 struct SymbolCUSorter {
2758 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2759 const MCStreamer &Streamer;
2761 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2762 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2763 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2765 // Symbols with no order assigned should be placed at the end.
2766 // (e.g. section end labels)
2768 IA = (unsigned)(-1);
2770 IB = (unsigned)(-1);
2775 static bool CUSort(const Unit *A, const Unit *B) {
2776 return (A->getUniqueID() < B->getUniqueID());
2780 const MCSymbol *Start, *End;
2783 // Emit a debug aranges section, containing a CU lookup for any
2784 // address we can tie back to a CU.
2785 void DwarfDebug::emitDebugARanges() {
2786 // Start the dwarf aranges section.
2787 Asm->OutStreamer.SwitchSection(
2788 Asm->getObjFileLowering().getDwarfARangesSection());
2790 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2794 // Build a list of sections used.
2795 std::vector<const MCSection *> Sections;
2796 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2798 const MCSection *Section = it->first;
2799 Sections.push_back(Section);
2802 // Sort the sections into order.
2803 // This is only done to ensure consistent output order across different runs.
2804 std::sort(Sections.begin(), Sections.end(), SectionSort);
2806 // Build a set of address spans, sorted by CU.
2807 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2808 const MCSection *Section = Sections[SecIdx];
2809 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2810 if (List.size() < 2)
2813 // Sort the symbols by offset within the section.
2814 SymbolCUSorter sorter(Asm->OutStreamer);
2815 std::sort(List.begin(), List.end(), sorter);
2817 // If we have no section (e.g. common), just write out
2818 // individual spans for each symbol.
2819 if (Section == NULL) {
2820 for (size_t n = 0; n < List.size(); n++) {
2821 const SymbolCU &Cur = List[n];
2824 Span.Start = Cur.Sym;
2827 Spans[Cur.CU].push_back(Span);
2830 // Build spans between each label.
2831 const MCSymbol *StartSym = List[0].Sym;
2832 for (size_t n = 1; n < List.size(); n++) {
2833 const SymbolCU &Prev = List[n - 1];
2834 const SymbolCU &Cur = List[n];
2836 // Try and build the longest span we can within the same CU.
2837 if (Cur.CU != Prev.CU) {
2839 Span.Start = StartSym;
2841 Spans[Prev.CU].push_back(Span);
2848 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2849 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2851 // Build a list of CUs used.
2852 std::vector<CompileUnit *> CUs;
2853 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2854 CompileUnit *CU = it->first;
2858 // Sort the CU list (again, to ensure consistent output order).
2859 std::sort(CUs.begin(), CUs.end(), CUSort);
2861 // Emit an arange table for each CU we used.
2862 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2863 CompileUnit *CU = CUs[CUIdx];
2864 std::vector<ArangeSpan> &List = Spans[CU];
2866 // Emit size of content not including length itself.
2867 unsigned ContentSize =
2868 sizeof(int16_t) + // DWARF ARange version number
2869 sizeof(int32_t) + // Offset of CU in the .debug_info section
2870 sizeof(int8_t) + // Pointer Size (in bytes)
2871 sizeof(int8_t); // Segment Size (in bytes)
2873 unsigned TupleSize = PtrSize * 2;
2875 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2876 unsigned Padding = 0;
2877 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2880 ContentSize += Padding;
2881 ContentSize += (List.size() + 1) * TupleSize;
2883 // For each compile unit, write the list of spans it covers.
2884 Asm->OutStreamer.AddComment("Length of ARange Set");
2885 Asm->EmitInt32(ContentSize);
2886 Asm->OutStreamer.AddComment("DWARF Arange version number");
2887 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2888 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2889 Asm->EmitSectionOffset(
2890 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2891 DwarfInfoSectionSym);
2892 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2893 Asm->EmitInt8(PtrSize);
2894 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2897 for (unsigned n = 0; n < Padding; n++)
2898 Asm->EmitInt8(0xff);
2900 for (unsigned n = 0; n < List.size(); n++) {
2901 const ArangeSpan &Span = List[n];
2902 Asm->EmitLabelReference(Span.Start, PtrSize);
2904 // Calculate the size as being from the span start to it's end.
2906 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2908 // For symbols without an end marker (e.g. common), we
2909 // write a single arange entry containing just that one symbol.
2910 uint64_t Size = SymSize[Span.Start];
2914 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2918 Asm->OutStreamer.AddComment("ARange terminator");
2919 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2920 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2924 // Emit visible names into a debug ranges section.
2925 void DwarfDebug::emitDebugRanges() {
2926 // Start the dwarf ranges section.
2927 Asm->OutStreamer.SwitchSection(
2928 Asm->getObjFileLowering().getDwarfRangesSection());
2930 // Size for our labels.
2931 unsigned char Size = Asm->getDataLayout().getPointerSize();
2933 // Grab the specific ranges for the compile units in the module.
2934 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2937 CompileUnit *TheCU = I->second;
2938 unsigned ID = TheCU->getUniqueID();
2940 // Emit a symbol so we can find the beginning of our ranges.
2941 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_ranges", ID));
2943 // Iterate over the misc ranges for the compile units in the module.
2944 const SmallVectorImpl<RangeSpanList *> &RangeLists = TheCU->getRangeLists();
2945 for (SmallVectorImpl<RangeSpanList *>::const_iterator
2946 I = RangeLists.begin(),
2947 E = RangeLists.end();
2949 RangeSpanList *List = *I;
2951 // Emit a symbol so we can find the beginning of the range.
2952 Asm->OutStreamer.EmitLabel(
2953 Asm->GetTempSymbol("debug_ranges", List->getIndex()));
2955 for (SmallVectorImpl<RangeSpan>::const_iterator
2956 I = List->getRanges().begin(),
2957 E = List->getRanges().end();
2959 RangeSpan Range = *I;
2960 // We occasionally have ranges without begin/end labels.
2961 // FIXME: Verify and fix.
2962 const MCSymbol *Begin = Range.getStart();
2963 const MCSymbol *End = Range.getEnd();
2964 Begin ? Asm->OutStreamer.EmitSymbolValue(Begin, Size)
2965 : Asm->OutStreamer.EmitIntValue(0, Size);
2966 End ? Asm->OutStreamer.EmitSymbolValue(End, Size)
2967 : Asm->OutStreamer.EmitIntValue(0, Size);
2970 // And terminate the list with two 0 values.
2971 Asm->OutStreamer.EmitIntValue(0, Size);
2972 Asm->OutStreamer.EmitIntValue(0, Size);
2977 // Emit visible names into a debug macinfo section.
2978 void DwarfDebug::emitDebugMacInfo() {
2979 if (const MCSection *LineInfo =
2980 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2981 // Start the dwarf macinfo section.
2982 Asm->OutStreamer.SwitchSection(LineInfo);
2986 // DWARF5 Experimental Separate Dwarf emitters.
2988 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2989 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2990 // DW_AT_ranges_base, DW_AT_addr_base.
2991 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2993 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2994 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2995 Asm, this, &SkeletonHolder);
2997 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2998 CU->getNode().getSplitDebugFilename());
3000 // Relocate to the beginning of the addr_base section, else 0 for the
3001 // beginning of the one for this compile unit.
3002 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3003 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
3004 DwarfAddrSectionSym);
3006 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
3008 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
3009 // into an entity. We're using 0, or a NULL label for this.
3010 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
3012 // DW_AT_stmt_list is a offset of line number information for this
3013 // compile unit in debug_line section.
3014 // FIXME: Should handle multiple compile units.
3015 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3016 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
3017 DwarfLineSectionSym);
3019 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
3021 if (!CompilationDir.empty())
3022 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3024 // Flags to let the linker know we have emitted new style pubnames.
3025 if (GenerateGnuPubSections) {
3026 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3027 NewCU->addSectionLabel(
3028 Die, dwarf::DW_AT_GNU_pubnames,
3029 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
3031 NewCU->addSectionDelta(
3032 Die, dwarf::DW_AT_GNU_pubnames,
3033 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
3034 DwarfGnuPubNamesSectionSym);
3036 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3037 NewCU->addSectionLabel(
3038 Die, dwarf::DW_AT_GNU_pubtypes,
3039 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3041 NewCU->addSectionDelta(
3042 Die, dwarf::DW_AT_GNU_pubtypes,
3043 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3044 DwarfGnuPubTypesSectionSym);
3047 // Attribute if we've emitted any ranges and their location for the compile unit.
3048 if (CU->getRangeLists().size()) {
3049 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3050 NewCU->addSectionLabel(
3051 Die, dwarf::DW_AT_GNU_ranges_base,
3052 Asm->GetTempSymbol("gnu_ranges", NewCU->getUniqueID()));
3054 NewCU->addSectionDelta(
3055 Die, dwarf::DW_AT_GNU_ranges_base,
3056 Asm->GetTempSymbol("gnu_ranges", NewCU->getUniqueID()),
3057 DwarfDebugRangeSectionSym);
3060 SkeletonHolder.addUnit(NewCU);
3065 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3066 assert(useSplitDwarf() && "No split dwarf debug info?");
3067 emitAbbrevs(Section, &SkeletonAbbrevs);
3070 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3071 // compile units that would normally be in debug_info.
3072 void DwarfDebug::emitDebugInfoDWO() {
3073 assert(useSplitDwarf() && "No split dwarf debug info?");
3074 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3075 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3076 DwarfAbbrevDWOSectionSym);
3079 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3080 // abbreviations for the .debug_info.dwo section.
3081 void DwarfDebug::emitDebugAbbrevDWO() {
3082 assert(useSplitDwarf() && "No split dwarf?");
3083 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3087 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3088 // string section and is identical in format to traditional .debug_str
3090 void DwarfDebug::emitDebugStrDWO() {
3091 assert(useSplitDwarf() && "No split dwarf?");
3092 const MCSection *OffSec =
3093 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3094 const MCSymbol *StrSym = DwarfStrSectionSym;
3095 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3099 void DwarfDebug::addTypeUnitType(uint16_t Language, DIE *RefDie,
3100 DICompositeType CTy) {
3101 DenseMap<const MDNode *,
3102 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3103 TypeUnits.find(CTy);
3104 SmallVector<DIE *, 8> References;
3105 References.push_back(RefDie);
3106 if (I != TypeUnits.end()) {
3107 if (I->second.second) {
3108 I->second.second->push_back(RefDie);
3112 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3113 TypeUnit *NewTU = new TypeUnit(GlobalCUIndexCount++, UnitDie, Language, Asm,
3115 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3118 // Register the type in the TypeUnits map with a vector of references to be
3119 // populated whenever a reference is required.
3120 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3123 // Construct the type, this may, recursively, require more type units that
3124 // may in turn require this type again - in which case they will add DIEs to
3125 // the References vector.
3126 DIE *Die = NewTU->createTypeDIE(CTy);
3128 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3129 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3130 dwarf::DW_FORM_data8,
3131 DIEHash().computeDIEODRSignature(*Die));
3132 // FIXME: This won't handle circularly referential structures, as the DIE
3133 // may have references to other DIEs still under construction and missing
3134 // their signature. Hashing should walk through the signatures to their
3135 // referenced type, or possibly walk the precomputed hashes of related types
3137 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3139 // Remove the References vector and add the type hash.
3140 I->second.first = Signature;
3141 I->second.second = NULL;
3143 InfoHolder.addUnit(NewTU);
3146 // Populate all the signatures.
3147 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3148 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3149 dwarf::DW_FORM_ref_sig8, I->second.first);