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."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
72 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
73 cl::desc("Generate GNU-style pubnames and pubtypes"),
84 static cl::opt<DefaultOnOff>
85 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
86 cl::desc("Output prototype dwarf accelerator tables."),
87 cl::values(clEnumVal(Default, "Default for platform"),
88 clEnumVal(Enable, "Enabled"),
89 clEnumVal(Disable, "Disabled"), clEnumValEnd),
92 static cl::opt<DefaultOnOff>
93 SplitDwarf("split-dwarf", cl::Hidden,
94 cl::desc("Output prototype dwarf split debug info."),
95 cl::values(clEnumVal(Default, "Default for platform"),
96 clEnumVal(Enable, "Enabled"),
97 clEnumVal(Disable, "Disabled"), clEnumValEnd),
100 static cl::opt<DefaultOnOff>
101 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
102 cl::desc("Generate DWARF pubnames and pubtypes sections"),
103 cl::values(clEnumVal(Default, "Default for platform"),
104 clEnumVal(Enable, "Enabled"),
105 clEnumVal(Disable, "Disabled"), clEnumValEnd),
108 static cl::opt<unsigned>
109 DwarfVersionNumber("dwarf-version", cl::Hidden,
110 cl::desc("Generate DWARF for dwarf version."),
113 static const char *const DWARFGroupName = "DWARF Emission";
114 static const char *const DbgTimerName = "DWARF Debug Writer";
116 //===----------------------------------------------------------------------===//
118 // Configuration values for initial hash set sizes (log2).
120 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
124 /// resolve - Look in the DwarfDebug map for the MDNode that
125 /// corresponds to the reference.
126 template <typename T>
127 T DbgVariable::resolve(DIRef<T> Ref) const {
128 return DD->resolve(Ref);
131 DIType DbgVariable::getType() const {
132 DIType Ty = Var.getType();
133 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
134 // addresses instead.
135 if (Var.isBlockByrefVariable()) {
136 /* Byref variables, in Blocks, are declared by the programmer as
137 "SomeType VarName;", but the compiler creates a
138 __Block_byref_x_VarName struct, and gives the variable VarName
139 either the struct, or a pointer to the struct, as its type. This
140 is necessary for various behind-the-scenes things the compiler
141 needs to do with by-reference variables in blocks.
143 However, as far as the original *programmer* is concerned, the
144 variable should still have type 'SomeType', as originally declared.
146 The following function dives into the __Block_byref_x_VarName
147 struct to find the original type of the variable. This will be
148 passed back to the code generating the type for the Debug
149 Information Entry for the variable 'VarName'. 'VarName' will then
150 have the original type 'SomeType' in its debug information.
152 The original type 'SomeType' will be the type of the field named
153 'VarName' inside the __Block_byref_x_VarName struct.
155 NOTE: In order for this to not completely fail on the debugger
156 side, the Debug Information Entry for the variable VarName needs to
157 have a DW_AT_location that tells the debugger how to unwind through
158 the pointers and __Block_byref_x_VarName struct to find the actual
159 value of the variable. The function addBlockByrefType does this. */
161 uint16_t tag = Ty.getTag();
163 if (tag == dwarf::DW_TAG_pointer_type)
164 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
166 DIArray Elements = DICompositeType(subType).getTypeArray();
167 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
168 DIDerivedType DT(Elements.getElement(i));
169 if (getName() == DT.getName())
170 return (resolve(DT.getTypeDerivedFrom()));
176 } // end llvm namespace
178 /// Return Dwarf Version by checking module flags.
179 static unsigned getDwarfVersionFromModule(const Module *M) {
180 Value *Val = M->getModuleFlag("Dwarf Version");
182 return dwarf::DWARF_VERSION;
183 return cast<ConstantInt>(Val)->getZExtValue();
186 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
187 : Asm(A), MMI(Asm->MMI), FirstCU(0),
188 AbbreviationsSet(InitAbbreviationsSetSize),
189 SourceIdMap(DIEValueAllocator),
190 PrevLabel(NULL), GlobalCUIndexCount(0),
191 InfoHolder(A, &AbbreviationsSet, Abbreviations, "info_string",
193 SkeletonAbbrevSet(InitAbbreviationsSetSize),
194 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
197 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
198 DwarfStrSectionSym = TextSectionSym = 0;
199 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
200 DwarfAddrSectionSym = 0;
201 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
202 FunctionBeginSym = FunctionEndSym = 0;
204 // Turn on accelerator tables for Darwin by default, pubnames by
205 // default for non-Darwin, and handle split dwarf.
206 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
208 if (DwarfAccelTables == Default)
209 HasDwarfAccelTables = IsDarwin;
211 HasDwarfAccelTables = DwarfAccelTables == Enable;
213 if (SplitDwarf == Default)
214 HasSplitDwarf = false;
216 HasSplitDwarf = SplitDwarf == Enable;
218 if (DwarfPubSections == Default)
219 HasDwarfPubSections = !IsDarwin;
221 HasDwarfPubSections = DwarfPubSections == Enable;
223 DwarfVersion = DwarfVersionNumber
225 : getDwarfVersionFromModule(MMI->getModule());
228 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
233 // Switch to the specified MCSection and emit an assembler
234 // temporary label to it if SymbolStem is specified.
235 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
236 const char *SymbolStem = 0) {
237 Asm->OutStreamer.SwitchSection(Section);
238 if (!SymbolStem) return 0;
240 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
241 Asm->OutStreamer.EmitLabel(TmpSym);
245 MCSymbol *DwarfUnits::getStringPoolSym() {
246 return Asm->GetTempSymbol(StringPref);
249 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
250 std::pair<MCSymbol*, unsigned> &Entry =
251 StringPool.GetOrCreateValue(Str).getValue();
252 if (Entry.first) return Entry.first;
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol*, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
261 if (Entry.first) return Entry.second;
263 Entry.second = NextStringPoolNumber++;
264 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
269 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
272 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
273 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
274 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
276 ++NextAddrPoolNumber;
277 return P.first->second;
280 // Define a unique number for the abbreviation.
282 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
283 // Check the set for priors.
284 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
286 // If it's newly added.
287 if (InSet == &Abbrev) {
288 // Add to abbreviation list.
289 Abbreviations.push_back(&Abbrev);
291 // Assign the vector position + 1 as its number.
292 Abbrev.setNumber(Abbreviations.size());
294 // Assign existing abbreviation number.
295 Abbrev.setNumber(InSet->getNumber());
299 static bool isObjCClass(StringRef Name) {
300 return Name.startswith("+") || Name.startswith("-");
303 static bool hasObjCCategory(StringRef Name) {
304 if (!isObjCClass(Name)) return false;
306 return Name.find(") ") != StringRef::npos;
309 static void getObjCClassCategory(StringRef In, StringRef &Class,
310 StringRef &Category) {
311 if (!hasObjCCategory(In)) {
312 Class = In.slice(In.find('[') + 1, In.find(' '));
317 Class = In.slice(In.find('[') + 1, In.find('('));
318 Category = In.slice(In.find('[') + 1, In.find(' '));
322 static StringRef getObjCMethodName(StringRef In) {
323 return In.slice(In.find(' ') + 1, In.find(']'));
326 // Helper for sorting sections into a stable output order.
327 static bool SectionSort(const MCSection *A, const MCSection *B) {
328 std::string LA = (A ? A->getLabelBeginName() : "");
329 std::string LB = (B ? B->getLabelBeginName() : "");
333 // Add the various names to the Dwarf accelerator table names.
334 // TODO: Determine whether or not we should add names for programs
335 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
336 // is only slightly different than the lookup of non-standard ObjC names.
337 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
339 if (!SP.isDefinition()) return;
340 TheCU->addAccelName(SP.getName(), Die);
342 // If the linkage name is different than the name, go ahead and output
343 // that as well into the name table.
344 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
345 TheCU->addAccelName(SP.getLinkageName(), Die);
347 // If this is an Objective-C selector name add it to the ObjC accelerator
349 if (isObjCClass(SP.getName())) {
350 StringRef Class, Category;
351 getObjCClassCategory(SP.getName(), Class, Category);
352 TheCU->addAccelObjC(Class, Die);
354 TheCU->addAccelObjC(Category, Die);
355 // Also add the base method name to the name table.
356 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
360 /// isSubprogramContext - Return true if Context is either a subprogram
361 /// or another context nested inside a subprogram.
362 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
365 DIDescriptor D(Context);
366 if (D.isSubprogram())
369 return isSubprogramContext(resolve(DIType(Context).getContext()));
373 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
374 // and DW_AT_high_pc attributes. If there are global variables in this
375 // scope then create and insert DIEs for these variables.
376 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
377 DIE *SPDie = SPCU->getDIE(SP);
379 assert(SPDie && "Unable to find subprogram DIE!");
381 // If we're updating an abstract DIE, then we will be adding the children and
382 // object pointer later on. But what we don't want to do is process the
383 // concrete DIE twice.
384 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
385 // Pick up abstract subprogram DIE.
386 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
387 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
389 DISubprogram SPDecl = SP.getFunctionDeclaration();
390 if (!SPDecl.isSubprogram()) {
391 // There is not any need to generate specification DIE for a function
392 // defined at compile unit level. If a function is defined inside another
393 // function then gdb prefers the definition at top level and but does not
394 // expect specification DIE in parent function. So avoid creating
395 // specification DIE for a function defined inside a function.
396 DIScope SPContext = resolve(SP.getContext());
397 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398 !SPContext.isFile() &&
399 !isSubprogramContext(SPContext)) {
400 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 DICompositeType SPTy = SP.getType();
404 DIArray Args = SPTy.getTypeArray();
405 uint16_t SPTag = SPTy.getTag();
406 if (SPTag == dwarf::DW_TAG_subroutine_type)
407 // FIXME: Use DwarfUnit::constructSubprogramArguments() here.
408 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 DIType ATy(Args.getElement(i));
410 if (ATy.isUnspecifiedParameter()) {
411 assert(i == N-1 && "ellipsis must be the last argument");
412 SPCU->createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, *SPDie);
415 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
416 SPCU->addType(Arg, ATy);
417 if (ATy.isArtificial())
418 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
419 if (ATy.isObjectPointer())
420 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(SPDie, dwarf::DW_AT_low_pc,
432 Asm->GetTempSymbol("func_begin",
433 Asm->getFunctionNumber()));
434 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
435 Asm->GetTempSymbol("func_end",
436 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 uint, size 4, for now. emitDIE will handle
485 // DW_AT_ranges appropriately.
486 TheCU->addSectionOffset(ScopeDIE, dwarf::DW_AT_ranges,
487 DebugRangeSymbols.size() *
488 Asm->getDataLayout().getPointerSize());
489 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
490 RE = Ranges.end(); RI != RE; ++RI) {
491 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
492 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
495 // Terminate the range list.
496 DebugRangeSymbols.push_back(NULL);
497 DebugRangeSymbols.push_back(NULL);
501 // Construct the address range for this DIE.
502 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
503 MCSymbol *Start = getLabelBeforeInsn(RI->first);
504 MCSymbol *End = getLabelAfterInsn(RI->second);
505 assert(End && "End label should not be null!");
507 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
508 assert(End->isDefined() && "Invalid end label for an inlined scope!");
510 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
511 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
516 // This scope represents inlined body of a function. Construct DIE to
517 // represent this concrete inlined copy of the function.
518 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
519 LexicalScope *Scope) {
520 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
521 assert(Ranges.empty() == false &&
522 "LexicalScope does not have instruction markers!");
524 if (!Scope->getScopeNode())
526 DIScope DS(Scope->getScopeNode());
527 DISubprogram InlinedSP = getDISubprogram(DS);
528 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
530 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
534 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
535 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
537 if (Ranges.size() > 1) {
538 // .debug_range section has not been laid out yet. Emit offset in
539 // .debug_range as a uint, size 4, for now. emitDIE will handle
540 // DW_AT_ranges appropriately.
541 TheCU->addSectionOffset(ScopeDIE, dwarf::DW_AT_ranges,
542 DebugRangeSymbols.size() *
543 Asm->getDataLayout().getPointerSize());
544 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
545 RE = Ranges.end(); RI != RE; ++RI) {
546 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
547 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
549 DebugRangeSymbols.push_back(NULL);
550 DebugRangeSymbols.push_back(NULL);
552 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
553 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
554 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
556 if (StartLabel == 0 || EndLabel == 0)
557 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
559 assert(StartLabel->isDefined() &&
560 "Invalid starting label for an inlined scope!");
561 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
563 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
564 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
567 InlinedSubprogramDIEs.insert(OriginDIE);
569 // Add the call site information to the DIE.
570 DILocation DL(Scope->getInlinedAt());
571 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
572 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
573 TheCU->getUniqueID()));
574 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
576 // Add name to the name table, we do this here because we're guaranteed
577 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
578 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
583 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
584 SmallVectorImpl<DIE*> &Children) {
585 DIE *ObjectPointer = NULL;
587 // Collect arguments for current function.
588 if (LScopes.isCurrentFunctionScope(Scope)) {
589 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
590 if (DbgVariable *ArgDV = CurrentFnArguments[i])
592 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
593 Children.push_back(Arg);
594 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
597 // Create the unspecified parameter that marks a function as variadic.
598 DISubprogram SP(Scope->getScopeNode());
600 DIArray FnArgs = SP.getType().getTypeArray();
601 if (FnArgs.getElement(FnArgs.getNumElements()-1).isUnspecifiedParameter()) {
602 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
603 Children.push_back(Ellipsis);
607 // Collect lexical scope children first.
608 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
609 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
611 TheCU->constructVariableDIE(*Variables[i], Scope->isAbstractScope())) {
612 Children.push_back(Variable);
613 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
615 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
616 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
617 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
618 Children.push_back(Nested);
619 return ObjectPointer;
622 // Construct a DIE for this scope.
623 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
624 if (!Scope || !Scope->getScopeNode())
627 DIScope DS(Scope->getScopeNode());
629 SmallVector<DIE *, 8> Children;
630 DIE *ObjectPointer = NULL;
631 bool ChildrenCreated = false;
633 // We try to create the scope DIE first, then the children DIEs. This will
634 // avoid creating un-used children then removing them later when we find out
635 // the scope DIE is null.
636 DIE *ScopeDIE = NULL;
637 if (Scope->getInlinedAt())
638 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
639 else if (DS.isSubprogram()) {
640 ProcessedSPNodes.insert(DS);
641 if (Scope->isAbstractScope()) {
642 ScopeDIE = TheCU->getDIE(DS);
643 // Note down abstract DIE.
645 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
647 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
649 // Early exit when we know the scope DIE is going to be null.
650 if (isLexicalScopeDIENull(Scope))
653 // We create children here when we know the scope DIE is not going to be
654 // null and the children will be added to the scope DIE.
655 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
656 ChildrenCreated = true;
658 // There is no need to emit empty lexical block DIE.
659 std::pair<ImportedEntityMap::const_iterator,
660 ImportedEntityMap::const_iterator> Range = std::equal_range(
661 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
662 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
664 if (Children.empty() && Range.first == Range.second)
666 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
667 assert(ScopeDIE && "Scope DIE should not be null.");
668 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
670 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
674 assert(Children.empty() &&
675 "We create children only when the scope DIE is not null.");
678 if (!ChildrenCreated)
679 // We create children when the scope DIE is not null.
680 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
683 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
684 E = Children.end(); I != E; ++I)
685 ScopeDIE->addChild(*I);
687 if (DS.isSubprogram() && ObjectPointer != NULL)
688 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
690 if (DS.isSubprogram())
691 TheCU->addPubTypes(DISubprogram(DS));
696 // Look up the source id with the given directory and source file names.
697 // If none currently exists, create a new id and insert it in the
698 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
700 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
701 StringRef DirName, unsigned CUID) {
702 // If we use .loc in assembly, we can't separate .file entries according to
703 // compile units. Thus all files will belong to the default compile unit.
705 // FIXME: add a better feature test than hasRawTextSupport. Even better,
706 // extend .file to support this.
707 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
710 // If FE did not provide a file name, then assume stdin.
711 if (FileName.empty())
712 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
714 // TODO: this might not belong here. See if we can factor this better.
715 if (DirName == CompilationDir)
718 // FileIDCUMap stores the current ID for the given compile unit.
719 unsigned SrcId = FileIDCUMap[CUID] + 1;
721 // We look up the CUID/file/dir by concatenating them with a zero byte.
722 SmallString<128> NamePair;
723 NamePair += utostr(CUID);
726 NamePair += '\0'; // Zero bytes are not allowed in paths.
727 NamePair += FileName;
729 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
730 if (Ent.getValue() != SrcId)
731 return Ent.getValue();
733 FileIDCUMap[CUID] = SrcId;
734 // Print out a .file directive to specify files for .loc directives.
735 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
740 // Create new CompileUnit for the given metadata node with tag
741 // DW_TAG_compile_unit.
742 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
743 StringRef FN = DIUnit.getFilename();
744 CompilationDir = DIUnit.getDirectory();
746 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
747 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
750 FileIDCUMap[NewCU->getUniqueID()] = 0;
751 // Call this to emit a .file directive if it wasn't emitted for the source
752 // file this CU comes from yet.
753 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
755 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
756 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
757 DIUnit.getLanguage());
758 NewCU->addString(Die, dwarf::DW_AT_name, FN);
760 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
761 // into an entity. We're using 0 (or a NULL label) for this. For
762 // split dwarf it's in the skeleton CU so omit it here.
763 if (!useSplitDwarf())
764 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
766 // Define start line table label for each Compile Unit.
767 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
768 NewCU->getUniqueID());
769 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
770 NewCU->getUniqueID());
772 // Use a single line table if we are using .loc and generating assembly.
774 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
775 (NewCU->getUniqueID() == 0);
777 if (!useSplitDwarf()) {
778 // DW_AT_stmt_list is a offset of line number information for this
779 // compile unit in debug_line section. For split dwarf this is
780 // left in the skeleton CU and so not included.
781 // The line table entries are not always emitted in assembly, so it
782 // is not okay to use line_table_start here.
783 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
784 NewCU->addSectionLabel(
785 Die, dwarf::DW_AT_stmt_list,
786 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
787 : LineTableStartSym);
788 else if (UseTheFirstCU)
789 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
791 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
792 LineTableStartSym, DwarfLineSectionSym);
794 // If we're using split dwarf the compilation dir is going to be in the
795 // skeleton CU and so we don't need to duplicate it here.
796 if (!CompilationDir.empty())
797 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
799 // Flags to let the linker know we have emitted new style pubnames. Only
800 // emit it here if we don't have a skeleton CU for split dwarf.
801 if (GenerateGnuPubSections) {
802 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
803 NewCU->addSectionLabel(
804 Die, dwarf::DW_AT_GNU_pubnames,
805 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
807 NewCU->addSectionDelta(
808 Die, dwarf::DW_AT_GNU_pubnames,
809 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
810 DwarfGnuPubNamesSectionSym);
812 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
813 NewCU->addSectionLabel(
814 Die, dwarf::DW_AT_GNU_pubtypes,
815 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
817 NewCU->addSectionDelta(
818 Die, dwarf::DW_AT_GNU_pubtypes,
819 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
820 DwarfGnuPubTypesSectionSym);
824 if (DIUnit.isOptimized())
825 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
827 StringRef Flags = DIUnit.getFlags();
829 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
831 if (unsigned RVer = DIUnit.getRunTimeVersion())
832 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
833 dwarf::DW_FORM_data1, RVer);
838 InfoHolder.addUnit(NewCU);
840 CUMap.insert(std::make_pair(DIUnit, NewCU));
841 CUDieMap.insert(std::make_pair(Die, NewCU));
845 // Construct subprogram DIE.
846 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
847 // FIXME: We should only call this routine once, however, during LTO if a
848 // program is defined in multiple CUs we could end up calling it out of
849 // beginModule as we walk the CUs.
851 CompileUnit *&CURef = SPMap[N];
857 if (!SP.isDefinition())
858 // This is a method declaration which will be handled while constructing
862 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
864 // Expose as a global name.
865 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
868 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
870 DIImportedEntity Module(N);
871 if (!Module.Verify())
873 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
874 constructImportedEntityDIE(TheCU, Module, D);
877 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
879 DIImportedEntity Module(N);
880 if (!Module.Verify())
882 return constructImportedEntityDIE(TheCU, Module, Context);
885 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
886 const DIImportedEntity &Module,
888 assert(Module.Verify() &&
889 "Use one of the MDNode * overloads to handle invalid metadata");
890 assert(Context && "Should always have a context for an imported_module");
891 DIE *IMDie = new DIE(Module.getTag());
892 TheCU->insertDIE(Module, IMDie);
894 DIDescriptor Entity = Module.getEntity();
895 if (Entity.isNameSpace())
896 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
897 else if (Entity.isSubprogram())
898 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
899 else if (Entity.isType())
900 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
902 EntityDie = TheCU->getDIE(Entity);
903 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
904 Module.getContext().getDirectory(),
905 TheCU->getUniqueID());
906 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
907 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
908 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
909 StringRef Name = Module.getName();
911 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
912 Context->addChild(IMDie);
915 // Emit all Dwarf sections that should come prior to the content. Create
916 // global DIEs and emit initial debug info sections. This is invoked by
917 // the target AsmPrinter.
918 void DwarfDebug::beginModule() {
919 if (DisableDebugInfoPrinting)
922 const Module *M = MMI->getModule();
924 // If module has named metadata anchors then use them, otherwise scan the
925 // module using debug info finder to collect debug info.
926 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
929 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
931 // Emit initial sections so we can reference labels later.
934 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
935 DICompileUnit CUNode(CU_Nodes->getOperand(i));
936 CompileUnit *CU = constructCompileUnit(CUNode);
937 DIArray ImportedEntities = CUNode.getImportedEntities();
938 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
939 ScopesWithImportedEntities.push_back(std::make_pair(
940 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
941 ImportedEntities.getElement(i)));
942 std::sort(ScopesWithImportedEntities.begin(),
943 ScopesWithImportedEntities.end(), less_first());
944 DIArray GVs = CUNode.getGlobalVariables();
945 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
946 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
947 DIArray SPs = CUNode.getSubprograms();
948 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
949 constructSubprogramDIE(CU, SPs.getElement(i));
950 DIArray EnumTypes = CUNode.getEnumTypes();
951 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
952 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
953 DIArray RetainedTypes = CUNode.getRetainedTypes();
954 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
955 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
956 // Emit imported_modules last so that the relevant context is already
958 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
959 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
962 // Tell MMI that we have debug info.
963 MMI->setDebugInfoAvailability(true);
965 // Prime section data.
966 SectionMap[Asm->getObjFileLowering().getTextSection()];
969 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
970 void DwarfDebug::computeInlinedDIEs() {
971 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
972 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
973 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
975 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
977 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
978 AE = AbstractSPDies.end(); AI != AE; ++AI) {
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 =
1019 SPCU->constructVariableDIE(NewVar, false))
1020 SPDIE->addChild(VariableDIE);
1027 // Type Signature [7.27] and ODR Hash code.
1029 /// \brief Grabs the string in whichever attribute is passed in and returns
1030 /// a reference to it. Returns "" if the attribute doesn't exist.
1031 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1032 DIEValue *V = Die->findAttribute(Attr);
1034 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1035 return S->getString();
1037 return StringRef("");
1040 /// Return true if the current DIE is contained within an anonymous namespace.
1041 static bool isContainedInAnonNamespace(DIE *Die) {
1042 DIE *Parent = Die->getParent();
1045 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1046 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1048 Parent = Parent->getParent();
1054 /// Test if the current CU language is C++ and that we have
1055 /// a named type that is not contained in an anonymous namespace.
1056 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1057 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1058 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1059 !isContainedInAnonNamespace(Die);
1062 void DwarfDebug::finalizeModuleInfo() {
1063 // Collect info for variables that were optimized out.
1064 collectDeadVariables();
1066 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1067 computeInlinedDIEs();
1069 // Split out type units and conditionally add an ODR tag to the split
1071 // FIXME: Do type splitting.
1072 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1073 DIE *Die = TypeUnits[i];
1075 // If we've requested ODR hashes and it's applicable for an ODR hash then
1076 // add the ODR signature now.
1077 // FIXME: This should be added onto the type unit, not the type, but this
1078 // works as an intermediate stage.
1079 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1080 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1081 dwarf::DW_FORM_data8,
1082 Hash.computeDIEODRSignature(*Die));
1085 // Handle anything that needs to be done on a per-cu basis.
1086 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1088 CUI != CUE; ++CUI) {
1089 CompileUnit *TheCU = CUI->second;
1090 // Emit DW_AT_containing_type attribute to connect types with their
1091 // vtable holding type.
1092 TheCU->constructContainingTypeDIEs();
1094 // If we're splitting the dwarf out now that we've got the entire
1095 // CU then construct a skeleton CU based upon it.
1096 if (useSplitDwarf()) {
1098 if (GenerateCUHash) {
1100 ID = CUHash.computeCUSignature(*TheCU->getCUDie());
1102 // This should be a unique identifier when we want to build .dwp files.
1103 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1104 dwarf::DW_FORM_data8, ID);
1105 // Now construct the skeleton CU associated.
1106 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1107 // This should be a unique identifier when we want to build .dwp files.
1108 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1109 dwarf::DW_FORM_data8, ID);
1113 // Compute DIE offsets and sizes.
1114 InfoHolder.computeSizeAndOffsets();
1115 if (useSplitDwarf())
1116 SkeletonHolder.computeSizeAndOffsets();
1119 void DwarfDebug::endSections() {
1120 // Filter labels by section.
1121 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1122 const SymbolCU &SCU = ArangeLabels[n];
1123 if (SCU.Sym->isInSection()) {
1124 // Make a note of this symbol and it's section.
1125 const MCSection *Section = &SCU.Sym->getSection();
1126 if (!Section->getKind().isMetadata())
1127 SectionMap[Section].push_back(SCU);
1129 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1130 // appear in the output. This sucks as we rely on sections to build
1131 // arange spans. We can do it without, but it's icky.
1132 SectionMap[NULL].push_back(SCU);
1136 // Build a list of sections used.
1137 std::vector<const MCSection *> Sections;
1138 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1140 const MCSection *Section = it->first;
1141 Sections.push_back(Section);
1144 // Sort the sections into order.
1145 // This is only done to ensure consistent output order across different runs.
1146 std::sort(Sections.begin(), Sections.end(), SectionSort);
1148 // Add terminating symbols for each section.
1149 for (unsigned ID=0;ID<Sections.size();ID++) {
1150 const MCSection *Section = Sections[ID];
1151 MCSymbol *Sym = NULL;
1154 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1155 // if we know the section name up-front. For user-created sections, the resulting
1156 // label may not be valid to use as a label. (section names can use a greater
1157 // set of characters on some systems)
1158 Sym = Asm->GetTempSymbol("debug_end", ID);
1159 Asm->OutStreamer.SwitchSection(Section);
1160 Asm->OutStreamer.EmitLabel(Sym);
1163 // Insert a final terminator.
1164 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1168 // Emit all Dwarf sections that should come after the content.
1169 void DwarfDebug::endModule() {
1171 if (!FirstCU) return;
1173 // End any existing sections.
1174 // TODO: Does this need to happen?
1177 // Finalize the debug info for the module.
1178 finalizeModuleInfo();
1180 if (!useSplitDwarf()) {
1183 // Emit all the DIEs into a debug info section.
1186 // Corresponding abbreviations into a abbrev section.
1187 emitAbbreviations();
1189 // Emit info into a debug loc section.
1192 // Emit info into a debug aranges section.
1195 // Emit info into a debug ranges section.
1198 // Emit info into a debug macinfo section.
1202 // TODO: Fill this in for separated debug sections and separate
1203 // out information into new sections.
1205 if (useSplitDwarf())
1208 // Emit the debug info section and compile units.
1212 // Corresponding abbreviations into a abbrev section.
1213 emitAbbreviations();
1214 emitDebugAbbrevDWO();
1216 // Emit info into a debug loc section.
1219 // Emit info into a debug aranges section.
1222 // Emit info into a debug ranges section.
1225 // Emit info into a debug macinfo section.
1228 // Emit DWO addresses.
1229 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1233 // Emit info into the dwarf accelerator table sections.
1234 if (useDwarfAccelTables()) {
1237 emitAccelNamespaces();
1241 // Emit the pubnames and pubtypes sections if requested.
1242 if (HasDwarfPubSections) {
1243 emitDebugPubNames(GenerateGnuPubSections);
1244 emitDebugPubTypes(GenerateGnuPubSections);
1249 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1250 E = CUMap.end(); I != E; ++I)
1253 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1254 E = SkeletonCUs.end(); I != E; ++I)
1257 // Reset these for the next Module if we have one.
1261 // Find abstract variable, if any, associated with Var.
1262 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1263 DebugLoc ScopeLoc) {
1264 LLVMContext &Ctx = DV->getContext();
1265 // More then one inlined variable corresponds to one abstract variable.
1266 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1267 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1269 return AbsDbgVariable;
1271 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1275 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1276 addScopeVariable(Scope, AbsDbgVariable);
1277 AbstractVariables[Var] = AbsDbgVariable;
1278 return AbsDbgVariable;
1281 // If Var is a current function argument then add it to CurrentFnArguments list.
1282 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1283 DbgVariable *Var, LexicalScope *Scope) {
1284 if (!LScopes.isCurrentFunctionScope(Scope))
1286 DIVariable DV = Var->getVariable();
1287 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1289 unsigned ArgNo = DV.getArgNumber();
1293 size_t Size = CurrentFnArguments.size();
1295 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1296 // llvm::Function argument size is not good indicator of how many
1297 // arguments does the function have at source level.
1299 CurrentFnArguments.resize(ArgNo * 2);
1300 CurrentFnArguments[ArgNo - 1] = Var;
1304 // Collect variable information from side table maintained by MMI.
1306 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1307 SmallPtrSet<const MDNode *, 16> &Processed) {
1308 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1309 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1310 VE = VMap.end(); VI != VE; ++VI) {
1311 const MDNode *Var = VI->first;
1313 Processed.insert(Var);
1315 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1317 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1319 // If variable scope is not found then skip this variable.
1323 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1324 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1325 RegVar->setFrameIndex(VP.first);
1326 if (!addCurrentFnArgument(MF, RegVar, Scope))
1327 addScopeVariable(Scope, RegVar);
1329 AbsDbgVariable->setFrameIndex(VP.first);
1333 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1335 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1336 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1337 return MI->getNumOperands() == 3 &&
1338 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1339 (MI->getOperand(1).isImm() ||
1340 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1343 // Get .debug_loc entry for the instruction range starting at MI.
1344 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1345 const MCSymbol *FLabel,
1346 const MCSymbol *SLabel,
1347 const MachineInstr *MI) {
1348 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1350 assert(MI->getNumOperands() == 3);
1351 if (MI->getOperand(0).isReg()) {
1352 MachineLocation MLoc;
1353 // If the second operand is an immediate, this is a
1354 // register-indirect address.
1355 if (!MI->getOperand(1).isImm())
1356 MLoc.set(MI->getOperand(0).getReg());
1358 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1359 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1361 if (MI->getOperand(0).isImm())
1362 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1363 if (MI->getOperand(0).isFPImm())
1364 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1365 if (MI->getOperand(0).isCImm())
1366 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1368 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1371 // Find variables for each lexical scope.
1373 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1374 SmallPtrSet<const MDNode *, 16> &Processed) {
1376 // Grab the variable info that was squirreled away in the MMI side-table.
1377 collectVariableInfoFromMMITable(MF, Processed);
1379 for (SmallVectorImpl<const MDNode*>::const_iterator
1380 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1382 const MDNode *Var = *UVI;
1383 if (Processed.count(Var))
1386 // History contains relevant DBG_VALUE instructions for Var and instructions
1388 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1389 if (History.empty())
1391 const MachineInstr *MInsn = History.front();
1394 LexicalScope *Scope = NULL;
1395 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1396 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1397 Scope = LScopes.getCurrentFunctionScope();
1398 else if (MDNode *IA = DV.getInlinedAt())
1399 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1401 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1402 // If variable scope is not found then skip this variable.
1406 Processed.insert(DV);
1407 assert(MInsn->isDebugValue() && "History must begin with debug value");
1408 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1409 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1410 if (!addCurrentFnArgument(MF, RegVar, Scope))
1411 addScopeVariable(Scope, RegVar);
1413 AbsVar->setMInsn(MInsn);
1415 // Simplify ranges that are fully coalesced.
1416 if (History.size() <= 1 || (History.size() == 2 &&
1417 MInsn->isIdenticalTo(History.back()))) {
1418 RegVar->setMInsn(MInsn);
1422 // Handle multiple DBG_VALUE instructions describing one variable.
1423 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1425 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1426 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1427 const MachineInstr *Begin = *HI;
1428 assert(Begin->isDebugValue() && "Invalid History entry");
1430 // Check if DBG_VALUE is truncating a range.
1431 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1432 && !Begin->getOperand(0).getReg())
1435 // Compute the range for a register location.
1436 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1437 const MCSymbol *SLabel = 0;
1440 // If Begin is the last instruction in History then its value is valid
1441 // until the end of the function.
1442 SLabel = FunctionEndSym;
1444 const MachineInstr *End = HI[1];
1445 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1446 << "\t" << *Begin << "\t" << *End << "\n");
1447 if (End->isDebugValue())
1448 SLabel = getLabelBeforeInsn(End);
1450 // End is a normal instruction clobbering the range.
1451 SLabel = getLabelAfterInsn(End);
1452 assert(SLabel && "Forgot label after clobber instruction");
1457 // The value is valid until the next DBG_VALUE or clobber.
1458 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1461 DotDebugLocEntries.push_back(DotDebugLocEntry());
1464 // Collect info for variables that were optimized out.
1465 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1466 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1467 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1468 DIVariable DV(Variables.getElement(i));
1469 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1471 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1472 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1476 // Return Label preceding the instruction.
1477 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1478 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1479 assert(Label && "Didn't insert label before instruction");
1483 // Return Label immediately following the instruction.
1484 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1485 return LabelsAfterInsn.lookup(MI);
1488 // Process beginning of an instruction.
1489 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1490 // Check if source location changes, but ignore DBG_VALUE locations.
1491 if (!MI->isDebugValue()) {
1492 DebugLoc DL = MI->getDebugLoc();
1493 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1496 if (DL == PrologEndLoc) {
1497 Flags |= DWARF2_FLAG_PROLOGUE_END;
1498 PrologEndLoc = DebugLoc();
1500 if (PrologEndLoc.isUnknown())
1501 Flags |= DWARF2_FLAG_IS_STMT;
1503 if (!DL.isUnknown()) {
1504 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1505 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1507 recordSourceLine(0, 0, 0, 0);
1511 // Insert labels where requested.
1512 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1513 LabelsBeforeInsn.find(MI);
1516 if (I == LabelsBeforeInsn.end())
1519 // Label already assigned.
1524 PrevLabel = MMI->getContext().CreateTempSymbol();
1525 Asm->OutStreamer.EmitLabel(PrevLabel);
1527 I->second = PrevLabel;
1530 // Process end of an instruction.
1531 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1532 // Don't create a new label after DBG_VALUE instructions.
1533 // They don't generate code.
1534 if (!MI->isDebugValue())
1537 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1538 LabelsAfterInsn.find(MI);
1541 if (I == LabelsAfterInsn.end())
1544 // Label already assigned.
1548 // We need a label after this instruction.
1550 PrevLabel = MMI->getContext().CreateTempSymbol();
1551 Asm->OutStreamer.EmitLabel(PrevLabel);
1553 I->second = PrevLabel;
1556 // Each LexicalScope has first instruction and last instruction to mark
1557 // beginning and end of a scope respectively. Create an inverse map that list
1558 // scopes starts (and ends) with an instruction. One instruction may start (or
1559 // end) multiple scopes. Ignore scopes that are not reachable.
1560 void DwarfDebug::identifyScopeMarkers() {
1561 SmallVector<LexicalScope *, 4> WorkList;
1562 WorkList.push_back(LScopes.getCurrentFunctionScope());
1563 while (!WorkList.empty()) {
1564 LexicalScope *S = WorkList.pop_back_val();
1566 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1567 if (!Children.empty())
1568 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1569 SE = Children.end(); SI != SE; ++SI)
1570 WorkList.push_back(*SI);
1572 if (S->isAbstractScope())
1575 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1578 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1579 RE = Ranges.end(); RI != RE; ++RI) {
1580 assert(RI->first && "InsnRange does not have first instruction!");
1581 assert(RI->second && "InsnRange does not have second instruction!");
1582 requestLabelBeforeInsn(RI->first);
1583 requestLabelAfterInsn(RI->second);
1588 // Get MDNode for DebugLoc's scope.
1589 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1590 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1591 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1592 return DL.getScope(Ctx);
1595 // Walk up the scope chain of given debug loc and find line number info
1596 // for the function.
1597 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1598 const MDNode *Scope = getScopeNode(DL, Ctx);
1599 DISubprogram SP = getDISubprogram(Scope);
1600 if (SP.isSubprogram()) {
1601 // Check for number of operands since the compatibility is
1603 if (SP->getNumOperands() > 19)
1604 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1606 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1612 // Gather pre-function debug information. Assumes being called immediately
1613 // after the function entry point has been emitted.
1614 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1616 // If there's no debug info for the function we're not going to do anything.
1617 if (!MMI->hasDebugInfo())
1620 // Grab the lexical scopes for the function, if we don't have any of those
1621 // then we're not going to be able to do anything.
1622 LScopes.initialize(*MF);
1623 if (LScopes.empty())
1626 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1628 // Make sure that each lexical scope will have a begin/end label.
1629 identifyScopeMarkers();
1631 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1632 // belongs to so that we add to the correct per-cu line table in the
1634 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1635 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1636 assert(TheCU && "Unable to find compile unit!");
1637 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1638 // Use a single line table if we are using .loc and generating assembly.
1639 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1641 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1643 // Emit a label for the function so that we have a beginning address.
1644 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1645 // Assumes in correct section after the entry point.
1646 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1648 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1649 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1650 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1652 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1654 bool AtBlockEntry = true;
1655 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1657 const MachineInstr *MI = II;
1659 if (MI->isDebugValue()) {
1660 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1662 // Keep track of user variables.
1664 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1666 // Variable is in a register, we need to check for clobbers.
1667 if (isDbgValueInDefinedReg(MI))
1668 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1670 // Check the history of this variable.
1671 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1672 if (History.empty()) {
1673 UserVariables.push_back(Var);
1674 // The first mention of a function argument gets the FunctionBeginSym
1675 // label, so arguments are visible when breaking at function entry.
1677 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1678 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1679 LabelsBeforeInsn[MI] = FunctionBeginSym;
1681 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1682 const MachineInstr *Prev = History.back();
1683 if (Prev->isDebugValue()) {
1684 // Coalesce identical entries at the end of History.
1685 if (History.size() >= 2 &&
1686 Prev->isIdenticalTo(History[History.size() - 2])) {
1687 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1688 << "\t" << *Prev << "\t"
1689 << *History[History.size() - 2] << "\n");
1693 // Terminate old register assignments that don't reach MI;
1694 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1695 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1696 isDbgValueInDefinedReg(Prev)) {
1697 // Previous register assignment needs to terminate at the end of
1699 MachineBasicBlock::const_iterator LastMI =
1700 PrevMBB->getLastNonDebugInstr();
1701 if (LastMI == PrevMBB->end()) {
1702 // Drop DBG_VALUE for empty range.
1703 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1704 << "\t" << *Prev << "\n");
1706 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1707 // Terminate after LastMI.
1708 History.push_back(LastMI);
1712 History.push_back(MI);
1714 // Not a DBG_VALUE instruction.
1716 AtBlockEntry = false;
1718 // First known non-DBG_VALUE and non-frame setup location marks
1719 // the beginning of the function body.
1720 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1721 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1722 PrologEndLoc = MI->getDebugLoc();
1724 // Check if the instruction clobbers any registers with debug vars.
1725 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1726 MOE = MI->operands_end();
1727 MOI != MOE; ++MOI) {
1728 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1730 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1733 const MDNode *Var = LiveUserVar[Reg];
1736 // Reg is now clobbered.
1737 LiveUserVar[Reg] = 0;
1739 // Was MD last defined by a DBG_VALUE referring to Reg?
1740 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1741 if (HistI == DbgValues.end())
1743 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1744 if (History.empty())
1746 const MachineInstr *Prev = History.back();
1747 // Sanity-check: Register assignments are terminated at the end of
1749 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1751 // Is the variable still in Reg?
1752 if (!isDbgValueInDefinedReg(Prev) ||
1753 Prev->getOperand(0).getReg() != Reg)
1755 // Var is clobbered. Make sure the next instruction gets a label.
1756 History.push_back(MI);
1763 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1765 SmallVectorImpl<const MachineInstr *> &History = I->second;
1766 if (History.empty())
1769 // Make sure the final register assignments are terminated.
1770 const MachineInstr *Prev = History.back();
1771 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1772 const MachineBasicBlock *PrevMBB = Prev->getParent();
1773 MachineBasicBlock::const_iterator LastMI =
1774 PrevMBB->getLastNonDebugInstr();
1775 if (LastMI == PrevMBB->end())
1776 // Drop DBG_VALUE for empty range.
1778 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1779 // Terminate after LastMI.
1780 History.push_back(LastMI);
1783 // Request labels for the full history.
1784 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1785 const MachineInstr *MI = History[i];
1786 if (MI->isDebugValue())
1787 requestLabelBeforeInsn(MI);
1789 requestLabelAfterInsn(MI);
1793 PrevInstLoc = DebugLoc();
1794 PrevLabel = FunctionBeginSym;
1796 // Record beginning of function.
1797 if (!PrologEndLoc.isUnknown()) {
1798 DebugLoc FnStartDL =
1799 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1801 FnStartDL.getLine(), FnStartDL.getCol(),
1802 FnStartDL.getScope(MF->getFunction()->getContext()),
1803 // We'd like to list the prologue as "not statements" but GDB behaves
1804 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1805 DWARF2_FLAG_IS_STMT);
1809 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1810 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1811 DIVariable DV = Var->getVariable();
1812 // Variables with positive arg numbers are parameters.
1813 if (unsigned ArgNum = DV.getArgNumber()) {
1814 // Keep all parameters in order at the start of the variable list to ensure
1815 // function types are correct (no out-of-order parameters)
1817 // This could be improved by only doing it for optimized builds (unoptimized
1818 // builds have the right order to begin with), searching from the back (this
1819 // would catch the unoptimized case quickly), or doing a binary search
1820 // rather than linear search.
1821 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1822 while (I != Vars.end()) {
1823 unsigned CurNum = (*I)->getVariable().getArgNumber();
1824 // A local (non-parameter) variable has been found, insert immediately
1828 // A later indexed parameter has been found, insert immediately before it.
1829 if (CurNum > ArgNum)
1833 Vars.insert(I, Var);
1837 Vars.push_back(Var);
1840 // Gather and emit post-function debug information.
1841 void DwarfDebug::endFunction(const MachineFunction *MF) {
1842 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1844 // Define end label for subprogram.
1845 FunctionEndSym = Asm->GetTempSymbol("func_end",
1846 Asm->getFunctionNumber());
1847 // Assumes in correct section after the entry point.
1848 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1849 // Set DwarfCompileUnitID in MCContext to default value.
1850 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1852 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1853 collectVariableInfo(MF, ProcessedVars);
1855 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1856 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1857 assert(TheCU && "Unable to find compile unit!");
1859 // Construct abstract scopes.
1860 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1861 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1862 LexicalScope *AScope = AList[i];
1863 DISubprogram SP(AScope->getScopeNode());
1864 if (SP.isSubprogram()) {
1865 // Collect info for variables that were optimized out.
1866 DIArray Variables = SP.getVariables();
1867 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1868 DIVariable DV(Variables.getElement(i));
1869 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1871 // Check that DbgVariable for DV wasn't created earlier, when
1872 // findAbstractVariable() was called for inlined instance of DV.
1873 LLVMContext &Ctx = DV->getContext();
1874 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1875 if (AbstractVariables.lookup(CleanDV))
1877 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1878 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1881 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1882 constructScopeDIE(TheCU, AScope);
1885 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1887 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1888 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1891 for (ScopeVariablesMap::iterator
1892 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1893 DeleteContainerPointers(I->second);
1894 ScopeVariables.clear();
1895 DeleteContainerPointers(CurrentFnArguments);
1896 UserVariables.clear();
1898 AbstractVariables.clear();
1899 LabelsBeforeInsn.clear();
1900 LabelsAfterInsn.clear();
1904 // Register a source line with debug info. Returns the unique label that was
1905 // emitted and which provides correspondence to the source line list.
1906 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1912 DIDescriptor Scope(S);
1914 if (Scope.isCompileUnit()) {
1915 DICompileUnit CU(S);
1916 Fn = CU.getFilename();
1917 Dir = CU.getDirectory();
1918 } else if (Scope.isFile()) {
1920 Fn = F.getFilename();
1921 Dir = F.getDirectory();
1922 } else if (Scope.isSubprogram()) {
1924 Fn = SP.getFilename();
1925 Dir = SP.getDirectory();
1926 } else if (Scope.isLexicalBlockFile()) {
1927 DILexicalBlockFile DBF(S);
1928 Fn = DBF.getFilename();
1929 Dir = DBF.getDirectory();
1930 } else if (Scope.isLexicalBlock()) {
1931 DILexicalBlock DB(S);
1932 Fn = DB.getFilename();
1933 Dir = DB.getDirectory();
1935 llvm_unreachable("Unexpected scope info");
1937 Src = getOrCreateSourceID(Fn, Dir,
1938 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1940 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1943 //===----------------------------------------------------------------------===//
1945 //===----------------------------------------------------------------------===//
1947 // Compute the size and offset of a DIE. The offset is relative to start of the
1948 // CU. It returns the offset after laying out the DIE.
1950 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1951 // Get the children.
1952 const std::vector<DIE *> &Children = Die->getChildren();
1954 // Record the abbreviation.
1955 assignAbbrevNumber(Die->getAbbrev());
1957 // Get the abbreviation for this DIE.
1958 unsigned AbbrevNumber = Die->getAbbrevNumber();
1959 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1962 Die->setOffset(Offset);
1964 // Start the size with the size of abbreviation code.
1965 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1967 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1968 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1970 // Size the DIE attribute values.
1971 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1972 // Size attribute value.
1973 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1975 // Size the DIE children if any.
1976 if (!Children.empty()) {
1977 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1978 "Children flag not set");
1980 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1981 Offset = computeSizeAndOffset(Children[j], Offset);
1983 // End of children marker.
1984 Offset += sizeof(int8_t);
1987 Die->setSize(Offset - Die->getOffset());
1991 // Compute the size and offset for each DIE.
1992 void DwarfUnits::computeSizeAndOffsets() {
1993 // Offset from the first CU in the debug info section is 0 initially.
1994 unsigned SecOffset = 0;
1996 // Iterate over each compile unit and set the size and offsets for each
1997 // DIE within each compile unit. All offsets are CU relative.
1998 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1999 E = CUs.end(); I != E; ++I) {
2000 (*I)->setDebugInfoOffset(SecOffset);
2002 // CU-relative offset is reset to 0 here.
2003 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
2004 (*I)->getHeaderSize(); // Unit-specific headers
2006 // EndOffset here is CU-relative, after laying out
2007 // all of the CU DIE.
2008 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
2009 SecOffset += EndOffset;
2013 // Emit initial Dwarf sections with a label at the start of each one.
2014 void DwarfDebug::emitSectionLabels() {
2015 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2017 // Dwarf sections base addresses.
2018 DwarfInfoSectionSym =
2019 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2020 DwarfAbbrevSectionSym =
2021 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2022 if (useSplitDwarf())
2023 DwarfAbbrevDWOSectionSym =
2024 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
2025 "section_abbrev_dwo");
2026 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
2028 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2029 emitSectionSym(Asm, MacroInfo);
2031 DwarfLineSectionSym =
2032 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2033 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2034 if (GenerateGnuPubSections) {
2035 DwarfGnuPubNamesSectionSym =
2036 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2037 DwarfGnuPubTypesSectionSym =
2038 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2039 } else if (HasDwarfPubSections) {
2040 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2041 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2044 DwarfStrSectionSym =
2045 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2046 if (useSplitDwarf()) {
2047 DwarfStrDWOSectionSym =
2048 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2049 DwarfAddrSectionSym =
2050 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2052 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2055 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
2056 "section_debug_loc");
2058 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2059 emitSectionSym(Asm, TLOF.getDataSection());
2062 // Recursively emits a debug information entry.
2063 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2064 // Get the abbreviation for this DIE.
2065 unsigned AbbrevNumber = Die->getAbbrevNumber();
2066 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2068 // Emit the code (index) for the abbreviation.
2069 if (Asm->isVerbose())
2070 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2071 Twine::utohexstr(Die->getOffset()) + ":0x" +
2072 Twine::utohexstr(Die->getSize()) + " " +
2073 dwarf::TagString(Abbrev->getTag()));
2074 Asm->EmitULEB128(AbbrevNumber);
2076 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
2077 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2079 // Emit the DIE attribute values.
2080 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2081 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2082 dwarf::Form Form = AbbrevData[i].getForm();
2083 assert(Form && "Too many attributes for DIE (check abbreviation)");
2085 if (Asm->isVerbose())
2086 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2089 case dwarf::DW_AT_abstract_origin:
2090 case dwarf::DW_AT_type:
2091 case dwarf::DW_AT_friend:
2092 case dwarf::DW_AT_specification:
2093 case dwarf::DW_AT_import:
2094 case dwarf::DW_AT_containing_type: {
2095 DIEEntry *E = cast<DIEEntry>(Values[i]);
2096 DIE *Origin = E->getEntry();
2097 unsigned Addr = Origin->getOffset();
2098 if (Form == dwarf::DW_FORM_ref_addr) {
2099 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2100 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2101 // section. Origin->getOffset() returns the offset from start of the
2103 CompileUnit *CU = CUDieMap.lookup(Origin->getCompileUnit());
2104 assert(CU && "CUDie should belong to a CU.");
2105 Addr += CU->getDebugInfoOffset();
2106 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2107 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2108 DIEEntry::getRefAddrSize(Asm));
2110 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2111 DwarfInfoSectionSym,
2112 DIEEntry::getRefAddrSize(Asm));
2114 // Make sure Origin belong to the same CU.
2115 assert(Die->getCompileUnit() == Origin->getCompileUnit() &&
2116 "The referenced DIE should belong to the same CU in ref4");
2117 Asm->EmitInt32(Addr);
2121 case dwarf::DW_AT_ranges: {
2122 // DW_AT_range Value encodes offset in debug_range section.
2123 DIEInteger *V = cast<DIEInteger>(Values[i]);
2125 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2126 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2130 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2132 DwarfDebugRangeSectionSym,
2137 case dwarf::DW_AT_location: {
2138 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2139 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2140 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2142 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2144 Values[i]->EmitValue(Asm, Form);
2148 case dwarf::DW_AT_accessibility: {
2149 if (Asm->isVerbose()) {
2150 DIEInteger *V = cast<DIEInteger>(Values[i]);
2151 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2153 Values[i]->EmitValue(Asm, Form);
2157 // Emit an attribute using the defined form.
2158 Values[i]->EmitValue(Asm, Form);
2163 // Emit the DIE children if any.
2164 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2165 const std::vector<DIE *> &Children = Die->getChildren();
2167 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2168 emitDIE(Children[j], Abbrevs);
2170 if (Asm->isVerbose())
2171 Asm->OutStreamer.AddComment("End Of Children Mark");
2176 // Emit the various dwarf units to the unit section USection with
2177 // the abbreviations going into ASection.
2178 void DwarfUnits::emitUnits(DwarfDebug *DD,
2179 const MCSection *USection,
2180 const MCSection *ASection,
2181 const MCSymbol *ASectionSym) {
2182 Asm->OutStreamer.SwitchSection(USection);
2183 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2184 E = CUs.end(); I != E; ++I) {
2185 CompileUnit *TheCU = *I;
2186 DIE *Die = TheCU->getCUDie();
2188 // Emit the compile units header.
2190 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2191 TheCU->getUniqueID()));
2193 // Emit size of content not including length itself
2194 Asm->OutStreamer.AddComment("Length of Unit");
2195 Asm->EmitInt32(TheCU->getHeaderSize() + Die->getSize());
2197 TheCU->emitHeader(ASection, ASectionSym);
2199 DD->emitDIE(Die, Abbreviations);
2200 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2201 TheCU->getUniqueID()));
2205 // Emit the debug info section.
2206 void DwarfDebug::emitDebugInfo() {
2207 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2209 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2210 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2211 DwarfAbbrevSectionSym);
2214 // Emit the abbreviation section.
2215 void DwarfDebug::emitAbbreviations() {
2216 if (!useSplitDwarf())
2217 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2220 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2223 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2224 std::vector<DIEAbbrev *> *Abbrevs) {
2225 // Check to see if it is worth the effort.
2226 if (!Abbrevs->empty()) {
2227 // Start the debug abbrev section.
2228 Asm->OutStreamer.SwitchSection(Section);
2230 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2231 Asm->OutStreamer.EmitLabel(Begin);
2233 // For each abbrevation.
2234 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2235 // Get abbreviation data
2236 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2238 // Emit the abbrevations code (base 1 index.)
2239 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2241 // Emit the abbreviations data.
2245 // Mark end of abbreviations.
2246 Asm->EmitULEB128(0, "EOM(3)");
2248 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2249 Asm->OutStreamer.EmitLabel(End);
2253 // Emit the last address of the section and the end of the line matrix.
2254 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2255 // Define last address of section.
2256 Asm->OutStreamer.AddComment("Extended Op");
2259 Asm->OutStreamer.AddComment("Op size");
2260 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2261 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2262 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2264 Asm->OutStreamer.AddComment("Section end label");
2266 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2267 Asm->getDataLayout().getPointerSize());
2269 // Mark end of matrix.
2270 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2276 // Emit visible names into a hashed accelerator table section.
2277 void DwarfDebug::emitAccelNames() {
2278 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2279 dwarf::DW_FORM_data4));
2280 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2281 E = CUMap.end(); I != E; ++I) {
2282 CompileUnit *TheCU = I->second;
2283 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2284 for (StringMap<std::vector<DIE*> >::const_iterator
2285 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2286 StringRef Name = GI->getKey();
2287 const std::vector<DIE *> &Entities = GI->second;
2288 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2289 DE = Entities.end(); DI != DE; ++DI)
2290 AT.AddName(Name, (*DI));
2294 AT.FinalizeTable(Asm, "Names");
2295 Asm->OutStreamer.SwitchSection(
2296 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2297 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2298 Asm->OutStreamer.EmitLabel(SectionBegin);
2300 // Emit the full data.
2301 AT.Emit(Asm, SectionBegin, &InfoHolder);
2304 // Emit objective C classes and categories into a hashed accelerator table
2306 void DwarfDebug::emitAccelObjC() {
2307 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2308 dwarf::DW_FORM_data4));
2309 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2310 E = CUMap.end(); I != E; ++I) {
2311 CompileUnit *TheCU = I->second;
2312 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2313 for (StringMap<std::vector<DIE*> >::const_iterator
2314 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2315 StringRef Name = GI->getKey();
2316 const std::vector<DIE *> &Entities = GI->second;
2317 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2318 DE = Entities.end(); DI != DE; ++DI)
2319 AT.AddName(Name, (*DI));
2323 AT.FinalizeTable(Asm, "ObjC");
2324 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2325 .getDwarfAccelObjCSection());
2326 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2327 Asm->OutStreamer.EmitLabel(SectionBegin);
2329 // Emit the full data.
2330 AT.Emit(Asm, SectionBegin, &InfoHolder);
2333 // Emit namespace dies into a hashed accelerator table.
2334 void DwarfDebug::emitAccelNamespaces() {
2335 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2336 dwarf::DW_FORM_data4));
2337 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2338 E = CUMap.end(); I != E; ++I) {
2339 CompileUnit *TheCU = I->second;
2340 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2341 for (StringMap<std::vector<DIE*> >::const_iterator
2342 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2343 StringRef Name = GI->getKey();
2344 const std::vector<DIE *> &Entities = GI->second;
2345 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2346 DE = Entities.end(); DI != DE; ++DI)
2347 AT.AddName(Name, (*DI));
2351 AT.FinalizeTable(Asm, "namespac");
2352 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2353 .getDwarfAccelNamespaceSection());
2354 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2355 Asm->OutStreamer.EmitLabel(SectionBegin);
2357 // Emit the full data.
2358 AT.Emit(Asm, SectionBegin, &InfoHolder);
2361 // Emit type dies into a hashed accelerator table.
2362 void DwarfDebug::emitAccelTypes() {
2363 std::vector<DwarfAccelTable::Atom> Atoms;
2364 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2365 dwarf::DW_FORM_data4));
2366 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag,
2367 dwarf::DW_FORM_data2));
2368 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags,
2369 dwarf::DW_FORM_data1));
2370 DwarfAccelTable AT(Atoms);
2371 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2372 E = CUMap.end(); I != E; ++I) {
2373 CompileUnit *TheCU = I->second;
2374 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2375 = TheCU->getAccelTypes();
2376 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2377 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2378 StringRef Name = GI->getKey();
2379 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2380 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2381 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2382 AT.AddName(Name, (*DI).first, (*DI).second);
2386 AT.FinalizeTable(Asm, "types");
2387 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2388 .getDwarfAccelTypesSection());
2389 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2390 Asm->OutStreamer.EmitLabel(SectionBegin);
2392 // Emit the full data.
2393 AT.Emit(Asm, SectionBegin, &InfoHolder);
2396 // Public name handling.
2397 // The format for the various pubnames:
2399 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2400 // for the DIE that is named.
2402 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2403 // into the CU and the index value is computed according to the type of value
2404 // for the DIE that is named.
2406 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2407 // it's the offset within the debug_info/debug_types dwo section, however, the
2408 // reference in the pubname header doesn't change.
2410 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2411 static dwarf::PubIndexEntryDescriptor computeIndexValue(CompileUnit *CU,
2413 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2415 // We could have a specification DIE that has our most of our knowledge,
2416 // look for that now.
2417 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2419 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2420 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2421 Linkage = dwarf::GIEL_EXTERNAL;
2422 } else if (Die->findAttribute(dwarf::DW_AT_external))
2423 Linkage = dwarf::GIEL_EXTERNAL;
2425 switch (Die->getTag()) {
2426 case dwarf::DW_TAG_class_type:
2427 case dwarf::DW_TAG_structure_type:
2428 case dwarf::DW_TAG_union_type:
2429 case dwarf::DW_TAG_enumeration_type:
2430 return dwarf::PubIndexEntryDescriptor(
2431 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2432 ? dwarf::GIEL_STATIC
2433 : dwarf::GIEL_EXTERNAL);
2434 case dwarf::DW_TAG_typedef:
2435 case dwarf::DW_TAG_base_type:
2436 case dwarf::DW_TAG_subrange_type:
2437 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2438 case dwarf::DW_TAG_namespace:
2439 return dwarf::GIEK_TYPE;
2440 case dwarf::DW_TAG_subprogram:
2441 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2442 case dwarf::DW_TAG_constant:
2443 case dwarf::DW_TAG_variable:
2444 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2445 case dwarf::DW_TAG_enumerator:
2446 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2447 dwarf::GIEL_STATIC);
2449 return dwarf::GIEK_NONE;
2453 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2455 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2456 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2457 const MCSection *PSec =
2458 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2459 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2461 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2462 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2463 CompileUnit *TheCU = I->second;
2464 unsigned ID = TheCU->getUniqueID();
2466 // Start the dwarf pubnames section.
2467 Asm->OutStreamer.SwitchSection(PSec);
2469 // Emit a label so we can reference the beginning of this pubname section.
2471 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames",
2472 TheCU->getUniqueID()));
2475 Asm->OutStreamer.AddComment("Length of Public Names Info");
2476 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2477 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2479 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2481 Asm->OutStreamer.AddComment("DWARF Version");
2482 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2484 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2485 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2486 DwarfInfoSectionSym);
2488 Asm->OutStreamer.AddComment("Compilation Unit Length");
2489 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2490 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2493 // Emit the pubnames for this compilation unit.
2494 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2495 for (StringMap<DIE*>::const_iterator
2496 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2497 const char *Name = GI->getKeyData();
2498 DIE *Entity = GI->second;
2500 Asm->OutStreamer.AddComment("DIE offset");
2501 Asm->EmitInt32(Entity->getOffset());
2504 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2505 Asm->OutStreamer.AddComment(
2506 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2507 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2508 Asm->EmitInt8(Desc.toBits());
2511 if (Asm->isVerbose())
2512 Asm->OutStreamer.AddComment("External Name");
2513 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2516 Asm->OutStreamer.AddComment("End Mark");
2518 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2522 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2523 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2524 const MCSection *PSec =
2525 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2526 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2528 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2531 CompileUnit *TheCU = I->second;
2532 // Start the dwarf pubtypes section.
2533 Asm->OutStreamer.SwitchSection(PSec);
2535 // Emit a label so we can reference the beginning of this pubtype section.
2537 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes",
2538 TheCU->getUniqueID()));
2541 Asm->OutStreamer.AddComment("Length of Public Types Info");
2542 Asm->EmitLabelDifference(
2543 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2544 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2546 Asm->OutStreamer.EmitLabel(
2547 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()));
2549 if (Asm->isVerbose())
2550 Asm->OutStreamer.AddComment("DWARF Version");
2551 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2553 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2554 Asm->EmitSectionOffset(
2555 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()),
2556 DwarfInfoSectionSym);
2558 Asm->OutStreamer.AddComment("Compilation Unit Length");
2559 Asm->EmitLabelDifference(
2560 Asm->GetTempSymbol(ISec->getLabelEndName(), TheCU->getUniqueID()),
2561 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()), 4);
2563 // Emit the pubtypes.
2564 const StringMap<DIE *> &Globals = TheCU->getGlobalTypes();
2565 for (StringMap<DIE *>::const_iterator GI = Globals.begin(),
2568 const char *Name = GI->getKeyData();
2569 DIE *Entity = GI->second;
2571 if (Asm->isVerbose())
2572 Asm->OutStreamer.AddComment("DIE offset");
2573 Asm->EmitInt32(Entity->getOffset());
2576 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2577 Asm->OutStreamer.AddComment(
2578 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2579 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2580 Asm->EmitInt8(Desc.toBits());
2583 if (Asm->isVerbose())
2584 Asm->OutStreamer.AddComment("External Name");
2586 // Emit the name with a terminating null byte.
2587 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2590 Asm->OutStreamer.AddComment("End Mark");
2592 Asm->OutStreamer.EmitLabel(
2593 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()));
2597 // Emit strings into a string section.
2598 void DwarfUnits::emitStrings(const MCSection *StrSection,
2599 const MCSection *OffsetSection = NULL,
2600 const MCSymbol *StrSecSym = NULL) {
2602 if (StringPool.empty()) return;
2604 // Start the dwarf str section.
2605 Asm->OutStreamer.SwitchSection(StrSection);
2607 // Get all of the string pool entries and put them in an array by their ID so
2608 // we can sort them.
2609 SmallVector<std::pair<unsigned,
2610 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2612 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2613 I = StringPool.begin(), E = StringPool.end();
2615 Entries.push_back(std::make_pair(I->second.second, &*I));
2617 array_pod_sort(Entries.begin(), Entries.end());
2619 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2620 // Emit a label for reference from debug information entries.
2621 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2623 // Emit the string itself with a terminating null byte.
2624 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2625 Entries[i].second->getKeyLength()+1));
2628 // If we've got an offset section go ahead and emit that now as well.
2629 if (OffsetSection) {
2630 Asm->OutStreamer.SwitchSection(OffsetSection);
2631 unsigned offset = 0;
2632 unsigned size = 4; // FIXME: DWARF64 is 8.
2633 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2634 Asm->OutStreamer.EmitIntValue(offset, size);
2635 offset += Entries[i].second->getKeyLength() + 1;
2640 // Emit strings into a string section.
2641 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2643 if (AddressPool.empty()) return;
2645 // Start the dwarf addr section.
2646 Asm->OutStreamer.SwitchSection(AddrSection);
2648 // Order the address pool entries by ID
2649 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2651 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2652 E = AddressPool.end();
2654 Entries[I->second] = I->first;
2656 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2657 // Emit an expression for reference from debug information entries.
2658 if (const MCExpr *Expr = Entries[i])
2659 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2661 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2666 // Emit visible names into a debug str section.
2667 void DwarfDebug::emitDebugStr() {
2668 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2669 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2672 // Emit locations into the debug loc section.
2673 void DwarfDebug::emitDebugLoc() {
2674 if (DotDebugLocEntries.empty())
2677 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2678 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2680 DotDebugLocEntry &Entry = *I;
2681 if (I + 1 != DotDebugLocEntries.end())
2685 // Start the dwarf loc section.
2686 Asm->OutStreamer.SwitchSection(
2687 Asm->getObjFileLowering().getDwarfLocSection());
2688 unsigned char Size = Asm->getDataLayout().getPointerSize();
2689 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2691 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2692 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2693 I != E; ++I, ++index) {
2694 DotDebugLocEntry &Entry = *I;
2695 if (Entry.isMerged()) continue;
2696 if (Entry.isEmpty()) {
2697 Asm->OutStreamer.EmitIntValue(0, Size);
2698 Asm->OutStreamer.EmitIntValue(0, Size);
2699 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2701 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2702 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2703 DIVariable DV(Entry.getVariable());
2704 Asm->OutStreamer.AddComment("Loc expr size");
2705 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2706 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2707 Asm->EmitLabelDifference(end, begin, 2);
2708 Asm->OutStreamer.EmitLabel(begin);
2709 if (Entry.isInt()) {
2710 DIBasicType BTy(DV.getType());
2712 (BTy.getEncoding() == dwarf::DW_ATE_signed
2713 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2714 Asm->OutStreamer.AddComment("DW_OP_consts");
2715 Asm->EmitInt8(dwarf::DW_OP_consts);
2716 Asm->EmitSLEB128(Entry.getInt());
2718 Asm->OutStreamer.AddComment("DW_OP_constu");
2719 Asm->EmitInt8(dwarf::DW_OP_constu);
2720 Asm->EmitULEB128(Entry.getInt());
2722 } else if (Entry.isLocation()) {
2723 MachineLocation Loc = Entry.getLoc();
2724 if (!DV.hasComplexAddress())
2726 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2728 // Complex address entry.
2729 unsigned N = DV.getNumAddrElements();
2731 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2732 if (Loc.getOffset()) {
2734 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2735 Asm->OutStreamer.AddComment("DW_OP_deref");
2736 Asm->EmitInt8(dwarf::DW_OP_deref);
2737 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2738 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2739 Asm->EmitSLEB128(DV.getAddrElement(1));
2741 // If first address element is OpPlus then emit
2742 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2743 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2744 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2748 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2751 // Emit remaining complex address elements.
2752 for (; i < N; ++i) {
2753 uint64_t Element = DV.getAddrElement(i);
2754 if (Element == DIBuilder::OpPlus) {
2755 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2756 Asm->EmitULEB128(DV.getAddrElement(++i));
2757 } else if (Element == DIBuilder::OpDeref) {
2759 Asm->EmitInt8(dwarf::DW_OP_deref);
2761 llvm_unreachable("unknown Opcode found in complex address");
2765 // else ... ignore constant fp. There is not any good way to
2766 // to represent them here in dwarf.
2767 Asm->OutStreamer.EmitLabel(end);
2772 struct SymbolCUSorter {
2773 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2774 const MCStreamer &Streamer;
2776 bool operator() (const SymbolCU &A, const SymbolCU &B) {
2777 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2778 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2780 // Symbols with no order assigned should be placed at the end.
2781 // (e.g. section end labels)
2783 IA = (unsigned)(-1);
2785 IB = (unsigned)(-1);
2790 static bool CUSort(const CompileUnit *A, const CompileUnit *B) {
2791 return (A->getUniqueID() < B->getUniqueID());
2795 const MCSymbol *Start, *End;
2798 // Emit a debug aranges section, containing a CU lookup for any
2799 // address we can tie back to a CU.
2800 void DwarfDebug::emitDebugARanges() {
2801 // Start the dwarf aranges section.
2803 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2805 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2809 // Build a list of sections used.
2810 std::vector<const MCSection *> Sections;
2811 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2813 const MCSection *Section = it->first;
2814 Sections.push_back(Section);
2817 // Sort the sections into order.
2818 // This is only done to ensure consistent output order across different runs.
2819 std::sort(Sections.begin(), Sections.end(), SectionSort);
2821 // Build a set of address spans, sorted by CU.
2822 for (size_t SecIdx=0;SecIdx<Sections.size();SecIdx++) {
2823 const MCSection *Section = Sections[SecIdx];
2824 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2825 if (List.size() < 2)
2828 // Sort the symbols by offset within the section.
2829 SymbolCUSorter sorter(Asm->OutStreamer);
2830 std::sort(List.begin(), List.end(), sorter);
2832 // If we have no section (e.g. common), just write out
2833 // individual spans for each symbol.
2834 if (Section == NULL) {
2835 for (size_t n = 0; n < List.size(); n++) {
2836 const SymbolCU &Cur = List[n];
2839 Span.Start = Cur.Sym;
2842 Spans[Cur.CU].push_back(Span);
2845 // Build spans between each label.
2846 const MCSymbol *StartSym = List[0].Sym;
2847 for (size_t n = 1; n < List.size(); n++) {
2848 const SymbolCU &Prev = List[n - 1];
2849 const SymbolCU &Cur = List[n];
2851 // Try and build the longest span we can within the same CU.
2852 if (Cur.CU != Prev.CU) {
2854 Span.Start = StartSym;
2856 Spans[Prev.CU].push_back(Span);
2863 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2864 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2866 // Build a list of CUs used.
2867 std::vector<CompileUnit *> CUs;
2868 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2869 CompileUnit *CU = it->first;
2873 // Sort the CU list (again, to ensure consistent output order).
2874 std::sort(CUs.begin(), CUs.end(), CUSort);
2876 // Emit an arange table for each CU we used.
2877 for (size_t CUIdx=0;CUIdx<CUs.size();CUIdx++) {
2878 CompileUnit *CU = CUs[CUIdx];
2879 std::vector<ArangeSpan> &List = Spans[CU];
2881 // Emit size of content not including length itself.
2882 unsigned ContentSize
2883 = sizeof(int16_t) // DWARF ARange version number
2884 + sizeof(int32_t) // Offset of CU in the .debug_info section
2885 + sizeof(int8_t) // Pointer Size (in bytes)
2886 + sizeof(int8_t); // Segment Size (in bytes)
2888 unsigned TupleSize = PtrSize * 2;
2890 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2891 unsigned Padding = 0;
2892 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2895 ContentSize += Padding;
2896 ContentSize += (List.size() + 1) * TupleSize;
2898 // For each compile unit, write the list of spans it covers.
2899 Asm->OutStreamer.AddComment("Length of ARange Set");
2900 Asm->EmitInt32(ContentSize);
2901 Asm->OutStreamer.AddComment("DWARF Arange version number");
2902 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2903 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2904 Asm->EmitSectionOffset(
2905 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2906 DwarfInfoSectionSym);
2907 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2908 Asm->EmitInt8(PtrSize);
2909 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2912 for (unsigned n = 0; n < Padding; n++)
2913 Asm->EmitInt8(0xff);
2915 for (unsigned n = 0; n < List.size(); n++) {
2916 const ArangeSpan &Span = List[n];
2917 Asm->EmitLabelReference(Span.Start, PtrSize);
2919 // Calculate the size as being from the span start to it's end.
2921 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2923 // For symbols without an end marker (e.g. common), we
2924 // write a single arange entry containing just that one symbol.
2925 uint64_t Size = SymSize[Span.Start];
2929 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2933 Asm->OutStreamer.AddComment("ARange terminator");
2934 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2935 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2939 // Emit visible names into a debug ranges section.
2940 void DwarfDebug::emitDebugRanges() {
2941 // Start the dwarf ranges section.
2943 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2944 unsigned char Size = Asm->getDataLayout().getPointerSize();
2945 for (SmallVectorImpl<const MCSymbol *>::iterator
2946 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2949 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2951 Asm->OutStreamer.EmitIntValue(0, Size);
2955 // Emit visible names into a debug macinfo section.
2956 void DwarfDebug::emitDebugMacInfo() {
2957 if (const MCSection *LineInfo =
2958 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2959 // Start the dwarf macinfo section.
2960 Asm->OutStreamer.SwitchSection(LineInfo);
2964 // DWARF5 Experimental Separate Dwarf emitters.
2966 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2967 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2968 // DW_AT_ranges_base, DW_AT_addr_base.
2969 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2971 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2972 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2973 Asm, this, &SkeletonHolder);
2975 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2976 CU->getNode().getSplitDebugFilename());
2978 // Relocate to the beginning of the addr_base section, else 0 for the
2979 // beginning of the one for this compile unit.
2980 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2981 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2982 DwarfAddrSectionSym);
2984 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2986 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2987 // into an entity. We're using 0, or a NULL label for this.
2988 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2990 // DW_AT_stmt_list is a offset of line number information for this
2991 // compile unit in debug_line section.
2992 // FIXME: Should handle multiple compile units.
2993 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2994 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
2995 DwarfLineSectionSym);
2997 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2999 if (!CompilationDir.empty())
3000 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3002 // Flags to let the linker know we have emitted new style pubnames.
3003 if (GenerateGnuPubSections) {
3004 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3005 NewCU->addSectionLabel(
3006 Die, dwarf::DW_AT_GNU_pubnames,
3007 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
3009 NewCU->addSectionDelta(
3010 Die, dwarf::DW_AT_GNU_pubnames,
3011 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
3012 DwarfGnuPubNamesSectionSym);
3014 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3015 NewCU->addSectionLabel(
3016 Die, dwarf::DW_AT_GNU_pubtypes,
3017 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3019 NewCU->addSectionDelta(
3020 Die, dwarf::DW_AT_GNU_pubtypes,
3021 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3022 DwarfGnuPubTypesSectionSym);
3025 // Flag if we've emitted any ranges and their location for the compile unit.
3026 if (DebugRangeSymbols.size()) {
3027 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3028 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_ranges_base,
3029 DwarfDebugRangeSectionSym);
3031 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
3035 SkeletonHolder.addUnit(NewCU);
3036 SkeletonCUs.push_back(NewCU);
3041 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3042 assert(useSplitDwarf() && "No split dwarf debug info?");
3043 emitAbbrevs(Section, &SkeletonAbbrevs);
3046 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3047 // compile units that would normally be in debug_info.
3048 void DwarfDebug::emitDebugInfoDWO() {
3049 assert(useSplitDwarf() && "No split dwarf debug info?");
3050 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3051 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3052 DwarfAbbrevDWOSectionSym);
3055 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3056 // abbreviations for the .debug_info.dwo section.
3057 void DwarfDebug::emitDebugAbbrevDWO() {
3058 assert(useSplitDwarf() && "No split dwarf?");
3059 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3063 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3064 // string section and is identical in format to traditional .debug_str
3066 void DwarfDebug::emitDebugStrDWO() {
3067 assert(useSplitDwarf() && "No split dwarf?");
3068 const MCSection *OffSec = Asm->getObjFileLowering()
3069 .getDwarfStrOffDWOSection();
3070 const MCSymbol *StrSym = DwarfStrSectionSym;
3071 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),