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 "DwarfCompileUnit.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 InfoHolder(A, &AbbreviationsSet, Abbreviations, "info_string",
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<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
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(CompileUnit *TheCU, DISubprogram SP, DIE *Die) {
345 if (!SP.isDefinition())
347 TheCU->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 TheCU->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 TheCU->addAccelObjC(Class, Die);
361 TheCU->addAccelObjC(Category, Die);
362 // Also add the base method name to the name table.
363 TheCU->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.
393 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
394 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
396 DISubprogram SPDecl = SP.getFunctionDeclaration();
397 if (!SPDecl.isSubprogram()) {
398 // There is not any need to generate specification DIE for a function
399 // defined at compile unit level. If a function is defined inside another
400 // function then gdb prefers the definition at top level and but does not
401 // expect specification DIE in parent function. So avoid creating
402 // specification DIE for a function defined inside a function.
403 DIScope SPContext = resolve(SP.getContext());
404 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
405 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
406 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
409 DICompositeType SPTy = SP.getType();
410 DIArray Args = SPTy.getTypeArray();
411 uint16_t SPTag = SPTy.getTag();
412 if (SPTag == dwarf::DW_TAG_subroutine_type)
413 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
415 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
416 DIType ATy(Args.getElement(i));
417 SPCU->addType(Arg, ATy);
418 if (ATy.isArtificial())
419 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
420 if (ATy.isObjectPointer())
421 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
423 DIE *SPDeclDie = SPDie;
425 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
426 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
431 SPCU->addLabelAddress(
432 SPDie, dwarf::DW_AT_low_pc,
433 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
434 SPCU->addLabelAddress(
435 SPDie, dwarf::DW_AT_high_pc,
436 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
437 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
438 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
439 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
441 // Add name to the name table, we do this here because we're guaranteed
442 // to have concrete versions of our DW_TAG_subprogram nodes.
443 addSubprogramNames(SPCU, SP, SPDie);
448 /// Check whether we should create a DIE for the given Scope, return true
449 /// if we don't create a DIE (the corresponding DIE is null).
450 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
451 if (Scope->isAbstractScope())
454 // We don't create a DIE if there is no Range.
455 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
459 if (Ranges.size() > 1)
462 // We don't create a DIE if we have a single Range and the end label
464 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
465 MCSymbol *End = getLabelAfterInsn(RI->second);
469 // Construct new DW_TAG_lexical_block for this scope and attach
470 // DW_AT_low_pc/DW_AT_high_pc labels.
471 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
472 LexicalScope *Scope) {
473 if (isLexicalScopeDIENull(Scope))
476 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
477 if (Scope->isAbstractScope())
480 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
481 // If we have multiple ranges, emit them into the range section.
482 if (Ranges.size() > 1) {
483 // .debug_range section has not been laid out yet. Emit offset in
484 // .debug_range as a relocatable label. emitDIE will handle
485 // emitting it appropriately.
486 unsigned Offset = DebugRangeSymbols.size();
487 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
488 Asm->GetTempSymbol("debug_ranges", Offset));
489 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
492 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
493 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
496 // Terminate the range list.
497 DebugRangeSymbols.push_back(NULL);
498 DebugRangeSymbols.push_back(NULL);
502 // Construct the address range for this DIE.
503 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
504 MCSymbol *Start = getLabelBeforeInsn(RI->first);
505 MCSymbol *End = getLabelAfterInsn(RI->second);
506 assert(End && "End label should not be null!");
508 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
509 assert(End->isDefined() && "Invalid end label for an inlined scope!");
511 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
512 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
517 // This scope represents inlined body of a function. Construct DIE to
518 // represent this concrete inlined copy of the function.
519 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
520 LexicalScope *Scope) {
521 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
522 assert(Ranges.empty() == false &&
523 "LexicalScope does not have instruction markers!");
525 if (!Scope->getScopeNode())
527 DIScope DS(Scope->getScopeNode());
528 DISubprogram InlinedSP = getDISubprogram(DS);
529 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
531 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
535 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
536 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
538 if (Ranges.size() > 1) {
539 // .debug_range section has not been laid out yet. Emit offset in
540 // .debug_range as a relocatable label. emitDIE will handle
541 // emitting it appropriately.
542 unsigned Offset = DebugRangeSymbols.size();
543 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
544 Asm->GetTempSymbol("debug_ranges", Offset));
545 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
548 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
549 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
551 DebugRangeSymbols.push_back(NULL);
552 DebugRangeSymbols.push_back(NULL);
554 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
555 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
556 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
558 if (StartLabel == 0 || EndLabel == 0)
559 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
561 assert(StartLabel->isDefined() &&
562 "Invalid starting label for an inlined scope!");
563 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
565 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
566 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
569 InlinedSubprogramDIEs.insert(OriginDIE);
571 // Add the call site information to the DIE.
572 DILocation DL(Scope->getInlinedAt());
573 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
574 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
575 TheCU->getUniqueID()));
576 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
578 // Add name to the name table, we do this here because we're guaranteed
579 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
580 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
585 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
586 SmallVectorImpl<DIE *> &Children) {
587 DIE *ObjectPointer = NULL;
589 // Collect arguments for current function.
590 if (LScopes.isCurrentFunctionScope(Scope))
591 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
592 if (DbgVariable *ArgDV = CurrentFnArguments[i])
594 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
595 Children.push_back(Arg);
596 if (ArgDV->isObjectPointer())
600 // Collect lexical scope children first.
601 const SmallVectorImpl<DbgVariable *> &Variables =
602 ScopeVariables.lookup(Scope);
603 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
604 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
605 Scope->isAbstractScope())) {
606 Children.push_back(Variable);
607 if (Variables[i]->isObjectPointer())
608 ObjectPointer = Variable;
610 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
611 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
612 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
613 Children.push_back(Nested);
614 return ObjectPointer;
617 // Construct a DIE for this scope.
618 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
619 if (!Scope || !Scope->getScopeNode())
622 DIScope DS(Scope->getScopeNode());
624 SmallVector<DIE *, 8> Children;
625 DIE *ObjectPointer = NULL;
626 bool ChildrenCreated = false;
628 // We try to create the scope DIE first, then the children DIEs. This will
629 // avoid creating un-used children then removing them later when we find out
630 // the scope DIE is null.
631 DIE *ScopeDIE = NULL;
632 if (Scope->getInlinedAt())
633 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
634 else if (DS.isSubprogram()) {
635 ProcessedSPNodes.insert(DS);
636 if (Scope->isAbstractScope()) {
637 ScopeDIE = TheCU->getDIE(DS);
638 // Note down abstract DIE.
640 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
642 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
644 // Early exit when we know the scope DIE is going to be null.
645 if (isLexicalScopeDIENull(Scope))
648 // We create children here when we know the scope DIE is not going to be
649 // null and the children will be added to the scope DIE.
650 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
651 ChildrenCreated = true;
653 // There is no need to emit empty lexical block DIE.
654 std::pair<ImportedEntityMap::const_iterator,
655 ImportedEntityMap::const_iterator> Range =
657 ScopesWithImportedEntities.begin(),
658 ScopesWithImportedEntities.end(),
659 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
661 if (Children.empty() && Range.first == Range.second)
663 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
664 assert(ScopeDIE && "Scope DIE should not be null.");
665 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
667 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
671 assert(Children.empty() &&
672 "We create children only when the scope DIE is not null.");
675 if (!ChildrenCreated)
676 // We create children when the scope DIE is not null.
677 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
680 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
683 ScopeDIE->addChild(*I);
685 if (DS.isSubprogram() && ObjectPointer != NULL)
686 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
688 if (DS.isSubprogram())
689 TheCU->addPubTypes(DISubprogram(DS));
694 // Look up the source id with the given directory and source file names.
695 // If none currently exists, create a new id and insert it in the
696 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
698 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
700 // If we use .loc in assembly, we can't separate .file entries according to
701 // compile units. Thus all files will belong to the default compile unit.
703 // FIXME: add a better feature test than hasRawTextSupport. Even better,
704 // extend .file to support this.
705 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
708 // If FE did not provide a file name, then assume stdin.
709 if (FileName.empty())
710 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
712 // TODO: this might not belong here. See if we can factor this better.
713 if (DirName == CompilationDir)
716 // FileIDCUMap stores the current ID for the given compile unit.
717 unsigned SrcId = FileIDCUMap[CUID] + 1;
719 // We look up the CUID/file/dir by concatenating them with a zero byte.
720 SmallString<128> NamePair;
721 NamePair += utostr(CUID);
724 NamePair += '\0'; // Zero bytes are not allowed in paths.
725 NamePair += FileName;
727 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
728 if (Ent.getValue() != SrcId)
729 return Ent.getValue();
731 FileIDCUMap[CUID] = SrcId;
732 // Print out a .file directive to specify files for .loc directives.
733 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
738 // Create new CompileUnit for the given metadata node with tag
739 // DW_TAG_compile_unit.
740 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
741 StringRef FN = DIUnit.getFilename();
742 CompilationDir = DIUnit.getDirectory();
744 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
745 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
748 FileIDCUMap[NewCU->getUniqueID()] = 0;
749 // Call this to emit a .file directive if it wasn't emitted for the source
750 // file this CU comes from yet.
751 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
753 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
754 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
755 DIUnit.getLanguage());
756 NewCU->addString(Die, dwarf::DW_AT_name, FN);
758 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
759 // into an entity. We're using 0 (or a NULL label) for this. For
760 // split dwarf it's in the skeleton CU so omit it here.
761 if (!useSplitDwarf())
762 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
764 // Define start line table label for each Compile Unit.
765 MCSymbol *LineTableStartSym =
766 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
767 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
768 NewCU->getUniqueID());
770 // Use a single line table if we are using .loc and generating assembly.
772 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
773 (NewCU->getUniqueID() == 0);
775 if (!useSplitDwarf()) {
776 // DW_AT_stmt_list is a offset of line number information for this
777 // compile unit in debug_line section. For split dwarf this is
778 // left in the skeleton CU and so not included.
779 // The line table entries are not always emitted in assembly, so it
780 // is not okay to use line_table_start here.
781 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
782 NewCU->addSectionLabel(
783 Die, dwarf::DW_AT_stmt_list,
784 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
785 : LineTableStartSym);
786 else if (UseTheFirstCU)
787 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
789 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
790 LineTableStartSym, DwarfLineSectionSym);
792 // If we're using split dwarf the compilation dir is going to be in the
793 // skeleton CU and so we don't need to duplicate it here.
794 if (!CompilationDir.empty())
795 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
797 // Flags to let the linker know we have emitted new style pubnames. Only
798 // emit it here if we don't have a skeleton CU for split dwarf.
799 if (GenerateGnuPubSections) {
800 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
801 NewCU->addSectionLabel(
802 Die, dwarf::DW_AT_GNU_pubnames,
803 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
805 NewCU->addSectionDelta(
806 Die, dwarf::DW_AT_GNU_pubnames,
807 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
808 DwarfGnuPubNamesSectionSym);
810 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
811 NewCU->addSectionLabel(
812 Die, dwarf::DW_AT_GNU_pubtypes,
813 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
815 NewCU->addSectionDelta(
816 Die, dwarf::DW_AT_GNU_pubtypes,
817 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
818 DwarfGnuPubTypesSectionSym);
822 if (DIUnit.isOptimized())
823 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
825 StringRef Flags = DIUnit.getFlags();
827 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
829 if (unsigned RVer = DIUnit.getRunTimeVersion())
830 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
831 dwarf::DW_FORM_data1, RVer);
836 InfoHolder.addUnit(NewCU);
838 CUMap.insert(std::make_pair(DIUnit, NewCU));
839 CUDieMap.insert(std::make_pair(Die, NewCU));
843 // Construct subprogram DIE.
844 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
845 // FIXME: We should only call this routine once, however, during LTO if a
846 // program is defined in multiple CUs we could end up calling it out of
847 // beginModule as we walk the CUs.
849 CompileUnit *&CURef = SPMap[N];
855 if (!SP.isDefinition())
856 // This is a method declaration which will be handled while constructing
860 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
862 // Expose as a global name.
863 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
866 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
868 DIImportedEntity Module(N);
869 if (!Module.Verify())
871 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
872 constructImportedEntityDIE(TheCU, Module, D);
875 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
877 DIImportedEntity Module(N);
878 if (!Module.Verify())
880 return constructImportedEntityDIE(TheCU, Module, Context);
883 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
884 const DIImportedEntity &Module,
886 assert(Module.Verify() &&
887 "Use one of the MDNode * overloads to handle invalid metadata");
888 assert(Context && "Should always have a context for an imported_module");
889 DIE *IMDie = new DIE(Module.getTag());
890 TheCU->insertDIE(Module, IMDie);
892 DIDescriptor Entity = Module.getEntity();
893 if (Entity.isNameSpace())
894 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
895 else if (Entity.isSubprogram())
896 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
897 else if (Entity.isType())
898 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
900 EntityDie = TheCU->getDIE(Entity);
901 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
902 Module.getContext().getDirectory(),
903 TheCU->getUniqueID());
904 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
905 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
906 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
907 StringRef Name = Module.getName();
909 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
910 Context->addChild(IMDie);
913 // Emit all Dwarf sections that should come prior to the content. Create
914 // global DIEs and emit initial debug info sections. This is invoked by
915 // the target AsmPrinter.
916 void DwarfDebug::beginModule() {
917 if (DisableDebugInfoPrinting)
920 const Module *M = MMI->getModule();
922 // If module has named metadata anchors then use them, otherwise scan the
923 // module using debug info finder to collect debug info.
924 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
927 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
929 // Emit initial sections so we can reference labels later.
932 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
933 DICompileUnit CUNode(CU_Nodes->getOperand(i));
934 CompileUnit *CU = constructCompileUnit(CUNode);
935 DIArray ImportedEntities = CUNode.getImportedEntities();
936 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
937 ScopesWithImportedEntities.push_back(std::make_pair(
938 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
939 ImportedEntities.getElement(i)));
940 std::sort(ScopesWithImportedEntities.begin(),
941 ScopesWithImportedEntities.end(), less_first());
942 DIArray GVs = CUNode.getGlobalVariables();
943 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
944 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
945 DIArray SPs = CUNode.getSubprograms();
946 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
947 constructSubprogramDIE(CU, SPs.getElement(i));
948 DIArray EnumTypes = CUNode.getEnumTypes();
949 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
950 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
951 DIArray RetainedTypes = CUNode.getRetainedTypes();
952 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
953 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
954 // Emit imported_modules last so that the relevant context is already
956 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
957 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
960 // Tell MMI that we have debug info.
961 MMI->setDebugInfoAvailability(true);
963 // Prime section data.
964 SectionMap[Asm->getObjFileLowering().getTextSection()];
967 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
968 void DwarfDebug::computeInlinedDIEs() {
969 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
970 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
971 AE = InlinedSubprogramDIEs.end();
974 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
976 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
977 AE = AbstractSPDies.end();
979 DIE *ISP = AI->second;
980 if (InlinedSubprogramDIEs.count(ISP))
982 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
986 // Collect info for variables that were optimized out.
987 void DwarfDebug::collectDeadVariables() {
988 const Module *M = MMI->getModule();
990 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
991 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
992 DICompileUnit TheCU(CU_Nodes->getOperand(i));
993 DIArray Subprograms = TheCU.getSubprograms();
994 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
995 DISubprogram SP(Subprograms.getElement(i));
996 if (ProcessedSPNodes.count(SP) != 0)
998 if (!SP.isSubprogram())
1000 if (!SP.isDefinition())
1002 DIArray Variables = SP.getVariables();
1003 if (Variables.getNumElements() == 0)
1006 // Construct subprogram DIE and add variables DIEs.
1007 CompileUnit *SPCU = CUMap.lookup(TheCU);
1008 assert(SPCU && "Unable to find Compile Unit!");
1009 // FIXME: See the comment in constructSubprogramDIE about duplicate
1011 constructSubprogramDIE(SPCU, SP);
1012 DIE *SPDIE = SPCU->getDIE(SP);
1013 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1014 DIVariable DV(Variables.getElement(vi));
1015 if (!DV.isVariable())
1017 DbgVariable NewVar(DV, NULL, this);
1018 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1019 SPDIE->addChild(VariableDIE);
1026 // Type Signature [7.27] and ODR Hash code.
1028 /// \brief Grabs the string in whichever attribute is passed in and returns
1029 /// a reference to it. Returns "" if the attribute doesn't exist.
1030 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1031 DIEValue *V = Die->findAttribute(Attr);
1033 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1034 return S->getString();
1036 return StringRef("");
1039 /// Return true if the current DIE is contained within an anonymous namespace.
1040 static bool isContainedInAnonNamespace(DIE *Die) {
1041 DIE *Parent = Die->getParent();
1044 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1045 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1047 Parent = Parent->getParent();
1053 /// Test if the current CU language is C++ and that we have
1054 /// a named type that is not contained in an anonymous namespace.
1055 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1056 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1057 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1058 !isContainedInAnonNamespace(Die);
1061 void DwarfDebug::finalizeModuleInfo() {
1062 // Collect info for variables that were optimized out.
1063 collectDeadVariables();
1065 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1066 computeInlinedDIEs();
1068 // Handle anything that needs to be done on a per-cu basis.
1069 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1071 CUI != CUE; ++CUI) {
1072 CompileUnit *TheCU = CUI->second;
1073 // Emit DW_AT_containing_type attribute to connect types with their
1074 // vtable holding type.
1075 TheCU->constructContainingTypeDIEs();
1077 // If we're splitting the dwarf out now that we've got the entire
1078 // CU then construct a skeleton CU based upon it.
1079 if (useSplitDwarf()) {
1081 if (GenerateCUHash) {
1083 ID = CUHash.computeCUSignature(*TheCU->getCUDie());
1085 // This should be a unique identifier when we want to build .dwp files.
1086 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1087 dwarf::DW_FORM_data8, ID);
1088 // Now construct the skeleton CU associated.
1089 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1090 // This should be a unique identifier when we want to build .dwp files.
1091 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1092 dwarf::DW_FORM_data8, ID);
1096 // Compute DIE offsets and sizes.
1097 InfoHolder.computeSizeAndOffsets();
1098 if (useSplitDwarf())
1099 SkeletonHolder.computeSizeAndOffsets();
1102 void DwarfDebug::endSections() {
1103 // Filter labels by section.
1104 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1105 const SymbolCU &SCU = ArangeLabels[n];
1106 if (SCU.Sym->isInSection()) {
1107 // Make a note of this symbol and it's section.
1108 const MCSection *Section = &SCU.Sym->getSection();
1109 if (!Section->getKind().isMetadata())
1110 SectionMap[Section].push_back(SCU);
1112 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1113 // appear in the output. This sucks as we rely on sections to build
1114 // arange spans. We can do it without, but it's icky.
1115 SectionMap[NULL].push_back(SCU);
1119 // Build a list of sections used.
1120 std::vector<const MCSection *> Sections;
1121 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1123 const MCSection *Section = it->first;
1124 Sections.push_back(Section);
1127 // Sort the sections into order.
1128 // This is only done to ensure consistent output order across different runs.
1129 std::sort(Sections.begin(), Sections.end(), SectionSort);
1131 // Add terminating symbols for each section.
1132 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1133 const MCSection *Section = Sections[ID];
1134 MCSymbol *Sym = NULL;
1137 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1138 // if we know the section name up-front. For user-created sections, the
1140 // label may not be valid to use as a label. (section names can use a
1142 // set of characters on some systems)
1143 Sym = Asm->GetTempSymbol("debug_end", ID);
1144 Asm->OutStreamer.SwitchSection(Section);
1145 Asm->OutStreamer.EmitLabel(Sym);
1148 // Insert a final terminator.
1149 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1153 // Emit all Dwarf sections that should come after the content.
1154 void DwarfDebug::endModule() {
1159 // End any existing sections.
1160 // TODO: Does this need to happen?
1163 // Finalize the debug info for the module.
1164 finalizeModuleInfo();
1168 // Emit all the DIEs into a debug info section.
1171 // Corresponding abbreviations into a abbrev section.
1172 emitAbbreviations();
1174 // Emit info into a debug loc section.
1177 // Emit info into a debug aranges section.
1180 // Emit info into a debug ranges section.
1183 // Emit info into a debug macinfo section.
1186 if (useSplitDwarf()) {
1189 emitDebugAbbrevDWO();
1190 // Emit DWO addresses.
1191 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1194 // Emit info into the dwarf accelerator table sections.
1195 if (useDwarfAccelTables()) {
1198 emitAccelNamespaces();
1202 // Emit the pubnames and pubtypes sections if requested.
1203 if (HasDwarfPubSections) {
1204 emitDebugPubNames(GenerateGnuPubSections);
1205 emitDebugPubTypes(GenerateGnuPubSections);
1211 // Reset these for the next Module if we have one.
1215 // Find abstract variable, if any, associated with Var.
1216 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1217 DebugLoc ScopeLoc) {
1218 LLVMContext &Ctx = DV->getContext();
1219 // More then one inlined variable corresponds to one abstract variable.
1220 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1221 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1223 return AbsDbgVariable;
1225 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1229 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1230 addScopeVariable(Scope, AbsDbgVariable);
1231 AbstractVariables[Var] = AbsDbgVariable;
1232 return AbsDbgVariable;
1235 // If Var is a current function argument then add it to CurrentFnArguments list.
1236 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1237 DbgVariable *Var, LexicalScope *Scope) {
1238 if (!LScopes.isCurrentFunctionScope(Scope))
1240 DIVariable DV = Var->getVariable();
1241 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1243 unsigned ArgNo = DV.getArgNumber();
1247 size_t Size = CurrentFnArguments.size();
1249 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1250 // llvm::Function argument size is not good indicator of how many
1251 // arguments does the function have at source level.
1253 CurrentFnArguments.resize(ArgNo * 2);
1254 CurrentFnArguments[ArgNo - 1] = Var;
1258 // Collect variable information from side table maintained by MMI.
1259 void DwarfDebug::collectVariableInfoFromMMITable(
1260 const MachineFunction *MF, SmallPtrSet<const MDNode *, 16> &Processed) {
1261 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1262 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1265 const MDNode *Var = VI->first;
1268 Processed.insert(Var);
1270 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1272 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1274 // If variable scope is not found then skip this variable.
1278 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1279 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1280 RegVar->setFrameIndex(VP.first);
1281 if (!addCurrentFnArgument(MF, RegVar, Scope))
1282 addScopeVariable(Scope, RegVar);
1284 AbsDbgVariable->setFrameIndex(VP.first);
1288 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1290 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1291 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1292 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1293 MI->getOperand(0).getReg() &&
1294 (MI->getOperand(1).isImm() ||
1295 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1298 // Get .debug_loc entry for the instruction range starting at MI.
1299 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1300 const MCSymbol *FLabel,
1301 const MCSymbol *SLabel,
1302 const MachineInstr *MI) {
1303 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1305 assert(MI->getNumOperands() == 3);
1306 if (MI->getOperand(0).isReg()) {
1307 MachineLocation MLoc;
1308 // If the second operand is an immediate, this is a
1309 // register-indirect address.
1310 if (!MI->getOperand(1).isImm())
1311 MLoc.set(MI->getOperand(0).getReg());
1313 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1314 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1316 if (MI->getOperand(0).isImm())
1317 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1318 if (MI->getOperand(0).isFPImm())
1319 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1320 if (MI->getOperand(0).isCImm())
1321 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1323 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1326 // Find variables for each lexical scope.
1328 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1329 SmallPtrSet<const MDNode *, 16> &Processed) {
1331 // Grab the variable info that was squirreled away in the MMI side-table.
1332 collectVariableInfoFromMMITable(MF, Processed);
1334 for (SmallVectorImpl<const MDNode *>::const_iterator
1335 UVI = UserVariables.begin(),
1336 UVE = UserVariables.end();
1337 UVI != UVE; ++UVI) {
1338 const MDNode *Var = *UVI;
1339 if (Processed.count(Var))
1342 // History contains relevant DBG_VALUE instructions for Var and instructions
1344 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1345 if (History.empty())
1347 const MachineInstr *MInsn = History.front();
1350 LexicalScope *Scope = NULL;
1351 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1352 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1353 Scope = LScopes.getCurrentFunctionScope();
1354 else if (MDNode *IA = DV.getInlinedAt())
1355 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1357 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1358 // If variable scope is not found then skip this variable.
1362 Processed.insert(DV);
1363 assert(MInsn->isDebugValue() && "History must begin with debug value");
1364 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1365 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1366 if (!addCurrentFnArgument(MF, RegVar, Scope))
1367 addScopeVariable(Scope, RegVar);
1369 AbsVar->setMInsn(MInsn);
1371 // Simplify ranges that are fully coalesced.
1372 if (History.size() <= 1 ||
1373 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1374 RegVar->setMInsn(MInsn);
1378 // Handle multiple DBG_VALUE instructions describing one variable.
1379 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1381 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1382 HI = History.begin(),
1385 const MachineInstr *Begin = *HI;
1386 assert(Begin->isDebugValue() && "Invalid History entry");
1388 // Check if DBG_VALUE is truncating a range.
1389 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1390 !Begin->getOperand(0).getReg())
1393 // Compute the range for a register location.
1394 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1395 const MCSymbol *SLabel = 0;
1398 // If Begin is the last instruction in History then its value is valid
1399 // until the end of the function.
1400 SLabel = FunctionEndSym;
1402 const MachineInstr *End = HI[1];
1403 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1404 << "\t" << *Begin << "\t" << *End << "\n");
1405 if (End->isDebugValue())
1406 SLabel = getLabelBeforeInsn(End);
1408 // End is a normal instruction clobbering the range.
1409 SLabel = getLabelAfterInsn(End);
1410 assert(SLabel && "Forgot label after clobber instruction");
1415 // The value is valid until the next DBG_VALUE or clobber.
1416 DotDebugLocEntries.push_back(
1417 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1419 DotDebugLocEntries.push_back(DotDebugLocEntry());
1422 // Collect info for variables that were optimized out.
1423 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1424 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1425 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1426 DIVariable DV(Variables.getElement(i));
1427 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1429 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1430 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1434 // Return Label preceding the instruction.
1435 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1436 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1437 assert(Label && "Didn't insert label before instruction");
1441 // Return Label immediately following the instruction.
1442 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1443 return LabelsAfterInsn.lookup(MI);
1446 // Process beginning of an instruction.
1447 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1448 // Check if source location changes, but ignore DBG_VALUE locations.
1449 if (!MI->isDebugValue()) {
1450 DebugLoc DL = MI->getDebugLoc();
1451 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1454 if (DL == PrologEndLoc) {
1455 Flags |= DWARF2_FLAG_PROLOGUE_END;
1456 PrologEndLoc = DebugLoc();
1458 if (PrologEndLoc.isUnknown())
1459 Flags |= DWARF2_FLAG_IS_STMT;
1461 if (!DL.isUnknown()) {
1462 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1463 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1465 recordSourceLine(0, 0, 0, 0);
1469 // Insert labels where requested.
1470 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1471 LabelsBeforeInsn.find(MI);
1474 if (I == LabelsBeforeInsn.end())
1477 // Label already assigned.
1482 PrevLabel = MMI->getContext().CreateTempSymbol();
1483 Asm->OutStreamer.EmitLabel(PrevLabel);
1485 I->second = PrevLabel;
1488 // Process end of an instruction.
1489 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1490 // Don't create a new label after DBG_VALUE instructions.
1491 // They don't generate code.
1492 if (!MI->isDebugValue())
1495 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1496 LabelsAfterInsn.find(MI);
1499 if (I == LabelsAfterInsn.end())
1502 // Label already assigned.
1506 // We need a label after this instruction.
1508 PrevLabel = MMI->getContext().CreateTempSymbol();
1509 Asm->OutStreamer.EmitLabel(PrevLabel);
1511 I->second = PrevLabel;
1514 // Each LexicalScope has first instruction and last instruction to mark
1515 // beginning and end of a scope respectively. Create an inverse map that list
1516 // scopes starts (and ends) with an instruction. One instruction may start (or
1517 // end) multiple scopes. Ignore scopes that are not reachable.
1518 void DwarfDebug::identifyScopeMarkers() {
1519 SmallVector<LexicalScope *, 4> WorkList;
1520 WorkList.push_back(LScopes.getCurrentFunctionScope());
1521 while (!WorkList.empty()) {
1522 LexicalScope *S = WorkList.pop_back_val();
1524 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1525 if (!Children.empty())
1526 for (SmallVectorImpl<LexicalScope *>::const_iterator
1527 SI = Children.begin(),
1528 SE = Children.end();
1530 WorkList.push_back(*SI);
1532 if (S->isAbstractScope())
1535 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1538 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1541 assert(RI->first && "InsnRange does not have first instruction!");
1542 assert(RI->second && "InsnRange does not have second instruction!");
1543 requestLabelBeforeInsn(RI->first);
1544 requestLabelAfterInsn(RI->second);
1549 // Get MDNode for DebugLoc's scope.
1550 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1551 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1552 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1553 return DL.getScope(Ctx);
1556 // Walk up the scope chain of given debug loc and find line number info
1557 // for the function.
1558 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1559 const MDNode *Scope = getScopeNode(DL, Ctx);
1560 DISubprogram SP = getDISubprogram(Scope);
1561 if (SP.isSubprogram()) {
1562 // Check for number of operands since the compatibility is
1564 if (SP->getNumOperands() > 19)
1565 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1567 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1573 // Gather pre-function debug information. Assumes being called immediately
1574 // after the function entry point has been emitted.
1575 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1577 // If there's no debug info for the function we're not going to do anything.
1578 if (!MMI->hasDebugInfo())
1581 // Grab the lexical scopes for the function, if we don't have any of those
1582 // then we're not going to be able to do anything.
1583 LScopes.initialize(*MF);
1584 if (LScopes.empty())
1587 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1589 // Make sure that each lexical scope will have a begin/end label.
1590 identifyScopeMarkers();
1592 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1593 // belongs to so that we add to the correct per-cu line table in the
1595 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1596 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1597 assert(TheCU && "Unable to find compile unit!");
1598 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1599 // Use a single line table if we are using .loc and generating assembly.
1600 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1602 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1604 // Emit a label for the function so that we have a beginning address.
1605 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1606 // Assumes in correct section after the entry point.
1607 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1609 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1610 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1611 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1613 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1615 bool AtBlockEntry = true;
1616 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1618 const MachineInstr *MI = II;
1620 if (MI->isDebugValue()) {
1621 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1623 // Keep track of user variables.
1625 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1627 // Variable is in a register, we need to check for clobbers.
1628 if (isDbgValueInDefinedReg(MI))
1629 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1631 // Check the history of this variable.
1632 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1633 if (History.empty()) {
1634 UserVariables.push_back(Var);
1635 // The first mention of a function argument gets the FunctionBeginSym
1636 // label, so arguments are visible when breaking at function entry.
1638 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1639 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1640 LabelsBeforeInsn[MI] = FunctionBeginSym;
1642 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1643 const MachineInstr *Prev = History.back();
1644 if (Prev->isDebugValue()) {
1645 // Coalesce identical entries at the end of History.
1646 if (History.size() >= 2 &&
1647 Prev->isIdenticalTo(History[History.size() - 2])) {
1648 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1649 << "\t" << *Prev << "\t"
1650 << *History[History.size() - 2] << "\n");
1654 // Terminate old register assignments that don't reach MI;
1655 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1656 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1657 isDbgValueInDefinedReg(Prev)) {
1658 // Previous register assignment needs to terminate at the end of
1660 MachineBasicBlock::const_iterator LastMI =
1661 PrevMBB->getLastNonDebugInstr();
1662 if (LastMI == PrevMBB->end()) {
1663 // Drop DBG_VALUE for empty range.
1664 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1665 << "\t" << *Prev << "\n");
1667 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1668 // Terminate after LastMI.
1669 History.push_back(LastMI);
1673 History.push_back(MI);
1675 // Not a DBG_VALUE instruction.
1677 AtBlockEntry = false;
1679 // First known non-DBG_VALUE and non-frame setup location marks
1680 // the beginning of the function body.
1681 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1682 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1683 PrologEndLoc = MI->getDebugLoc();
1685 // Check if the instruction clobbers any registers with debug vars.
1686 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1687 MOE = MI->operands_end();
1688 MOI != MOE; ++MOI) {
1689 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1691 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1694 const MDNode *Var = LiveUserVar[Reg];
1697 // Reg is now clobbered.
1698 LiveUserVar[Reg] = 0;
1700 // Was MD last defined by a DBG_VALUE referring to Reg?
1701 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1702 if (HistI == DbgValues.end())
1704 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1705 if (History.empty())
1707 const MachineInstr *Prev = History.back();
1708 // Sanity-check: Register assignments are terminated at the end of
1710 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1712 // Is the variable still in Reg?
1713 if (!isDbgValueInDefinedReg(Prev) ||
1714 Prev->getOperand(0).getReg() != Reg)
1716 // Var is clobbered. Make sure the next instruction gets a label.
1717 History.push_back(MI);
1724 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1726 SmallVectorImpl<const MachineInstr *> &History = I->second;
1727 if (History.empty())
1730 // Make sure the final register assignments are terminated.
1731 const MachineInstr *Prev = History.back();
1732 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1733 const MachineBasicBlock *PrevMBB = Prev->getParent();
1734 MachineBasicBlock::const_iterator LastMI =
1735 PrevMBB->getLastNonDebugInstr();
1736 if (LastMI == PrevMBB->end())
1737 // Drop DBG_VALUE for empty range.
1739 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1740 // Terminate after LastMI.
1741 History.push_back(LastMI);
1744 // Request labels for the full history.
1745 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1746 const MachineInstr *MI = History[i];
1747 if (MI->isDebugValue())
1748 requestLabelBeforeInsn(MI);
1750 requestLabelAfterInsn(MI);
1754 PrevInstLoc = DebugLoc();
1755 PrevLabel = FunctionBeginSym;
1757 // Record beginning of function.
1758 if (!PrologEndLoc.isUnknown()) {
1759 DebugLoc FnStartDL =
1760 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1762 FnStartDL.getLine(), FnStartDL.getCol(),
1763 FnStartDL.getScope(MF->getFunction()->getContext()),
1764 // We'd like to list the prologue as "not statements" but GDB behaves
1765 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1766 DWARF2_FLAG_IS_STMT);
1770 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1771 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1772 DIVariable DV = Var->getVariable();
1773 // Variables with positive arg numbers are parameters.
1774 if (unsigned ArgNum = DV.getArgNumber()) {
1775 // Keep all parameters in order at the start of the variable list to ensure
1776 // function types are correct (no out-of-order parameters)
1778 // This could be improved by only doing it for optimized builds (unoptimized
1779 // builds have the right order to begin with), searching from the back (this
1780 // would catch the unoptimized case quickly), or doing a binary search
1781 // rather than linear search.
1782 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1783 while (I != Vars.end()) {
1784 unsigned CurNum = (*I)->getVariable().getArgNumber();
1785 // A local (non-parameter) variable has been found, insert immediately
1789 // A later indexed parameter has been found, insert immediately before it.
1790 if (CurNum > ArgNum)
1794 Vars.insert(I, Var);
1798 Vars.push_back(Var);
1801 // Gather and emit post-function debug information.
1802 void DwarfDebug::endFunction(const MachineFunction *MF) {
1803 if (!MMI->hasDebugInfo() || LScopes.empty())
1806 // Define end label for subprogram.
1807 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1808 // Assumes in correct section after the entry point.
1809 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1810 // Set DwarfCompileUnitID in MCContext to default value.
1811 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1813 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1814 collectVariableInfo(MF, ProcessedVars);
1816 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1817 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1818 assert(TheCU && "Unable to find compile unit!");
1820 // Construct abstract scopes.
1821 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1822 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1823 LexicalScope *AScope = AList[i];
1824 DISubprogram SP(AScope->getScopeNode());
1825 if (SP.isSubprogram()) {
1826 // Collect info for variables that were optimized out.
1827 DIArray Variables = SP.getVariables();
1828 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1829 DIVariable DV(Variables.getElement(i));
1830 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1832 // Check that DbgVariable for DV wasn't created earlier, when
1833 // findAbstractVariable() was called for inlined instance of DV.
1834 LLVMContext &Ctx = DV->getContext();
1835 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1836 if (AbstractVariables.lookup(CleanDV))
1838 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1839 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1842 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1843 constructScopeDIE(TheCU, AScope);
1846 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1848 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1849 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1852 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1853 E = ScopeVariables.end();
1855 DeleteContainerPointers(I->second);
1856 ScopeVariables.clear();
1857 DeleteContainerPointers(CurrentFnArguments);
1858 UserVariables.clear();
1860 AbstractVariables.clear();
1861 LabelsBeforeInsn.clear();
1862 LabelsAfterInsn.clear();
1866 // Register a source line with debug info. Returns the unique label that was
1867 // emitted and which provides correspondence to the source line list.
1868 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1874 DIDescriptor Scope(S);
1876 if (Scope.isCompileUnit()) {
1877 DICompileUnit CU(S);
1878 Fn = CU.getFilename();
1879 Dir = CU.getDirectory();
1880 } else if (Scope.isFile()) {
1882 Fn = F.getFilename();
1883 Dir = F.getDirectory();
1884 } else if (Scope.isSubprogram()) {
1886 Fn = SP.getFilename();
1887 Dir = SP.getDirectory();
1888 } else if (Scope.isLexicalBlockFile()) {
1889 DILexicalBlockFile DBF(S);
1890 Fn = DBF.getFilename();
1891 Dir = DBF.getDirectory();
1892 } else if (Scope.isLexicalBlock()) {
1893 DILexicalBlock DB(S);
1894 Fn = DB.getFilename();
1895 Dir = DB.getDirectory();
1897 llvm_unreachable("Unexpected scope info");
1899 Src = getOrCreateSourceID(
1900 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1902 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1905 //===----------------------------------------------------------------------===//
1907 //===----------------------------------------------------------------------===//
1909 // Compute the size and offset of a DIE. The offset is relative to start of the
1910 // CU. It returns the offset after laying out the DIE.
1911 unsigned DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1912 // Get the children.
1913 const std::vector<DIE *> &Children = Die->getChildren();
1915 // Record the abbreviation.
1916 assignAbbrevNumber(Die->getAbbrev());
1918 // Get the abbreviation for this DIE.
1919 unsigned AbbrevNumber = Die->getAbbrevNumber();
1920 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1923 Die->setOffset(Offset);
1925 // Start the size with the size of abbreviation code.
1926 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1928 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1929 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1931 // Size the DIE attribute values.
1932 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1933 // Size attribute value.
1934 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1936 // Size the DIE children if any.
1937 if (!Children.empty()) {
1938 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1939 "Children flag not set");
1941 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1942 Offset = computeSizeAndOffset(Children[j], Offset);
1944 // End of children marker.
1945 Offset += sizeof(int8_t);
1948 Die->setSize(Offset - Die->getOffset());
1952 // Compute the size and offset for each DIE.
1953 void DwarfUnits::computeSizeAndOffsets() {
1954 // Offset from the first CU in the debug info section is 0 initially.
1955 unsigned SecOffset = 0;
1957 // Iterate over each compile unit and set the size and offsets for each
1958 // DIE within each compile unit. All offsets are CU relative.
1959 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
1961 (*I)->setDebugInfoOffset(SecOffset);
1963 // CU-relative offset is reset to 0 here.
1964 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1965 (*I)->getHeaderSize(); // Unit-specific headers
1967 // EndOffset here is CU-relative, after laying out
1968 // all of the CU DIE.
1969 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1970 SecOffset += EndOffset;
1974 // Emit initial Dwarf sections with a label at the start of each one.
1975 void DwarfDebug::emitSectionLabels() {
1976 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1978 // Dwarf sections base addresses.
1979 DwarfInfoSectionSym =
1980 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1981 DwarfAbbrevSectionSym =
1982 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1983 if (useSplitDwarf())
1984 DwarfAbbrevDWOSectionSym = emitSectionSym(
1985 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1986 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1988 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1989 emitSectionSym(Asm, MacroInfo);
1991 DwarfLineSectionSym =
1992 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1993 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1994 if (GenerateGnuPubSections) {
1995 DwarfGnuPubNamesSectionSym =
1996 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1997 DwarfGnuPubTypesSectionSym =
1998 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1999 } else if (HasDwarfPubSections) {
2000 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2001 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2004 DwarfStrSectionSym =
2005 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2006 if (useSplitDwarf()) {
2007 DwarfStrDWOSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2009 DwarfAddrSectionSym =
2010 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2012 DwarfDebugRangeSectionSym =
2013 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2015 DwarfDebugLocSectionSym =
2016 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2018 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2019 emitSectionSym(Asm, TLOF.getDataSection());
2022 // Recursively emits a debug information entry.
2023 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2024 // Get the abbreviation for this DIE.
2025 unsigned AbbrevNumber = Die->getAbbrevNumber();
2026 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2028 // Emit the code (index) for the abbreviation.
2029 if (Asm->isVerbose())
2030 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2031 Twine::utohexstr(Die->getOffset()) + ":0x" +
2032 Twine::utohexstr(Die->getSize()) + " " +
2033 dwarf::TagString(Abbrev->getTag()));
2034 Asm->EmitULEB128(AbbrevNumber);
2036 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2037 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2039 // Emit the DIE attribute values.
2040 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2041 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2042 dwarf::Form Form = AbbrevData[i].getForm();
2043 assert(Form && "Too many attributes for DIE (check abbreviation)");
2045 if (Asm->isVerbose())
2046 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2049 case dwarf::DW_AT_abstract_origin:
2050 case dwarf::DW_AT_type:
2051 case dwarf::DW_AT_friend:
2052 case dwarf::DW_AT_specification:
2053 case dwarf::DW_AT_import:
2054 case dwarf::DW_AT_containing_type: {
2055 DIEEntry *E = cast<DIEEntry>(Values[i]);
2056 DIE *Origin = E->getEntry();
2057 unsigned Addr = Origin->getOffset();
2058 if (Form == dwarf::DW_FORM_ref_addr) {
2059 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2060 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2061 // section. Origin->getOffset() returns the offset from start of the
2063 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2064 assert(CU && "CUDie should belong to a CU.");
2065 Addr += CU->getDebugInfoOffset();
2066 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2067 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2068 DIEEntry::getRefAddrSize(Asm));
2070 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2071 DwarfInfoSectionSym,
2072 DIEEntry::getRefAddrSize(Asm));
2074 // Make sure Origin belong to the same CU.
2075 assert(Die->getUnit() == Origin->getUnit() &&
2076 "The referenced DIE should belong to the same CU in ref4");
2077 Asm->EmitInt32(Addr);
2081 case dwarf::DW_AT_ranges: {
2082 // DW_AT_range Value encodes offset in debug_range section.
2083 DIELabel *V = cast<DIELabel>(Values[i]);
2085 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2086 Asm->EmitSectionOffset(V->getValue(), DwarfDebugRangeSectionSym);
2088 Asm->EmitLabelDifference(V->getValue(), DwarfDebugRangeSectionSym, 4);
2091 case dwarf::DW_AT_location: {
2092 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2093 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2094 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2096 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2098 Values[i]->EmitValue(Asm, Form);
2102 case dwarf::DW_AT_accessibility: {
2103 if (Asm->isVerbose()) {
2104 DIEInteger *V = cast<DIEInteger>(Values[i]);
2105 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2107 Values[i]->EmitValue(Asm, Form);
2111 // Emit an attribute using the defined form.
2112 Values[i]->EmitValue(Asm, Form);
2117 // Emit the DIE children if any.
2118 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2119 const std::vector<DIE *> &Children = Die->getChildren();
2121 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2122 emitDIE(Children[j], Abbrevs);
2124 if (Asm->isVerbose())
2125 Asm->OutStreamer.AddComment("End Of Children Mark");
2130 // Emit the various dwarf units to the unit section USection with
2131 // the abbreviations going into ASection.
2132 void DwarfUnits::emitUnits(DwarfDebug *DD, const MCSection *USection,
2133 const MCSection *ASection,
2134 const MCSymbol *ASectionSym) {
2135 Asm->OutStreamer.SwitchSection(USection);
2136 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2138 CompileUnit *TheCU = *I;
2139 DIE *Die = TheCU->getCUDie();
2141 // Emit the compile units header.
2142 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2143 TheCU->getUniqueID()));
2145 // Emit size of content not including length itself
2146 Asm->OutStreamer.AddComment("Length of Unit");
2147 Asm->EmitInt32(TheCU->getHeaderSize() + Die->getSize());
2149 TheCU->emitHeader(ASection, ASectionSym);
2151 DD->emitDIE(Die, Abbreviations);
2152 Asm->OutStreamer.EmitLabel(
2153 Asm->GetTempSymbol(USection->getLabelEndName(), TheCU->getUniqueID()));
2157 // Emit the debug info section.
2158 void DwarfDebug::emitDebugInfo() {
2159 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2161 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2162 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2163 DwarfAbbrevSectionSym);
2166 // Emit the abbreviation section.
2167 void DwarfDebug::emitAbbreviations() {
2168 if (!useSplitDwarf())
2169 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2172 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2175 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2176 std::vector<DIEAbbrev *> *Abbrevs) {
2177 // Check to see if it is worth the effort.
2178 if (!Abbrevs->empty()) {
2179 // Start the debug abbrev section.
2180 Asm->OutStreamer.SwitchSection(Section);
2182 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2183 Asm->OutStreamer.EmitLabel(Begin);
2185 // For each abbrevation.
2186 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2187 // Get abbreviation data
2188 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2190 // Emit the abbrevations code (base 1 index.)
2191 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2193 // Emit the abbreviations data.
2197 // Mark end of abbreviations.
2198 Asm->EmitULEB128(0, "EOM(3)");
2200 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2201 Asm->OutStreamer.EmitLabel(End);
2205 // Emit the last address of the section and the end of the line matrix.
2206 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2207 // Define last address of section.
2208 Asm->OutStreamer.AddComment("Extended Op");
2211 Asm->OutStreamer.AddComment("Op size");
2212 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2213 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2214 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2216 Asm->OutStreamer.AddComment("Section end label");
2218 Asm->OutStreamer.EmitSymbolValue(
2219 Asm->GetTempSymbol("section_end", SectionEnd),
2220 Asm->getDataLayout().getPointerSize());
2222 // Mark end of matrix.
2223 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2229 // Emit visible names into a hashed accelerator table section.
2230 void DwarfDebug::emitAccelNames() {
2232 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2233 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2236 CompileUnit *TheCU = I->second;
2237 const StringMap<std::vector<const DIE *> > &Names = TheCU->getAccelNames();
2238 for (StringMap<std::vector<const DIE *> >::const_iterator
2242 StringRef Name = GI->getKey();
2243 const std::vector<const DIE *> &Entities = GI->second;
2244 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2245 DE = Entities.end();
2247 AT.AddName(Name, *DI);
2251 AT.FinalizeTable(Asm, "Names");
2252 Asm->OutStreamer.SwitchSection(
2253 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2254 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2255 Asm->OutStreamer.EmitLabel(SectionBegin);
2257 // Emit the full data.
2258 AT.Emit(Asm, SectionBegin, &InfoHolder);
2261 // Emit objective C classes and categories into a hashed accelerator table
2263 void DwarfDebug::emitAccelObjC() {
2265 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2266 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2269 CompileUnit *TheCU = I->second;
2270 const StringMap<std::vector<const DIE *> > &Names = TheCU->getAccelObjC();
2271 for (StringMap<std::vector<const DIE *> >::const_iterator
2275 StringRef Name = GI->getKey();
2276 const std::vector<const DIE *> &Entities = GI->second;
2277 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2278 DE = Entities.end();
2280 AT.AddName(Name, *DI);
2284 AT.FinalizeTable(Asm, "ObjC");
2285 Asm->OutStreamer.SwitchSection(
2286 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2287 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2288 Asm->OutStreamer.EmitLabel(SectionBegin);
2290 // Emit the full data.
2291 AT.Emit(Asm, SectionBegin, &InfoHolder);
2294 // Emit namespace dies into a hashed accelerator table.
2295 void DwarfDebug::emitAccelNamespaces() {
2297 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2298 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2301 CompileUnit *TheCU = I->second;
2302 const StringMap<std::vector<const DIE *> > &Names =
2303 TheCU->getAccelNamespace();
2304 for (StringMap<std::vector<const DIE *> >::const_iterator
2308 StringRef Name = GI->getKey();
2309 const std::vector<const DIE *> &Entities = GI->second;
2310 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2311 DE = Entities.end();
2313 AT.AddName(Name, *DI);
2317 AT.FinalizeTable(Asm, "namespac");
2318 Asm->OutStreamer.SwitchSection(
2319 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2320 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2321 Asm->OutStreamer.EmitLabel(SectionBegin);
2323 // Emit the full data.
2324 AT.Emit(Asm, SectionBegin, &InfoHolder);
2327 // Emit type dies into a hashed accelerator table.
2328 void DwarfDebug::emitAccelTypes() {
2329 std::vector<DwarfAccelTable::Atom> Atoms;
2331 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2333 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2335 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2336 DwarfAccelTable AT(Atoms);
2337 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2340 CompileUnit *TheCU = I->second;
2341 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2342 TheCU->getAccelTypes();
2344 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2348 StringRef Name = GI->getKey();
2349 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2351 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2352 DI = Entities.begin(),
2353 DE = Entities.end();
2355 AT.AddName(Name, DI->first, DI->second);
2359 AT.FinalizeTable(Asm, "types");
2360 Asm->OutStreamer.SwitchSection(
2361 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2362 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2363 Asm->OutStreamer.EmitLabel(SectionBegin);
2365 // Emit the full data.
2366 AT.Emit(Asm, SectionBegin, &InfoHolder);
2369 // Public name handling.
2370 // The format for the various pubnames:
2372 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2373 // for the DIE that is named.
2375 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2376 // into the CU and the index value is computed according to the type of value
2377 // for the DIE that is named.
2379 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2380 // it's the offset within the debug_info/debug_types dwo section, however, the
2381 // reference in the pubname header doesn't change.
2383 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2384 static dwarf::PubIndexEntryDescriptor computeIndexValue(CompileUnit *CU,
2386 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2388 // We could have a specification DIE that has our most of our knowledge,
2389 // look for that now.
2390 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2392 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2393 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2394 Linkage = dwarf::GIEL_EXTERNAL;
2395 } else if (Die->findAttribute(dwarf::DW_AT_external))
2396 Linkage = dwarf::GIEL_EXTERNAL;
2398 switch (Die->getTag()) {
2399 case dwarf::DW_TAG_class_type:
2400 case dwarf::DW_TAG_structure_type:
2401 case dwarf::DW_TAG_union_type:
2402 case dwarf::DW_TAG_enumeration_type:
2403 return dwarf::PubIndexEntryDescriptor(
2404 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2405 ? dwarf::GIEL_STATIC
2406 : dwarf::GIEL_EXTERNAL);
2407 case dwarf::DW_TAG_typedef:
2408 case dwarf::DW_TAG_base_type:
2409 case dwarf::DW_TAG_subrange_type:
2410 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2411 case dwarf::DW_TAG_namespace:
2412 return dwarf::GIEK_TYPE;
2413 case dwarf::DW_TAG_subprogram:
2414 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2415 case dwarf::DW_TAG_constant:
2416 case dwarf::DW_TAG_variable:
2417 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2418 case dwarf::DW_TAG_enumerator:
2419 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2420 dwarf::GIEL_STATIC);
2422 return dwarf::GIEK_NONE;
2426 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2428 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2429 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2430 const MCSection *PSec =
2431 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2432 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2434 typedef DenseMap<const MDNode *, CompileUnit *> CUMapType;
2435 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2436 CompileUnit *TheCU = I->second;
2437 unsigned ID = TheCU->getUniqueID();
2439 // Start the dwarf pubnames section.
2440 Asm->OutStreamer.SwitchSection(PSec);
2442 // Emit a label so we can reference the beginning of this pubname section.
2444 Asm->OutStreamer.EmitLabel(
2445 Asm->GetTempSymbol("gnu_pubnames", TheCU->getUniqueID()));
2448 Asm->OutStreamer.AddComment("Length of Public Names Info");
2449 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2450 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2452 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2454 Asm->OutStreamer.AddComment("DWARF Version");
2455 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2457 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2458 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2459 DwarfInfoSectionSym);
2461 Asm->OutStreamer.AddComment("Compilation Unit Length");
2462 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2463 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2466 // Emit the pubnames for this compilation unit.
2467 const StringMap<const DIE *> &Globals = TheCU->getGlobalNames();
2468 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2471 const char *Name = GI->getKeyData();
2472 const DIE *Entity = GI->second;
2474 Asm->OutStreamer.AddComment("DIE offset");
2475 Asm->EmitInt32(Entity->getOffset());
2478 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2479 Asm->OutStreamer.AddComment(
2480 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2481 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2482 Asm->EmitInt8(Desc.toBits());
2485 if (Asm->isVerbose())
2486 Asm->OutStreamer.AddComment("External Name");
2487 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2490 Asm->OutStreamer.AddComment("End Mark");
2492 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2496 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2497 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2498 const MCSection *PSec =
2499 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2500 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2502 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2505 CompileUnit *TheCU = I->second;
2506 // Start the dwarf pubtypes section.
2507 Asm->OutStreamer.SwitchSection(PSec);
2509 // Emit a label so we can reference the beginning of this pubtype section.
2511 Asm->OutStreamer.EmitLabel(
2512 Asm->GetTempSymbol("gnu_pubtypes", TheCU->getUniqueID()));
2515 Asm->OutStreamer.AddComment("Length of Public Types Info");
2516 Asm->EmitLabelDifference(
2517 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2518 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2520 Asm->OutStreamer.EmitLabel(
2521 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()));
2523 if (Asm->isVerbose())
2524 Asm->OutStreamer.AddComment("DWARF Version");
2525 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2527 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2528 Asm->EmitSectionOffset(
2529 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()),
2530 DwarfInfoSectionSym);
2532 Asm->OutStreamer.AddComment("Compilation Unit Length");
2533 Asm->EmitLabelDifference(
2534 Asm->GetTempSymbol(ISec->getLabelEndName(), TheCU->getUniqueID()),
2535 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()), 4);
2537 // Emit the pubtypes.
2538 const StringMap<const DIE *> &Globals = TheCU->getGlobalTypes();
2539 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2542 const char *Name = GI->getKeyData();
2543 const DIE *Entity = GI->second;
2545 if (Asm->isVerbose())
2546 Asm->OutStreamer.AddComment("DIE offset");
2547 Asm->EmitInt32(Entity->getOffset());
2550 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2551 Asm->OutStreamer.AddComment(
2552 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2553 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2554 Asm->EmitInt8(Desc.toBits());
2557 if (Asm->isVerbose())
2558 Asm->OutStreamer.AddComment("External Name");
2560 // Emit the name with a terminating null byte.
2561 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2564 Asm->OutStreamer.AddComment("End Mark");
2566 Asm->OutStreamer.EmitLabel(
2567 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()));
2571 // Emit strings into a string section.
2572 void DwarfUnits::emitStrings(const MCSection *StrSection,
2573 const MCSection *OffsetSection = NULL,
2574 const MCSymbol *StrSecSym = NULL) {
2576 if (StringPool.empty())
2579 // Start the dwarf str section.
2580 Asm->OutStreamer.SwitchSection(StrSection);
2582 // Get all of the string pool entries and put them in an array by their ID so
2583 // we can sort them.
2585 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2588 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2589 I = StringPool.begin(),
2590 E = StringPool.end();
2592 Entries.push_back(std::make_pair(I->second.second, &*I));
2594 array_pod_sort(Entries.begin(), Entries.end());
2596 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2597 // Emit a label for reference from debug information entries.
2598 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2600 // Emit the string itself with a terminating null byte.
2601 Asm->OutStreamer.EmitBytes(
2602 StringRef(Entries[i].second->getKeyData(),
2603 Entries[i].second->getKeyLength() + 1));
2606 // If we've got an offset section go ahead and emit that now as well.
2607 if (OffsetSection) {
2608 Asm->OutStreamer.SwitchSection(OffsetSection);
2609 unsigned offset = 0;
2610 unsigned size = 4; // FIXME: DWARF64 is 8.
2611 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2612 Asm->OutStreamer.EmitIntValue(offset, size);
2613 offset += Entries[i].second->getKeyLength() + 1;
2619 // Emit addresses into the section given.
2620 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2622 if (AddressPool.empty())
2625 // Start the dwarf addr section.
2626 Asm->OutStreamer.SwitchSection(AddrSection);
2628 // Order the address pool entries by ID
2629 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2631 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2632 E = AddressPool.end();
2634 Entries[I->second] = I->first;
2636 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2637 // Emit an expression for reference from debug information entries.
2638 if (const MCExpr *Expr = Entries[i])
2639 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2641 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2645 // Emit visible names into a debug str section.
2646 void DwarfDebug::emitDebugStr() {
2647 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2648 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2651 // Emit locations into the debug loc section.
2652 void DwarfDebug::emitDebugLoc() {
2653 if (DotDebugLocEntries.empty())
2656 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2657 I = DotDebugLocEntries.begin(),
2658 E = DotDebugLocEntries.end();
2660 DotDebugLocEntry &Entry = *I;
2661 if (I + 1 != DotDebugLocEntries.end())
2665 // Start the dwarf loc section.
2666 Asm->OutStreamer.SwitchSection(
2667 Asm->getObjFileLowering().getDwarfLocSection());
2668 unsigned char Size = Asm->getDataLayout().getPointerSize();
2669 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2671 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2672 I = DotDebugLocEntries.begin(),
2673 E = DotDebugLocEntries.end();
2674 I != E; ++I, ++index) {
2675 DotDebugLocEntry &Entry = *I;
2676 if (Entry.isMerged())
2678 if (Entry.isEmpty()) {
2679 Asm->OutStreamer.EmitIntValue(0, Size);
2680 Asm->OutStreamer.EmitIntValue(0, Size);
2681 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2683 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2684 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2685 DIVariable DV(Entry.getVariable());
2686 Asm->OutStreamer.AddComment("Loc expr size");
2687 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2688 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2689 Asm->EmitLabelDifference(end, begin, 2);
2690 Asm->OutStreamer.EmitLabel(begin);
2691 if (Entry.isInt()) {
2692 DIBasicType BTy(DV.getType());
2693 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2694 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2695 Asm->OutStreamer.AddComment("DW_OP_consts");
2696 Asm->EmitInt8(dwarf::DW_OP_consts);
2697 Asm->EmitSLEB128(Entry.getInt());
2699 Asm->OutStreamer.AddComment("DW_OP_constu");
2700 Asm->EmitInt8(dwarf::DW_OP_constu);
2701 Asm->EmitULEB128(Entry.getInt());
2703 } else if (Entry.isLocation()) {
2704 MachineLocation Loc = Entry.getLoc();
2705 if (!DV.hasComplexAddress())
2707 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2709 // Complex address entry.
2710 unsigned N = DV.getNumAddrElements();
2712 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2713 if (Loc.getOffset()) {
2715 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2716 Asm->OutStreamer.AddComment("DW_OP_deref");
2717 Asm->EmitInt8(dwarf::DW_OP_deref);
2718 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2719 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2720 Asm->EmitSLEB128(DV.getAddrElement(1));
2722 // If first address element is OpPlus then emit
2723 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2724 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2725 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2729 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2732 // Emit remaining complex address elements.
2733 for (; i < N; ++i) {
2734 uint64_t Element = DV.getAddrElement(i);
2735 if (Element == DIBuilder::OpPlus) {
2736 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2737 Asm->EmitULEB128(DV.getAddrElement(++i));
2738 } else if (Element == DIBuilder::OpDeref) {
2740 Asm->EmitInt8(dwarf::DW_OP_deref);
2742 llvm_unreachable("unknown Opcode found in complex address");
2746 // else ... ignore constant fp. There is not any good way to
2747 // to represent them here in dwarf.
2748 Asm->OutStreamer.EmitLabel(end);
2753 struct SymbolCUSorter {
2754 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2755 const MCStreamer &Streamer;
2757 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2758 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2759 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2761 // Symbols with no order assigned should be placed at the end.
2762 // (e.g. section end labels)
2764 IA = (unsigned)(-1);
2766 IB = (unsigned)(-1);
2771 static bool CUSort(const CompileUnit *A, const CompileUnit *B) {
2772 return (A->getUniqueID() < B->getUniqueID());
2776 const MCSymbol *Start, *End;
2779 // Emit a debug aranges section, containing a CU lookup for any
2780 // address we can tie back to a CU.
2781 void DwarfDebug::emitDebugARanges() {
2782 // Start the dwarf aranges section.
2783 Asm->OutStreamer.SwitchSection(
2784 Asm->getObjFileLowering().getDwarfARangesSection());
2786 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2790 // Build a list of sections used.
2791 std::vector<const MCSection *> Sections;
2792 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2794 const MCSection *Section = it->first;
2795 Sections.push_back(Section);
2798 // Sort the sections into order.
2799 // This is only done to ensure consistent output order across different runs.
2800 std::sort(Sections.begin(), Sections.end(), SectionSort);
2802 // Build a set of address spans, sorted by CU.
2803 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2804 const MCSection *Section = Sections[SecIdx];
2805 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2806 if (List.size() < 2)
2809 // Sort the symbols by offset within the section.
2810 SymbolCUSorter sorter(Asm->OutStreamer);
2811 std::sort(List.begin(), List.end(), sorter);
2813 // If we have no section (e.g. common), just write out
2814 // individual spans for each symbol.
2815 if (Section == NULL) {
2816 for (size_t n = 0; n < List.size(); n++) {
2817 const SymbolCU &Cur = List[n];
2820 Span.Start = Cur.Sym;
2823 Spans[Cur.CU].push_back(Span);
2826 // Build spans between each label.
2827 const MCSymbol *StartSym = List[0].Sym;
2828 for (size_t n = 1; n < List.size(); n++) {
2829 const SymbolCU &Prev = List[n - 1];
2830 const SymbolCU &Cur = List[n];
2832 // Try and build the longest span we can within the same CU.
2833 if (Cur.CU != Prev.CU) {
2835 Span.Start = StartSym;
2837 Spans[Prev.CU].push_back(Span);
2844 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2845 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2847 // Build a list of CUs used.
2848 std::vector<CompileUnit *> CUs;
2849 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2850 CompileUnit *CU = it->first;
2854 // Sort the CU list (again, to ensure consistent output order).
2855 std::sort(CUs.begin(), CUs.end(), CUSort);
2857 // Emit an arange table for each CU we used.
2858 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2859 CompileUnit *CU = CUs[CUIdx];
2860 std::vector<ArangeSpan> &List = Spans[CU];
2862 // Emit size of content not including length itself.
2863 unsigned ContentSize =
2864 sizeof(int16_t) + // DWARF ARange version number
2865 sizeof(int32_t) + // Offset of CU in the .debug_info section
2866 sizeof(int8_t) + // Pointer Size (in bytes)
2867 sizeof(int8_t); // Segment Size (in bytes)
2869 unsigned TupleSize = PtrSize * 2;
2871 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2872 unsigned Padding = 0;
2873 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2876 ContentSize += Padding;
2877 ContentSize += (List.size() + 1) * TupleSize;
2879 // For each compile unit, write the list of spans it covers.
2880 Asm->OutStreamer.AddComment("Length of ARange Set");
2881 Asm->EmitInt32(ContentSize);
2882 Asm->OutStreamer.AddComment("DWARF Arange version number");
2883 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2884 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2885 Asm->EmitSectionOffset(
2886 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2887 DwarfInfoSectionSym);
2888 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2889 Asm->EmitInt8(PtrSize);
2890 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2893 for (unsigned n = 0; n < Padding; n++)
2894 Asm->EmitInt8(0xff);
2896 for (unsigned n = 0; n < List.size(); n++) {
2897 const ArangeSpan &Span = List[n];
2898 Asm->EmitLabelReference(Span.Start, PtrSize);
2900 // Calculate the size as being from the span start to it's end.
2902 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2904 // For symbols without an end marker (e.g. common), we
2905 // write a single arange entry containing just that one symbol.
2906 uint64_t Size = SymSize[Span.Start];
2910 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2914 Asm->OutStreamer.AddComment("ARange terminator");
2915 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2916 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2920 // Emit visible names into a debug ranges section.
2921 void DwarfDebug::emitDebugRanges() {
2922 // Start the dwarf ranges section.
2923 Asm->OutStreamer.SwitchSection(
2924 Asm->getObjFileLowering().getDwarfRangesSection());
2925 unsigned char Size = Asm->getDataLayout().getPointerSize();
2926 for (uint32_t i = 0, e = DebugRangeSymbols.size(); i < e; ++i) {
2927 // Only emit a symbol for every range pair for now.
2928 // FIXME: Make this per range list.
2930 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_ranges", i));
2932 const MCSymbol *I = DebugRangeSymbols[i];
2934 Asm->OutStreamer.EmitSymbolValue(I, Size);
2936 Asm->OutStreamer.EmitIntValue(0, Size);
2940 // Emit visible names into a debug macinfo section.
2941 void DwarfDebug::emitDebugMacInfo() {
2942 if (const MCSection *LineInfo =
2943 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2944 // Start the dwarf macinfo section.
2945 Asm->OutStreamer.SwitchSection(LineInfo);
2949 // DWARF5 Experimental Separate Dwarf emitters.
2951 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2952 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2953 // DW_AT_ranges_base, DW_AT_addr_base.
2954 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2956 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2957 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2958 Asm, this, &SkeletonHolder);
2960 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2961 CU->getNode().getSplitDebugFilename());
2963 // Relocate to the beginning of the addr_base section, else 0 for the
2964 // beginning of the one for this compile unit.
2965 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2966 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2967 DwarfAddrSectionSym);
2969 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2971 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2972 // into an entity. We're using 0, or a NULL label for this.
2973 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2975 // DW_AT_stmt_list is a offset of line number information for this
2976 // compile unit in debug_line section.
2977 // FIXME: Should handle multiple compile units.
2978 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2979 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
2980 DwarfLineSectionSym);
2982 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2984 if (!CompilationDir.empty())
2985 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2987 // Flags to let the linker know we have emitted new style pubnames.
2988 if (GenerateGnuPubSections) {
2989 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2990 NewCU->addSectionLabel(
2991 Die, dwarf::DW_AT_GNU_pubnames,
2992 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
2994 NewCU->addSectionDelta(
2995 Die, dwarf::DW_AT_GNU_pubnames,
2996 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
2997 DwarfGnuPubNamesSectionSym);
2999 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3000 NewCU->addSectionLabel(
3001 Die, dwarf::DW_AT_GNU_pubtypes,
3002 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3004 NewCU->addSectionDelta(
3005 Die, dwarf::DW_AT_GNU_pubtypes,
3006 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3007 DwarfGnuPubTypesSectionSym);
3010 // Flag if we've emitted any ranges and their location for the compile unit.
3011 if (DebugRangeSymbols.size()) {
3012 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3013 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_ranges_base,
3014 DwarfDebugRangeSectionSym);
3016 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
3020 SkeletonHolder.addUnit(NewCU);
3025 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3026 assert(useSplitDwarf() && "No split dwarf debug info?");
3027 emitAbbrevs(Section, &SkeletonAbbrevs);
3030 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3031 // compile units that would normally be in debug_info.
3032 void DwarfDebug::emitDebugInfoDWO() {
3033 assert(useSplitDwarf() && "No split dwarf debug info?");
3034 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3035 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3036 DwarfAbbrevDWOSectionSym);
3039 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3040 // abbreviations for the .debug_info.dwo section.
3041 void DwarfDebug::emitDebugAbbrevDWO() {
3042 assert(useSplitDwarf() && "No split dwarf?");
3043 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3047 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3048 // string section and is identical in format to traditional .debug_str
3050 void DwarfDebug::emitDebugStrDWO() {
3051 assert(useSplitDwarf() && "No split dwarf?");
3052 const MCSection *OffSec =
3053 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3054 const MCSymbol *StrSym = DwarfStrSectionSym;
3055 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3059 void DwarfDebug::addTypeUnitType(DIE *RefDie, DICompositeType CTy) {
3060 DenseMap<const MDNode*, std::pair<uint64_t, SmallVectorImpl<DIE*>* > >::iterator I = TypeUnits.find(CTy);
3061 SmallVector<DIE *, 8> References;
3062 References.push_back(RefDie);
3063 if (I != TypeUnits.end()) {
3064 if (I->second.second) {
3065 I->second.second->push_back(RefDie);
3069 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3070 CompileUnit *NewCU =
3071 new CompileUnit(GlobalCUIndexCount++, UnitDie,
3072 dwarf::DW_LANG_C_plus_plus, Asm, this, &InfoHolder);
3073 CUDieMap.insert(std::make_pair(UnitDie, NewCU));
3074 NewCU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3075 dwarf::DW_LANG_C_plus_plus);
3077 // Register the type in the TypeUnits map with a vector of references to be
3078 // populated whenever a reference is required.
3079 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3082 // Construct the type, this may, recursively, require more type units that
3083 // may in turn require this type again - in which case they will add DIEs to
3084 // the References vector.
3085 DIE *Die = NewCU->createTypeDIE(CTy);
3087 if (GenerateODRHash && shouldAddODRHash(NewCU, Die))
3088 NewCU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3089 dwarf::DW_FORM_data8,
3090 DIEHash().computeDIEODRSignature(*Die));
3091 // FIXME: This won't handle circularly referential structures, as the DIE
3092 // may have references to other DIEs still under construction and missing
3093 // their signature. Hashing should walk through the signatures to their
3094 // referenced type, or possibly walk the precomputed hashes of related types
3096 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3098 // Remove the References vector and add the type hash.
3099 I->second.first = Signature;
3100 I->second.second = NULL;
3103 InfoHolder.addUnit(NewCU);
3106 // Populate all the signatures.
3107 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3108 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3109 dwarf::DW_FORM_ref_sig8, I->second.first);