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"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
59 Default, Enable, Disable
63 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
64 cl::desc("Output prototype dwarf accelerator tables."),
66 clEnumVal(Default, "Default for platform"),
67 clEnumVal(Enable, "Enabled"),
68 clEnumVal(Disable, "Disabled"),
72 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
73 cl::desc("Compatibility with Darwin gdb."),
75 clEnumVal(Default, "Default for platform"),
76 clEnumVal(Enable, "Enabled"),
77 clEnumVal(Disable, "Disabled"),
81 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
82 cl::desc("Output prototype dwarf split debug info."),
84 clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"),
91 const char *DWARFGroupName = "DWARF Emission";
92 const char *DbgTimerName = "DWARF Debug Writer";
93 } // end anonymous namespace
95 //===----------------------------------------------------------------------===//
97 // Configuration values for initial hash set sizes (log2).
99 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
103 DIType DbgVariable::getType() const {
104 DIType Ty = Var.getType();
105 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
106 // addresses instead.
107 if (Var.isBlockByrefVariable()) {
108 /* Byref variables, in Blocks, are declared by the programmer as
109 "SomeType VarName;", but the compiler creates a
110 __Block_byref_x_VarName struct, and gives the variable VarName
111 either the struct, or a pointer to the struct, as its type. This
112 is necessary for various behind-the-scenes things the compiler
113 needs to do with by-reference variables in blocks.
115 However, as far as the original *programmer* is concerned, the
116 variable should still have type 'SomeType', as originally declared.
118 The following function dives into the __Block_byref_x_VarName
119 struct to find the original type of the variable. This will be
120 passed back to the code generating the type for the Debug
121 Information Entry for the variable 'VarName'. 'VarName' will then
122 have the original type 'SomeType' in its debug information.
124 The original type 'SomeType' will be the type of the field named
125 'VarName' inside the __Block_byref_x_VarName struct.
127 NOTE: In order for this to not completely fail on the debugger
128 side, the Debug Information Entry for the variable VarName needs to
129 have a DW_AT_location that tells the debugger how to unwind through
130 the pointers and __Block_byref_x_VarName struct to find the actual
131 value of the variable. The function addBlockByrefType does this. */
133 unsigned tag = Ty.getTag();
135 if (tag == dwarf::DW_TAG_pointer_type) {
136 DIDerivedType DTy = DIDerivedType(Ty);
137 subType = DTy.getTypeDerivedFrom();
140 DICompositeType blockStruct = DICompositeType(subType);
141 DIArray Elements = blockStruct.getTypeArray();
143 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
144 DIDescriptor Element = Elements.getElement(i);
145 DIDerivedType DT = DIDerivedType(Element);
146 if (getName() == DT.getName())
147 return (DT.getTypeDerivedFrom());
153 } // end llvm namespace
155 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
156 : Asm(A), MMI(Asm->MMI), FirstCU(0),
157 AbbreviationsSet(InitAbbreviationsSetSize),
158 SourceIdMap(DIEValueAllocator),
159 PrevLabel(NULL), GlobalCUIndexCount(0),
160 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
163 SkeletonAbbrevSet(InitAbbreviationsSetSize),
164 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
167 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
168 DwarfStrSectionSym = TextSectionSym = 0;
169 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
170 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
171 FunctionBeginSym = FunctionEndSym = 0;
173 // Turn on accelerator tables and older gdb compatibility
175 bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
176 if (DarwinGDBCompat == Default) {
178 IsDarwinGDBCompat = true;
180 IsDarwinGDBCompat = false;
182 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
184 if (DwarfAccelTables == Default) {
186 HasDwarfAccelTables = true;
188 HasDwarfAccelTables = false;
190 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
192 if (SplitDwarf == Default)
193 HasSplitDwarf = false;
195 HasSplitDwarf = SplitDwarf == Enable ? true : false;
198 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
202 DwarfDebug::~DwarfDebug() {
205 // Switch to the specified MCSection and emit an assembler
206 // temporary label to it if SymbolStem is specified.
207 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
208 const char *SymbolStem = 0) {
209 Asm->OutStreamer.SwitchSection(Section);
210 if (!SymbolStem) return 0;
212 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
213 Asm->OutStreamer.EmitLabel(TmpSym);
217 MCSymbol *DwarfUnits::getStringPoolSym() {
218 return Asm->GetTempSymbol(StringPref);
221 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
222 std::pair<MCSymbol*, unsigned> &Entry =
223 StringPool.GetOrCreateValue(Str).getValue();
224 if (Entry.first) return Entry.first;
226 Entry.second = NextStringPoolNumber++;
227 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
230 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
231 std::pair<MCSymbol*, unsigned> &Entry =
232 StringPool.GetOrCreateValue(Str).getValue();
233 if (Entry.first) return Entry.second;
235 Entry.second = NextStringPoolNumber++;
236 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
240 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
241 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
242 if (Entry.first) return Entry.second;
244 Entry.second = NextAddrPoolNumber++;
249 // Define a unique number for the abbreviation.
251 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
252 // Profile the node so that we can make it unique.
256 // Check the set for priors.
257 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
259 // If it's newly added.
260 if (InSet == &Abbrev) {
261 // Add to abbreviation list.
262 Abbreviations->push_back(&Abbrev);
264 // Assign the vector position + 1 as its number.
265 Abbrev.setNumber(Abbreviations->size());
267 // Assign existing abbreviation number.
268 Abbrev.setNumber(InSet->getNumber());
272 // If special LLVM prefix that is used to inform the asm
273 // printer to not emit usual symbol prefix before the symbol name is used then
274 // return linkage name after skipping this special LLVM prefix.
275 static StringRef getRealLinkageName(StringRef LinkageName) {
277 if (LinkageName.startswith(StringRef(&One, 1)))
278 return LinkageName.substr(1);
282 static bool isObjCClass(StringRef Name) {
283 return Name.startswith("+") || Name.startswith("-");
286 static bool hasObjCCategory(StringRef Name) {
287 if (!isObjCClass(Name)) return false;
289 size_t pos = Name.find(')');
290 if (pos != std::string::npos) {
291 if (Name[pos+1] != ' ') return false;
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
314 // Add the various names to the Dwarf accelerator table names.
315 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
317 if (!SP.isDefinition()) return;
319 TheCU->addAccelName(SP.getName(), Die);
321 // If the linkage name is different than the name, go ahead and output
322 // that as well into the name table.
323 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
324 TheCU->addAccelName(SP.getLinkageName(), Die);
326 // If this is an Objective-C selector name add it to the ObjC accelerator
328 if (isObjCClass(SP.getName())) {
329 StringRef Class, Category;
330 getObjCClassCategory(SP.getName(), Class, Category);
331 TheCU->addAccelObjC(Class, Die);
333 TheCU->addAccelObjC(Category, Die);
334 // Also add the base method name to the name table.
335 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
339 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
340 // and DW_AT_high_pc attributes. If there are global variables in this
341 // scope then create and insert DIEs for these variables.
342 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
343 const MDNode *SPNode) {
344 DIE *SPDie = SPCU->getDIE(SPNode);
346 assert(SPDie && "Unable to find subprogram DIE!");
347 DISubprogram SP(SPNode);
349 // If we're updating an abstract DIE, then we will be adding the children and
350 // object pointer later on. But what we don't want to do is process the
351 // concrete DIE twice.
352 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
353 // Pick up abstract subprogram DIE.
354 SPDie = new DIE(dwarf::DW_TAG_subprogram);
355 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
356 dwarf::DW_FORM_ref4, AbsSPDIE);
359 DISubprogram SPDecl = SP.getFunctionDeclaration();
360 if (!SPDecl.isSubprogram()) {
361 // There is not any need to generate specification DIE for a function
362 // defined at compile unit level. If a function is defined inside another
363 // function then gdb prefers the definition at top level and but does not
364 // expect specification DIE in parent function. So avoid creating
365 // specification DIE for a function defined inside a function.
366 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
367 !SP.getContext().isFile() &&
368 !isSubprogramContext(SP.getContext())) {
369 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
372 DICompositeType SPTy = SP.getType();
373 DIArray Args = SPTy.getTypeArray();
374 unsigned SPTag = SPTy.getTag();
375 if (SPTag == dwarf::DW_TAG_subroutine_type)
376 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
377 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
378 DIType ATy = DIType(Args.getElement(i));
379 SPCU->addType(Arg, ATy);
380 if (ATy.isArtificial())
381 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
382 if (ATy.isObjectPointer())
383 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
384 dwarf::DW_FORM_ref4, Arg);
385 SPDie->addChild(Arg);
387 DIE *SPDeclDie = SPDie;
388 SPDie = new DIE(dwarf::DW_TAG_subprogram);
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
390 dwarf::DW_FORM_ref4, SPDeclDie);
396 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
397 Asm->GetTempSymbol("func_begin",
398 Asm->getFunctionNumber()));
399 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
400 Asm->GetTempSymbol("func_end",
401 Asm->getFunctionNumber()));
402 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
403 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
404 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
406 // Add name to the name table, we do this here because we're guaranteed
407 // to have concrete versions of our DW_TAG_subprogram nodes.
408 addSubprogramNames(SPCU, SP, SPDie);
413 // Construct new DW_TAG_lexical_block for this scope and attach
414 // DW_AT_low_pc/DW_AT_high_pc labels.
415 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
416 LexicalScope *Scope) {
417 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
418 if (Scope->isAbstractScope())
421 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
425 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
426 if (Ranges.size() > 1) {
427 // .debug_range section has not been laid out yet. Emit offset in
428 // .debug_range as a uint, size 4, for now. emitDIE will handle
429 // DW_AT_ranges appropriately.
430 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
431 DebugRangeSymbols.size()
432 * Asm->getDataLayout().getPointerSize());
433 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
434 RE = Ranges.end(); RI != RE; ++RI) {
435 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
436 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
438 DebugRangeSymbols.push_back(NULL);
439 DebugRangeSymbols.push_back(NULL);
443 MCSymbol *Start = getLabelBeforeInsn(RI->first);
444 MCSymbol *End = getLabelAfterInsn(RI->second);
446 if (End == 0) return 0;
448 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
449 assert(End->isDefined() && "Invalid end label for an inlined scope!");
451 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
452 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
457 // This scope represents inlined body of a function. Construct DIE to
458 // represent this concrete inlined copy of the function.
459 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
460 LexicalScope *Scope) {
461 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
462 assert(Ranges.empty() == false &&
463 "LexicalScope does not have instruction markers!");
465 if (!Scope->getScopeNode())
467 DIScope DS(Scope->getScopeNode());
468 DISubprogram InlinedSP = getDISubprogram(DS);
469 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
471 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
475 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
476 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
477 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
479 if (StartLabel == 0 || EndLabel == 0) {
480 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
482 assert(StartLabel->isDefined() &&
483 "Invalid starting label for an inlined scope!");
484 assert(EndLabel->isDefined() &&
485 "Invalid end label for an inlined scope!");
487 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
488 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
489 dwarf::DW_FORM_ref4, OriginDIE);
491 if (Ranges.size() > 1) {
492 // .debug_range section has not been laid out yet. Emit offset in
493 // .debug_range as a uint, size 4, for now. emitDIE will handle
494 // DW_AT_ranges appropriately.
495 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
496 DebugRangeSymbols.size()
497 * Asm->getDataLayout().getPointerSize());
498 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
499 RE = Ranges.end(); RI != RE; ++RI) {
500 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
501 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
503 DebugRangeSymbols.push_back(NULL);
504 DebugRangeSymbols.push_back(NULL);
506 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
507 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
510 InlinedSubprogramDIEs.insert(OriginDIE);
512 // Track the start label for this inlined function.
513 //.debug_inlined section specification does not clearly state how
514 // to emit inlined scope that is split into multiple instruction ranges.
515 // For now, use first instruction range and emit low_pc/high_pc pair and
516 // corresponding .debug_inlined section entry for this pair.
517 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
518 I = InlineInfo.find(InlinedSP);
520 if (I == InlineInfo.end()) {
521 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
522 InlinedSPNodes.push_back(InlinedSP);
524 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
526 DILocation DL(Scope->getInlinedAt());
527 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
528 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
529 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
531 // Add name to the name table, we do this here because we're guaranteed
532 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
533 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
538 // Construct a DIE for this scope.
539 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
540 if (!Scope || !Scope->getScopeNode())
543 DIScope DS(Scope->getScopeNode());
544 // Early return to avoid creating dangling variable|scope DIEs.
545 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
549 SmallVector<DIE *, 8> Children;
550 DIE *ObjectPointer = NULL;
552 // Collect arguments for current function.
553 if (LScopes.isCurrentFunctionScope(Scope))
554 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
555 if (DbgVariable *ArgDV = CurrentFnArguments[i])
557 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
558 Children.push_back(Arg);
559 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
562 // Collect lexical scope children first.
563 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
564 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
566 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
567 Children.push_back(Variable);
568 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
570 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
571 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
572 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
573 Children.push_back(Nested);
574 DIE *ScopeDIE = NULL;
575 if (Scope->getInlinedAt())
576 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
577 else if (DS.isSubprogram()) {
578 ProcessedSPNodes.insert(DS);
579 if (Scope->isAbstractScope()) {
580 ScopeDIE = TheCU->getDIE(DS);
581 // Note down abstract DIE.
583 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
586 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
589 // There is no need to emit empty lexical block DIE.
590 if (Children.empty())
592 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
595 if (!ScopeDIE) return NULL;
598 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
599 E = Children.end(); I != E; ++I)
600 ScopeDIE->addChild(*I);
602 if (DS.isSubprogram() && ObjectPointer != NULL)
603 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
604 dwarf::DW_FORM_ref4, ObjectPointer);
606 if (DS.isSubprogram())
607 TheCU->addPubTypes(DISubprogram(DS));
612 // Look up the source id with the given directory and source file names.
613 // If none currently exists, create a new id and insert it in the
614 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
616 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
618 // If FE did not provide a file name, then assume stdin.
619 if (FileName.empty())
620 return getOrCreateSourceID("<stdin>", StringRef());
622 // TODO: this might not belong here. See if we can factor this better.
623 if (DirName == CompilationDir)
626 unsigned SrcId = SourceIdMap.size()+1;
628 // We look up the file/dir pair by concatenating them with a zero byte.
629 SmallString<128> NamePair;
631 NamePair += '\0'; // Zero bytes are not allowed in paths.
632 NamePair += FileName;
634 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
635 if (Ent.getValue() != SrcId)
636 return Ent.getValue();
638 // Print out a .file directive to specify files for .loc directives.
639 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
644 // Create new CompileUnit for the given metadata node with tag
645 // DW_TAG_compile_unit.
646 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
647 DICompileUnit DIUnit(N);
648 StringRef FN = DIUnit.getFilename();
649 CompilationDir = DIUnit.getDirectory();
650 // Call this to emit a .file directive if it wasn't emitted for the source
651 // file this CU comes from yet.
652 getOrCreateSourceID(FN, CompilationDir);
654 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
655 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
656 DIUnit.getLanguage(), Die, Asm,
658 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
659 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
660 DIUnit.getLanguage());
661 NewCU->addString(Die, dwarf::DW_AT_name, FN);
662 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
663 // into an entity. We're using 0 (or a NULL label) for this.
664 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
665 // DW_AT_stmt_list is a offset of line number information for this
666 // compile unit in debug_line section.
667 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
668 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
669 Asm->GetTempSymbol("section_line"));
671 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
673 if (!CompilationDir.empty())
674 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
675 if (DIUnit.isOptimized())
676 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
678 StringRef Flags = DIUnit.getFlags();
680 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
682 if (unsigned RVer = DIUnit.getRunTimeVersion())
683 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
684 dwarf::DW_FORM_data1, RVer);
689 if (useSplitDwarf()) {
690 // This should be a unique identifier when we want to build .dwp files.
691 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
692 // Now construct the skeleton CU associated.
693 constructSkeletonCU(N);
696 InfoHolder.addUnit(NewCU);
698 CUMap.insert(std::make_pair(N, NewCU));
702 // Construct subprogram DIE.
703 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
705 CompileUnit *&CURef = SPMap[N];
711 if (!SP.isDefinition())
712 // This is a method declaration which will be handled while constructing
716 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
719 TheCU->insertDIE(N, SubprogramDie);
721 // Add to context owner.
722 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
727 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
728 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
729 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
730 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
731 const MDNode *N = NMD->getOperand(i);
732 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
733 constructSubprogramDIE(CU, N);
736 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
737 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
738 const MDNode *N = NMD->getOperand(i);
739 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
740 CU->createGlobalVariableDIE(N);
743 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
744 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
745 DIType Ty(NMD->getOperand(i));
746 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
747 CU->getOrCreateTypeDIE(Ty);
750 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
751 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
752 DIType Ty(NMD->getOperand(i));
753 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
754 CU->getOrCreateTypeDIE(Ty);
758 // Collect debug info using DebugInfoFinder.
759 // FIXME - Remove this when dragonegg switches to DIBuilder.
760 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
761 DebugInfoFinder DbgFinder;
762 DbgFinder.processModule(*M);
764 bool HasDebugInfo = false;
765 // Scan all the compile-units to see if there are any marked as the main
766 // unit. If not, we do not generate debug info.
767 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
768 E = DbgFinder.compile_unit_end(); I != E; ++I) {
769 if (DICompileUnit(*I).isMain()) {
774 if (!HasDebugInfo) return false;
776 // Create all the compile unit DIEs.
777 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
778 E = DbgFinder.compile_unit_end(); I != E; ++I)
779 constructCompileUnit(*I);
781 // Create DIEs for each global variable.
782 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
783 E = DbgFinder.global_variable_end(); I != E; ++I) {
784 const MDNode *N = *I;
785 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
786 CU->createGlobalVariableDIE(N);
789 // Create DIEs for each subprogram.
790 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
791 E = DbgFinder.subprogram_end(); I != E; ++I) {
792 const MDNode *N = *I;
793 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
794 constructSubprogramDIE(CU, N);
800 // Emit all Dwarf sections that should come prior to the content. Create
801 // global DIEs and emit initial debug info sections. This is invoked by
802 // the target AsmPrinter.
803 void DwarfDebug::beginModule() {
804 if (DisableDebugInfoPrinting)
807 const Module *M = MMI->getModule();
809 // If module has named metadata anchors then use them, otherwise scan the
810 // module using debug info finder to collect debug info.
811 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
813 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
814 DICompileUnit CUNode(CU_Nodes->getOperand(i));
815 CompileUnit *CU = constructCompileUnit(CUNode);
816 DIArray GVs = CUNode.getGlobalVariables();
817 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
818 CU->createGlobalVariableDIE(GVs.getElement(i));
819 DIArray SPs = CUNode.getSubprograms();
820 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
821 constructSubprogramDIE(CU, SPs.getElement(i));
822 DIArray EnumTypes = CUNode.getEnumTypes();
823 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
824 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
825 DIArray RetainedTypes = CUNode.getRetainedTypes();
826 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
827 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
829 } else if (!collectLegacyDebugInfo(M))
832 collectInfoFromNamedMDNodes(M);
834 // Tell MMI that we have debug info.
835 MMI->setDebugInfoAvailability(true);
837 // Prime section data.
838 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
841 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
842 void DwarfDebug::computeInlinedDIEs() {
843 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
844 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
845 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
847 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
849 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
850 AE = AbstractSPDies.end(); AI != AE; ++AI) {
851 DIE *ISP = AI->second;
852 if (InlinedSubprogramDIEs.count(ISP))
854 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
858 // Collect info for variables that were optimized out.
859 void DwarfDebug::collectDeadVariables() {
860 const Module *M = MMI->getModule();
861 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
863 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
864 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
865 DICompileUnit TheCU(CU_Nodes->getOperand(i));
866 DIArray Subprograms = TheCU.getSubprograms();
867 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
868 DISubprogram SP(Subprograms.getElement(i));
869 if (ProcessedSPNodes.count(SP) != 0) continue;
870 if (!SP.Verify()) continue;
871 if (!SP.isDefinition()) continue;
872 DIArray Variables = SP.getVariables();
873 if (Variables.getNumElements() == 0) continue;
875 LexicalScope *Scope =
876 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
877 DeadFnScopeMap[SP] = Scope;
879 // Construct subprogram DIE and add variables DIEs.
880 CompileUnit *SPCU = CUMap.lookup(TheCU);
881 assert(SPCU && "Unable to find Compile Unit!");
882 constructSubprogramDIE(SPCU, SP);
883 DIE *ScopeDIE = SPCU->getDIE(SP);
884 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
885 DIVariable DV(Variables.getElement(vi));
886 if (!DV.Verify()) continue;
887 DbgVariable *NewVar = new DbgVariable(DV, NULL);
888 if (DIE *VariableDIE =
889 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
890 ScopeDIE->addChild(VariableDIE);
895 DeleteContainerSeconds(DeadFnScopeMap);
898 void DwarfDebug::finalizeModuleInfo() {
899 // Collect info for variables that were optimized out.
900 collectDeadVariables();
902 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
903 computeInlinedDIEs();
905 // Emit DW_AT_containing_type attribute to connect types with their
906 // vtable holding type.
907 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
908 CUE = CUMap.end(); CUI != CUE; ++CUI) {
909 CompileUnit *TheCU = CUI->second;
910 TheCU->constructContainingTypeDIEs();
913 // Compute DIE offsets and sizes.
914 InfoHolder.computeSizeAndOffsets();
916 SkeletonHolder.computeSizeAndOffsets();
919 void DwarfDebug::endSections() {
920 // Standard sections final addresses.
921 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
922 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
923 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
924 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
926 // End text sections.
927 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
928 Asm->OutStreamer.SwitchSection(SectionMap[I]);
929 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
933 // Emit all Dwarf sections that should come after the content.
934 void DwarfDebug::endModule() {
936 if (!FirstCU) return;
938 // End any existing sections.
939 // TODO: Does this need to happen?
942 // Finalize the debug info for the module.
943 finalizeModuleInfo();
945 // Emit initial sections.
948 if (!useSplitDwarf()) {
949 // Emit all the DIEs into a debug info section.
952 // Corresponding abbreviations into a abbrev section.
955 // Emit info into a debug loc section.
958 // Emit info into a debug aranges section.
961 // Emit info into a debug ranges section.
964 // Emit info into a debug macinfo section.
968 // TODO: When we don't need the option anymore we
969 // can remove all of the code that this section
971 if (useDarwinGDBCompat())
972 emitDebugInlineInfo();
974 // TODO: Fill this in for separated debug sections and separate
975 // out information into new sections.
977 // Emit the debug info section and compile units.
981 // Corresponding abbreviations into a abbrev section.
983 emitDebugAbbrevDWO();
985 // Emit info into a debug loc section.
988 // Emit info into a debug aranges section.
991 // Emit info into a debug ranges section.
994 // Emit info into a debug macinfo section.
997 // Emit DWO addresses.
998 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1000 // Emit inline info.
1001 // TODO: When we don't need the option anymore we
1002 // can remove all of the code that this section
1004 if (useDarwinGDBCompat())
1005 emitDebugInlineInfo();
1008 // Emit info into the dwarf accelerator table sections.
1009 if (useDwarfAccelTables()) {
1012 emitAccelNamespaces();
1016 // Emit info into a debug pubtypes section.
1017 // TODO: When we don't need the option anymore we can
1018 // remove all of the code that adds to the table.
1019 if (useDarwinGDBCompat())
1020 emitDebugPubTypes();
1022 // Finally emit string information into a string table.
1024 if (useSplitDwarf())
1029 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1030 E = CUMap.end(); I != E; ++I)
1035 // Reset these for the next Module if we have one.
1040 // Find abstract variable, if any, associated with Var.
1041 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1042 DebugLoc ScopeLoc) {
1043 LLVMContext &Ctx = DV->getContext();
1044 // More then one inlined variable corresponds to one abstract variable.
1045 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1046 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1048 return AbsDbgVariable;
1050 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1054 AbsDbgVariable = new DbgVariable(Var, NULL);
1055 addScopeVariable(Scope, AbsDbgVariable);
1056 AbstractVariables[Var] = AbsDbgVariable;
1057 return AbsDbgVariable;
1060 // If Var is a current function argument then add it to CurrentFnArguments list.
1061 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1062 DbgVariable *Var, LexicalScope *Scope) {
1063 if (!LScopes.isCurrentFunctionScope(Scope))
1065 DIVariable DV = Var->getVariable();
1066 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1068 unsigned ArgNo = DV.getArgNumber();
1072 size_t Size = CurrentFnArguments.size();
1074 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1075 // llvm::Function argument size is not good indicator of how many
1076 // arguments does the function have at source level.
1078 CurrentFnArguments.resize(ArgNo * 2);
1079 CurrentFnArguments[ArgNo - 1] = Var;
1083 // Collect variable information from side table maintained by MMI.
1085 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1086 SmallPtrSet<const MDNode *, 16> &Processed) {
1087 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1088 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1089 VE = VMap.end(); VI != VE; ++VI) {
1090 const MDNode *Var = VI->first;
1092 Processed.insert(Var);
1094 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1096 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1098 // If variable scope is not found then skip this variable.
1102 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1103 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1104 RegVar->setFrameIndex(VP.first);
1105 if (!addCurrentFnArgument(MF, RegVar, Scope))
1106 addScopeVariable(Scope, RegVar);
1108 AbsDbgVariable->setFrameIndex(VP.first);
1112 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1114 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1115 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1116 return MI->getNumOperands() == 3 &&
1117 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1118 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1121 // Get .debug_loc entry for the instruction range starting at MI.
1122 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1123 const MCSymbol *FLabel,
1124 const MCSymbol *SLabel,
1125 const MachineInstr *MI) {
1126 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1128 if (MI->getNumOperands() != 3) {
1129 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1130 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1132 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1133 MachineLocation MLoc;
1134 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1135 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1137 if (MI->getOperand(0).isImm())
1138 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1139 if (MI->getOperand(0).isFPImm())
1140 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1141 if (MI->getOperand(0).isCImm())
1142 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1144 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1147 // Find variables for each lexical scope.
1149 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1150 SmallPtrSet<const MDNode *, 16> &Processed) {
1152 // collection info from MMI table.
1153 collectVariableInfoFromMMITable(MF, Processed);
1155 for (SmallVectorImpl<const MDNode*>::const_iterator
1156 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1158 const MDNode *Var = *UVI;
1159 if (Processed.count(Var))
1162 // History contains relevant DBG_VALUE instructions for Var and instructions
1164 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1165 if (History.empty())
1167 const MachineInstr *MInsn = History.front();
1170 LexicalScope *Scope = NULL;
1171 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1172 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1173 Scope = LScopes.getCurrentFunctionScope();
1175 if (DV.getVersion() <= LLVMDebugVersion9)
1176 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1178 if (MDNode *IA = DV.getInlinedAt())
1179 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1181 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1184 // If variable scope is not found then skip this variable.
1188 Processed.insert(DV);
1189 assert(MInsn->isDebugValue() && "History must begin with debug value");
1190 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1191 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1192 if (!addCurrentFnArgument(MF, RegVar, Scope))
1193 addScopeVariable(Scope, RegVar);
1195 AbsVar->setMInsn(MInsn);
1197 // Simplify ranges that are fully coalesced.
1198 if (History.size() <= 1 || (History.size() == 2 &&
1199 MInsn->isIdenticalTo(History.back()))) {
1200 RegVar->setMInsn(MInsn);
1204 // Handle multiple DBG_VALUE instructions describing one variable.
1205 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1207 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1208 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1209 const MachineInstr *Begin = *HI;
1210 assert(Begin->isDebugValue() && "Invalid History entry");
1212 // Check if DBG_VALUE is truncating a range.
1213 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1214 && !Begin->getOperand(0).getReg())
1217 // Compute the range for a register location.
1218 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1219 const MCSymbol *SLabel = 0;
1222 // If Begin is the last instruction in History then its value is valid
1223 // until the end of the function.
1224 SLabel = FunctionEndSym;
1226 const MachineInstr *End = HI[1];
1227 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1228 << "\t" << *Begin << "\t" << *End << "\n");
1229 if (End->isDebugValue())
1230 SLabel = getLabelBeforeInsn(End);
1232 // End is a normal instruction clobbering the range.
1233 SLabel = getLabelAfterInsn(End);
1234 assert(SLabel && "Forgot label after clobber instruction");
1239 // The value is valid until the next DBG_VALUE or clobber.
1240 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1243 DotDebugLocEntries.push_back(DotDebugLocEntry());
1246 // Collect info for variables that were optimized out.
1247 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1248 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1249 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1250 DIVariable DV(Variables.getElement(i));
1251 if (!DV || !DV.Verify() || !Processed.insert(DV))
1253 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1254 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1258 // Return Label preceding the instruction.
1259 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1260 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1261 assert(Label && "Didn't insert label before instruction");
1265 // Return Label immediately following the instruction.
1266 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1267 return LabelsAfterInsn.lookup(MI);
1270 // Process beginning of an instruction.
1271 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1272 // Check if source location changes, but ignore DBG_VALUE locations.
1273 if (!MI->isDebugValue()) {
1274 DebugLoc DL = MI->getDebugLoc();
1275 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1278 if (DL == PrologEndLoc) {
1279 Flags |= DWARF2_FLAG_PROLOGUE_END;
1280 PrologEndLoc = DebugLoc();
1282 if (PrologEndLoc.isUnknown())
1283 Flags |= DWARF2_FLAG_IS_STMT;
1285 if (!DL.isUnknown()) {
1286 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1287 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1289 recordSourceLine(0, 0, 0, 0);
1293 // Insert labels where requested.
1294 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1295 LabelsBeforeInsn.find(MI);
1298 if (I == LabelsBeforeInsn.end())
1301 // Label already assigned.
1306 PrevLabel = MMI->getContext().CreateTempSymbol();
1307 Asm->OutStreamer.EmitLabel(PrevLabel);
1309 I->second = PrevLabel;
1312 // Process end of an instruction.
1313 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1314 // Don't create a new label after DBG_VALUE instructions.
1315 // They don't generate code.
1316 if (!MI->isDebugValue())
1319 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1320 LabelsAfterInsn.find(MI);
1323 if (I == LabelsAfterInsn.end())
1326 // Label already assigned.
1330 // We need a label after this instruction.
1332 PrevLabel = MMI->getContext().CreateTempSymbol();
1333 Asm->OutStreamer.EmitLabel(PrevLabel);
1335 I->second = PrevLabel;
1338 // Each LexicalScope has first instruction and last instruction to mark
1339 // beginning and end of a scope respectively. Create an inverse map that list
1340 // scopes starts (and ends) with an instruction. One instruction may start (or
1341 // end) multiple scopes. Ignore scopes that are not reachable.
1342 void DwarfDebug::identifyScopeMarkers() {
1343 SmallVector<LexicalScope *, 4> WorkList;
1344 WorkList.push_back(LScopes.getCurrentFunctionScope());
1345 while (!WorkList.empty()) {
1346 LexicalScope *S = WorkList.pop_back_val();
1348 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1349 if (!Children.empty())
1350 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1351 SE = Children.end(); SI != SE; ++SI)
1352 WorkList.push_back(*SI);
1354 if (S->isAbstractScope())
1357 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1360 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1361 RE = Ranges.end(); RI != RE; ++RI) {
1362 assert(RI->first && "InsnRange does not have first instruction!");
1363 assert(RI->second && "InsnRange does not have second instruction!");
1364 requestLabelBeforeInsn(RI->first);
1365 requestLabelAfterInsn(RI->second);
1370 // Get MDNode for DebugLoc's scope.
1371 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1372 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1373 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1374 return DL.getScope(Ctx);
1377 // Walk up the scope chain of given debug loc and find line number info
1378 // for the function.
1379 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1380 const MDNode *Scope = getScopeNode(DL, Ctx);
1381 DISubprogram SP = getDISubprogram(Scope);
1383 // Check for number of operands since the compatibility is
1385 if (SP->getNumOperands() > 19)
1386 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1388 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1394 // Gather pre-function debug information. Assumes being called immediately
1395 // after the function entry point has been emitted.
1396 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1397 if (!MMI->hasDebugInfo()) return;
1398 LScopes.initialize(*MF);
1399 if (LScopes.empty()) return;
1400 identifyScopeMarkers();
1402 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1403 Asm->getFunctionNumber());
1404 // Assumes in correct section after the entry point.
1405 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1407 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1409 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1410 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1411 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1413 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1415 bool AtBlockEntry = true;
1416 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1418 const MachineInstr *MI = II;
1420 if (MI->isDebugValue()) {
1421 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1423 // Keep track of user variables.
1425 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1427 // Variable is in a register, we need to check for clobbers.
1428 if (isDbgValueInDefinedReg(MI))
1429 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1431 // Check the history of this variable.
1432 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1433 if (History.empty()) {
1434 UserVariables.push_back(Var);
1435 // The first mention of a function argument gets the FunctionBeginSym
1436 // label, so arguments are visible when breaking at function entry.
1438 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1439 DISubprogram(getDISubprogram(DV.getContext()))
1440 .describes(MF->getFunction()))
1441 LabelsBeforeInsn[MI] = FunctionBeginSym;
1443 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1444 const MachineInstr *Prev = History.back();
1445 if (Prev->isDebugValue()) {
1446 // Coalesce identical entries at the end of History.
1447 if (History.size() >= 2 &&
1448 Prev->isIdenticalTo(History[History.size() - 2])) {
1449 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1451 << "\t" << *History[History.size() - 2] << "\n");
1455 // Terminate old register assignments that don't reach MI;
1456 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1457 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1458 isDbgValueInDefinedReg(Prev)) {
1459 // Previous register assignment needs to terminate at the end of
1461 MachineBasicBlock::const_iterator LastMI =
1462 PrevMBB->getLastNonDebugInstr();
1463 if (LastMI == PrevMBB->end()) {
1464 // Drop DBG_VALUE for empty range.
1465 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1466 << "\t" << *Prev << "\n");
1470 // Terminate after LastMI.
1471 History.push_back(LastMI);
1476 History.push_back(MI);
1478 // Not a DBG_VALUE instruction.
1480 AtBlockEntry = false;
1482 // First known non-DBG_VALUE and non-frame setup location marks
1483 // the beginning of the function body.
1484 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1485 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1486 PrologEndLoc = MI->getDebugLoc();
1488 // Check if the instruction clobbers any registers with debug vars.
1489 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1490 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1491 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1493 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1494 AI.isValid(); ++AI) {
1496 const MDNode *Var = LiveUserVar[Reg];
1499 // Reg is now clobbered.
1500 LiveUserVar[Reg] = 0;
1502 // Was MD last defined by a DBG_VALUE referring to Reg?
1503 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1504 if (HistI == DbgValues.end())
1506 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1507 if (History.empty())
1509 const MachineInstr *Prev = History.back();
1510 // Sanity-check: Register assignments are terminated at the end of
1512 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1514 // Is the variable still in Reg?
1515 if (!isDbgValueInDefinedReg(Prev) ||
1516 Prev->getOperand(0).getReg() != Reg)
1518 // Var is clobbered. Make sure the next instruction gets a label.
1519 History.push_back(MI);
1526 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1528 SmallVectorImpl<const MachineInstr*> &History = I->second;
1529 if (History.empty())
1532 // Make sure the final register assignments are terminated.
1533 const MachineInstr *Prev = History.back();
1534 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1535 const MachineBasicBlock *PrevMBB = Prev->getParent();
1536 MachineBasicBlock::const_iterator LastMI =
1537 PrevMBB->getLastNonDebugInstr();
1538 if (LastMI == PrevMBB->end())
1539 // Drop DBG_VALUE for empty range.
1542 // Terminate after LastMI.
1543 History.push_back(LastMI);
1546 // Request labels for the full history.
1547 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1548 const MachineInstr *MI = History[i];
1549 if (MI->isDebugValue())
1550 requestLabelBeforeInsn(MI);
1552 requestLabelAfterInsn(MI);
1556 PrevInstLoc = DebugLoc();
1557 PrevLabel = FunctionBeginSym;
1559 // Record beginning of function.
1560 if (!PrologEndLoc.isUnknown()) {
1561 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1562 MF->getFunction()->getContext());
1563 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1564 FnStartDL.getScope(MF->getFunction()->getContext()),
1565 // We'd like to list the prologue as "not statements" but GDB behaves
1566 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1567 DWARF2_FLAG_IS_STMT);
1571 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1572 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1573 ScopeVariables[LS].push_back(Var);
1574 // Vars.push_back(Var);
1577 // Gather and emit post-function debug information.
1578 void DwarfDebug::endFunction(const MachineFunction *MF) {
1579 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1581 // Define end label for subprogram.
1582 FunctionEndSym = Asm->GetTempSymbol("func_end",
1583 Asm->getFunctionNumber());
1584 // Assumes in correct section after the entry point.
1585 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1587 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1588 collectVariableInfo(MF, ProcessedVars);
1590 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1591 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1592 assert(TheCU && "Unable to find compile unit!");
1594 // Construct abstract scopes.
1595 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1596 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1597 LexicalScope *AScope = AList[i];
1598 DISubprogram SP(AScope->getScopeNode());
1600 // Collect info for variables that were optimized out.
1601 DIArray Variables = SP.getVariables();
1602 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1603 DIVariable DV(Variables.getElement(i));
1604 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1606 // Check that DbgVariable for DV wasn't created earlier, when
1607 // findAbstractVariable() was called for inlined instance of DV.
1608 LLVMContext &Ctx = DV->getContext();
1609 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1610 if (AbstractVariables.lookup(CleanDV))
1612 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1613 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1616 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1617 constructScopeDIE(TheCU, AScope);
1620 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1622 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1623 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1625 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1626 MMI->getFrameMoves()));
1629 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1630 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1631 DeleteContainerPointers(I->second);
1632 ScopeVariables.clear();
1633 DeleteContainerPointers(CurrentFnArguments);
1634 UserVariables.clear();
1636 AbstractVariables.clear();
1637 LabelsBeforeInsn.clear();
1638 LabelsAfterInsn.clear();
1642 // Register a source line with debug info. Returns the unique label that was
1643 // emitted and which provides correspondence to the source line list.
1644 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1650 DIDescriptor Scope(S);
1652 if (Scope.isCompileUnit()) {
1653 DICompileUnit CU(S);
1654 Fn = CU.getFilename();
1655 Dir = CU.getDirectory();
1656 } else if (Scope.isFile()) {
1658 Fn = F.getFilename();
1659 Dir = F.getDirectory();
1660 } else if (Scope.isSubprogram()) {
1662 Fn = SP.getFilename();
1663 Dir = SP.getDirectory();
1664 } else if (Scope.isLexicalBlockFile()) {
1665 DILexicalBlockFile DBF(S);
1666 Fn = DBF.getFilename();
1667 Dir = DBF.getDirectory();
1668 } else if (Scope.isLexicalBlock()) {
1669 DILexicalBlock DB(S);
1670 Fn = DB.getFilename();
1671 Dir = DB.getDirectory();
1673 llvm_unreachable("Unexpected scope info");
1675 Src = getOrCreateSourceID(Fn, Dir);
1677 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1680 //===----------------------------------------------------------------------===//
1682 //===----------------------------------------------------------------------===//
1684 // Compute the size and offset of a DIE.
1686 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1687 // Get the children.
1688 const std::vector<DIE *> &Children = Die->getChildren();
1690 // Record the abbreviation.
1691 assignAbbrevNumber(Die->getAbbrev());
1693 // Get the abbreviation for this DIE.
1694 unsigned AbbrevNumber = Die->getAbbrevNumber();
1695 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1698 Die->setOffset(Offset);
1700 // Start the size with the size of abbreviation code.
1701 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1703 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1704 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1706 // Size the DIE attribute values.
1707 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1708 // Size attribute value.
1709 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1711 // Size the DIE children if any.
1712 if (!Children.empty()) {
1713 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1714 "Children flag not set");
1716 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1717 Offset = computeSizeAndOffset(Children[j], Offset);
1719 // End of children marker.
1720 Offset += sizeof(int8_t);
1723 Die->setSize(Offset - Die->getOffset());
1727 // Compute the size and offset of all the DIEs.
1728 void DwarfUnits::computeSizeAndOffsets() {
1729 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1730 E = CUs.end(); I != E; ++I) {
1732 sizeof(int32_t) + // Length of Compilation Unit Info
1733 sizeof(int16_t) + // DWARF version number
1734 sizeof(int32_t) + // Offset Into Abbrev. Section
1735 sizeof(int8_t); // Pointer Size (in bytes)
1737 computeSizeAndOffset((*I)->getCUDie(), Offset);
1741 // Emit initial Dwarf sections with a label at the start of each one.
1742 void DwarfDebug::emitSectionLabels() {
1743 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1745 // Dwarf sections base addresses.
1746 DwarfInfoSectionSym =
1747 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1748 DwarfAbbrevSectionSym =
1749 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1750 if (useSplitDwarf())
1751 DwarfAbbrevDWOSectionSym =
1752 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1753 "section_abbrev_dwo");
1754 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1756 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1757 emitSectionSym(Asm, MacroInfo);
1759 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1760 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1761 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1762 DwarfStrSectionSym =
1763 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1764 if (useSplitDwarf())
1765 DwarfStrDWOSectionSym =
1766 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1767 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1770 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1771 "section_debug_loc");
1773 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1774 emitSectionSym(Asm, TLOF.getDataSection());
1777 // Recursively emits a debug information entry.
1778 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1779 // Get the abbreviation for this DIE.
1780 unsigned AbbrevNumber = Die->getAbbrevNumber();
1781 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1783 // Emit the code (index) for the abbreviation.
1784 if (Asm->isVerbose())
1785 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1786 Twine::utohexstr(Die->getOffset()) + ":0x" +
1787 Twine::utohexstr(Die->getSize()) + " " +
1788 dwarf::TagString(Abbrev->getTag()));
1789 Asm->EmitULEB128(AbbrevNumber);
1791 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1792 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1794 // Emit the DIE attribute values.
1795 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1796 unsigned Attr = AbbrevData[i].getAttribute();
1797 unsigned Form = AbbrevData[i].getForm();
1798 assert(Form && "Too many attributes for DIE (check abbreviation)");
1800 if (Asm->isVerbose())
1801 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1804 case dwarf::DW_AT_abstract_origin: {
1805 DIEEntry *E = cast<DIEEntry>(Values[i]);
1806 DIE *Origin = E->getEntry();
1807 unsigned Addr = Origin->getOffset();
1808 Asm->EmitInt32(Addr);
1811 case dwarf::DW_AT_ranges: {
1812 // DW_AT_range Value encodes offset in debug_range section.
1813 DIEInteger *V = cast<DIEInteger>(Values[i]);
1815 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1816 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1820 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1822 DwarfDebugRangeSectionSym,
1827 case dwarf::DW_AT_location: {
1828 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1829 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1830 Asm->EmitLabelReference(L->getValue(), 4);
1832 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1834 Values[i]->EmitValue(Asm, Form);
1838 case dwarf::DW_AT_accessibility: {
1839 if (Asm->isVerbose()) {
1840 DIEInteger *V = cast<DIEInteger>(Values[i]);
1841 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1843 Values[i]->EmitValue(Asm, Form);
1847 // Emit an attribute using the defined form.
1848 Values[i]->EmitValue(Asm, Form);
1853 // Emit the DIE children if any.
1854 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1855 const std::vector<DIE *> &Children = Die->getChildren();
1857 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1858 emitDIE(Children[j], Abbrevs);
1860 if (Asm->isVerbose())
1861 Asm->OutStreamer.AddComment("End Of Children Mark");
1866 // Emit the various dwarf units to the unit section USection with
1867 // the abbreviations going into ASection.
1868 void DwarfUnits::emitUnits(DwarfDebug *DD,
1869 const MCSection *USection,
1870 const MCSection *ASection,
1871 const MCSymbol *ASectionSym) {
1872 Asm->OutStreamer.SwitchSection(USection);
1873 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1874 E = CUs.end(); I != E; ++I) {
1875 CompileUnit *TheCU = *I;
1876 DIE *Die = TheCU->getCUDie();
1878 // Emit the compile units header.
1880 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1881 TheCU->getUniqueID()));
1883 // Emit size of content not including length itself
1884 unsigned ContentSize = Die->getSize() +
1885 sizeof(int16_t) + // DWARF version number
1886 sizeof(int32_t) + // Offset Into Abbrev. Section
1887 sizeof(int8_t); // Pointer Size (in bytes)
1889 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1890 Asm->EmitInt32(ContentSize);
1891 Asm->OutStreamer.AddComment("DWARF version number");
1892 Asm->EmitInt16(dwarf::DWARF_VERSION);
1893 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1894 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1896 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1897 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1899 DD->emitDIE(Die, Abbreviations);
1900 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1901 TheCU->getUniqueID()));
1905 // Emit the debug info section.
1906 void DwarfDebug::emitDebugInfo() {
1907 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1909 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1910 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1911 DwarfAbbrevSectionSym);
1914 // Emit the abbreviation section.
1915 void DwarfDebug::emitAbbreviations() {
1916 if (!useSplitDwarf())
1917 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1920 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1923 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1924 std::vector<DIEAbbrev *> *Abbrevs) {
1925 // Check to see if it is worth the effort.
1926 if (!Abbrevs->empty()) {
1927 // Start the debug abbrev section.
1928 Asm->OutStreamer.SwitchSection(Section);
1930 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1931 Asm->OutStreamer.EmitLabel(Begin);
1933 // For each abbrevation.
1934 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1935 // Get abbreviation data
1936 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1938 // Emit the abbrevations code (base 1 index.)
1939 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1941 // Emit the abbreviations data.
1945 // Mark end of abbreviations.
1946 Asm->EmitULEB128(0, "EOM(3)");
1948 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1949 Asm->OutStreamer.EmitLabel(End);
1953 // Emit the last address of the section and the end of the line matrix.
1954 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1955 // Define last address of section.
1956 Asm->OutStreamer.AddComment("Extended Op");
1959 Asm->OutStreamer.AddComment("Op size");
1960 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1961 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1962 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1964 Asm->OutStreamer.AddComment("Section end label");
1966 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1967 Asm->getDataLayout().getPointerSize());
1969 // Mark end of matrix.
1970 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1976 // Emit visible names into a hashed accelerator table section.
1977 void DwarfDebug::emitAccelNames() {
1978 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1979 dwarf::DW_FORM_data4));
1980 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1981 E = CUMap.end(); I != E; ++I) {
1982 CompileUnit *TheCU = I->second;
1983 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1984 for (StringMap<std::vector<DIE*> >::const_iterator
1985 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1986 const char *Name = GI->getKeyData();
1987 const std::vector<DIE *> &Entities = GI->second;
1988 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1989 DE = Entities.end(); DI != DE; ++DI)
1990 AT.AddName(Name, (*DI));
1994 AT.FinalizeTable(Asm, "Names");
1995 Asm->OutStreamer.SwitchSection(
1996 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1997 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1998 Asm->OutStreamer.EmitLabel(SectionBegin);
2000 // Emit the full data.
2001 AT.Emit(Asm, SectionBegin, &InfoHolder);
2004 // Emit objective C classes and categories into a hashed accelerator table
2006 void DwarfDebug::emitAccelObjC() {
2007 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2008 dwarf::DW_FORM_data4));
2009 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2010 E = CUMap.end(); I != E; ++I) {
2011 CompileUnit *TheCU = I->second;
2012 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2013 for (StringMap<std::vector<DIE*> >::const_iterator
2014 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2015 const char *Name = GI->getKeyData();
2016 const std::vector<DIE *> &Entities = GI->second;
2017 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2018 DE = Entities.end(); DI != DE; ++DI)
2019 AT.AddName(Name, (*DI));
2023 AT.FinalizeTable(Asm, "ObjC");
2024 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2025 .getDwarfAccelObjCSection());
2026 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2027 Asm->OutStreamer.EmitLabel(SectionBegin);
2029 // Emit the full data.
2030 AT.Emit(Asm, SectionBegin, &InfoHolder);
2033 // Emit namespace dies into a hashed accelerator table.
2034 void DwarfDebug::emitAccelNamespaces() {
2035 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2036 dwarf::DW_FORM_data4));
2037 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2038 E = CUMap.end(); I != E; ++I) {
2039 CompileUnit *TheCU = I->second;
2040 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2041 for (StringMap<std::vector<DIE*> >::const_iterator
2042 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2043 const char *Name = GI->getKeyData();
2044 const std::vector<DIE *> &Entities = GI->second;
2045 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2046 DE = Entities.end(); DI != DE; ++DI)
2047 AT.AddName(Name, (*DI));
2051 AT.FinalizeTable(Asm, "namespac");
2052 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2053 .getDwarfAccelNamespaceSection());
2054 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2055 Asm->OutStreamer.EmitLabel(SectionBegin);
2057 // Emit the full data.
2058 AT.Emit(Asm, SectionBegin, &InfoHolder);
2061 // Emit type dies into a hashed accelerator table.
2062 void DwarfDebug::emitAccelTypes() {
2063 std::vector<DwarfAccelTable::Atom> Atoms;
2064 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2065 dwarf::DW_FORM_data4));
2066 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2067 dwarf::DW_FORM_data2));
2068 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2069 dwarf::DW_FORM_data1));
2070 DwarfAccelTable AT(Atoms);
2071 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2072 E = CUMap.end(); I != E; ++I) {
2073 CompileUnit *TheCU = I->second;
2074 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2075 = TheCU->getAccelTypes();
2076 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2077 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2078 const char *Name = GI->getKeyData();
2079 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2080 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2081 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2082 AT.AddName(Name, (*DI).first, (*DI).second);
2086 AT.FinalizeTable(Asm, "types");
2087 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2088 .getDwarfAccelTypesSection());
2089 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2090 Asm->OutStreamer.EmitLabel(SectionBegin);
2092 // Emit the full data.
2093 AT.Emit(Asm, SectionBegin, &InfoHolder);
2096 void DwarfDebug::emitDebugPubTypes() {
2097 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2098 E = CUMap.end(); I != E; ++I) {
2099 CompileUnit *TheCU = I->second;
2100 // Start the dwarf pubtypes section.
2101 Asm->OutStreamer.SwitchSection(
2102 Asm->getObjFileLowering().getDwarfPubTypesSection());
2103 Asm->OutStreamer.AddComment("Length of Public Types Info");
2104 Asm->EmitLabelDifference(
2105 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2106 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2108 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2109 TheCU->getUniqueID()));
2111 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2112 Asm->EmitInt16(dwarf::DWARF_VERSION);
2114 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2115 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2116 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2117 TheCU->getUniqueID()),
2118 DwarfInfoSectionSym);
2120 Asm->OutStreamer.AddComment("Compilation Unit Length");
2121 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2122 TheCU->getUniqueID()),
2123 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2124 TheCU->getUniqueID()),
2127 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2128 for (StringMap<DIE*>::const_iterator
2129 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2130 const char *Name = GI->getKeyData();
2131 DIE *Entity = GI->second;
2133 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2134 Asm->EmitInt32(Entity->getOffset());
2136 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2137 // Emit the name with a terminating null byte.
2138 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2141 Asm->OutStreamer.AddComment("End Mark");
2143 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2144 TheCU->getUniqueID()));
2148 // Emit strings into a string section.
2149 void DwarfUnits::emitStrings(const MCSection *StrSection,
2150 const MCSection *OffsetSection = NULL,
2151 const MCSymbol *StrSecSym = NULL) {
2153 if (StringPool.empty()) return;
2155 // Start the dwarf str section.
2156 Asm->OutStreamer.SwitchSection(StrSection);
2158 // Get all of the string pool entries and put them in an array by their ID so
2159 // we can sort them.
2160 SmallVector<std::pair<unsigned,
2161 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2163 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2164 I = StringPool.begin(), E = StringPool.end();
2166 Entries.push_back(std::make_pair(I->second.second, &*I));
2168 array_pod_sort(Entries.begin(), Entries.end());
2170 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2171 // Emit a label for reference from debug information entries.
2172 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2174 // Emit the string itself with a terminating null byte.
2175 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2176 Entries[i].second->getKeyLength()+1));
2179 // If we've got an offset section go ahead and emit that now as well.
2180 if (OffsetSection) {
2181 Asm->OutStreamer.SwitchSection(OffsetSection);
2182 unsigned offset = 0;
2183 unsigned size = 4; // FIXME: DWARF64 is 8.
2184 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2185 Asm->OutStreamer.EmitIntValue(offset, size);
2186 offset += Entries[i].second->getKeyLength() + 1;
2191 // Emit strings into a string section.
2192 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2194 if (AddressPool.empty()) return;
2196 // Start the dwarf addr section.
2197 Asm->OutStreamer.SwitchSection(AddrSection);
2199 // Get all of the string pool entries and put them in an array by their ID so
2200 // we can sort them.
2201 SmallVector<std::pair<unsigned,
2202 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2204 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2205 I = AddressPool.begin(), E = AddressPool.end();
2207 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2209 array_pod_sort(Entries.begin(), Entries.end());
2211 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2212 // Emit a label for reference from debug information entries.
2213 MCSymbol *Sym = Entries[i].second->first;
2215 Asm->EmitLabelReference(Entries[i].second->first,
2216 Asm->getDataLayout().getPointerSize());
2218 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2223 // Emit visible names into a debug str section.
2224 void DwarfDebug::emitDebugStr() {
2225 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2226 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2229 // Emit visible names into a debug loc section.
2230 void DwarfDebug::emitDebugLoc() {
2231 if (DotDebugLocEntries.empty())
2234 for (SmallVector<DotDebugLocEntry, 4>::iterator
2235 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2237 DotDebugLocEntry &Entry = *I;
2238 if (I + 1 != DotDebugLocEntries.end())
2242 // Start the dwarf loc section.
2243 Asm->OutStreamer.SwitchSection(
2244 Asm->getObjFileLowering().getDwarfLocSection());
2245 unsigned char Size = Asm->getDataLayout().getPointerSize();
2246 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2248 for (SmallVector<DotDebugLocEntry, 4>::iterator
2249 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2250 I != E; ++I, ++index) {
2251 DotDebugLocEntry &Entry = *I;
2252 if (Entry.isMerged()) continue;
2253 if (Entry.isEmpty()) {
2254 Asm->OutStreamer.EmitIntValue(0, Size);
2255 Asm->OutStreamer.EmitIntValue(0, Size);
2256 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2258 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2259 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2260 DIVariable DV(Entry.Variable);
2261 Asm->OutStreamer.AddComment("Loc expr size");
2262 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2263 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2264 Asm->EmitLabelDifference(end, begin, 2);
2265 Asm->OutStreamer.EmitLabel(begin);
2266 if (Entry.isInt()) {
2267 DIBasicType BTy(DV.getType());
2269 (BTy.getEncoding() == dwarf::DW_ATE_signed
2270 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2271 Asm->OutStreamer.AddComment("DW_OP_consts");
2272 Asm->EmitInt8(dwarf::DW_OP_consts);
2273 Asm->EmitSLEB128(Entry.getInt());
2275 Asm->OutStreamer.AddComment("DW_OP_constu");
2276 Asm->EmitInt8(dwarf::DW_OP_constu);
2277 Asm->EmitULEB128(Entry.getInt());
2279 } else if (Entry.isLocation()) {
2280 if (!DV.hasComplexAddress())
2282 Asm->EmitDwarfRegOp(Entry.Loc);
2284 // Complex address entry.
2285 unsigned N = DV.getNumAddrElements();
2287 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2288 if (Entry.Loc.getOffset()) {
2290 Asm->EmitDwarfRegOp(Entry.Loc);
2291 Asm->OutStreamer.AddComment("DW_OP_deref");
2292 Asm->EmitInt8(dwarf::DW_OP_deref);
2293 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2294 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2295 Asm->EmitSLEB128(DV.getAddrElement(1));
2297 // If first address element is OpPlus then emit
2298 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2299 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2300 Asm->EmitDwarfRegOp(Loc);
2304 Asm->EmitDwarfRegOp(Entry.Loc);
2307 // Emit remaining complex address elements.
2308 for (; i < N; ++i) {
2309 uint64_t Element = DV.getAddrElement(i);
2310 if (Element == DIBuilder::OpPlus) {
2311 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2312 Asm->EmitULEB128(DV.getAddrElement(++i));
2313 } else if (Element == DIBuilder::OpDeref) {
2314 if (!Entry.Loc.isReg())
2315 Asm->EmitInt8(dwarf::DW_OP_deref);
2317 llvm_unreachable("unknown Opcode found in complex address");
2321 // else ... ignore constant fp. There is not any good way to
2322 // to represent them here in dwarf.
2323 Asm->OutStreamer.EmitLabel(end);
2328 // Emit visible names into a debug aranges section.
2329 void DwarfDebug::emitDebugARanges() {
2330 // Start the dwarf aranges section.
2331 Asm->OutStreamer.SwitchSection(
2332 Asm->getObjFileLowering().getDwarfARangesSection());
2335 // Emit visible names into a debug ranges section.
2336 void DwarfDebug::emitDebugRanges() {
2337 // Start the dwarf ranges section.
2338 Asm->OutStreamer.SwitchSection(
2339 Asm->getObjFileLowering().getDwarfRangesSection());
2340 unsigned char Size = Asm->getDataLayout().getPointerSize();
2341 for (SmallVector<const MCSymbol *, 8>::iterator
2342 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2345 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2347 Asm->OutStreamer.EmitIntValue(0, Size);
2351 // Emit visible names into a debug macinfo section.
2352 void DwarfDebug::emitDebugMacInfo() {
2353 if (const MCSection *LineInfo =
2354 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2355 // Start the dwarf macinfo section.
2356 Asm->OutStreamer.SwitchSection(LineInfo);
2360 // Emit inline info using following format.
2362 // 1. length of section
2363 // 2. Dwarf version number
2366 // Entries (one "entry" for each function that was inlined):
2368 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2369 // otherwise offset into __debug_str for regular function name.
2370 // 2. offset into __debug_str section for regular function name.
2371 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2372 // instances for the function.
2374 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2375 // inlined instance; the die_offset points to the inlined_subroutine die in the
2376 // __debug_info section, and the low_pc is the starting address for the
2377 // inlining instance.
2378 void DwarfDebug::emitDebugInlineInfo() {
2379 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2385 Asm->OutStreamer.SwitchSection(
2386 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2388 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2389 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2390 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2392 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2394 Asm->OutStreamer.AddComment("Dwarf Version");
2395 Asm->EmitInt16(dwarf::DWARF_VERSION);
2396 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2397 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2399 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2400 E = InlinedSPNodes.end(); I != E; ++I) {
2402 const MDNode *Node = *I;
2403 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2404 = InlineInfo.find(Node);
2405 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2406 DISubprogram SP(Node);
2407 StringRef LName = SP.getLinkageName();
2408 StringRef Name = SP.getName();
2410 Asm->OutStreamer.AddComment("MIPS linkage name");
2412 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2413 DwarfStrSectionSym);
2415 Asm->EmitSectionOffset(InfoHolder
2416 .getStringPoolEntry(getRealLinkageName(LName)),
2417 DwarfStrSectionSym);
2419 Asm->OutStreamer.AddComment("Function name");
2420 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2421 DwarfStrSectionSym);
2422 Asm->EmitULEB128(Labels.size(), "Inline count");
2424 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2425 LE = Labels.end(); LI != LE; ++LI) {
2426 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2427 Asm->EmitInt32(LI->second->getOffset());
2429 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2430 Asm->OutStreamer.EmitSymbolValue(LI->first,
2431 Asm->getDataLayout().getPointerSize());
2435 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2438 // DWARF5 Experimental Separate Dwarf emitters.
2440 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2441 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2442 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2443 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2444 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2445 DICompileUnit DIUnit(N);
2446 CompilationDir = DIUnit.getDirectory();
2448 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2449 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2450 DIUnit.getLanguage(), Die, Asm,
2451 this, &SkeletonHolder);
2453 SmallString<16> T(DIUnit.getFilename());
2454 sys::path::replace_extension(T, ".dwo");
2455 StringRef FN = sys::path::filename(T);
2456 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2458 // This should be a unique identifier when we want to build .dwp files.
2459 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2461 // FIXME: The addr base should be relative for each compile unit, however,
2462 // this one is going to be 0 anyhow.
2463 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset, 0);
2465 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2466 // into an entity. We're using 0, or a NULL label for this.
2467 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2469 // DW_AT_stmt_list is a offset of line number information for this
2470 // compile unit in debug_line section.
2471 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2472 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2473 Asm->GetTempSymbol("section_line"));
2475 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2477 if (!CompilationDir.empty())
2478 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2483 SkeletonHolder.addUnit(NewCU);
2488 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2489 Asm->OutStreamer.SwitchSection(Section);
2490 DIE *Die = SkeletonCU->getCUDie();
2492 // Emit the compile units header.
2493 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2494 SkeletonCU->getUniqueID()));
2496 // Emit size of content not including length itself
2497 unsigned ContentSize = Die->getSize() +
2498 sizeof(int16_t) + // DWARF version number
2499 sizeof(int32_t) + // Offset Into Abbrev. Section
2500 sizeof(int8_t); // Pointer Size (in bytes)
2502 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2503 Asm->EmitInt32(ContentSize);
2504 Asm->OutStreamer.AddComment("DWARF version number");
2505 Asm->EmitInt16(dwarf::DWARF_VERSION);
2506 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2508 const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2509 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2510 DwarfAbbrevSectionSym);
2511 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2512 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2514 emitDIE(Die, &SkeletonAbbrevs);
2515 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2516 SkeletonCU->getUniqueID()));
2519 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2520 assert(useSplitDwarf() && "No split dwarf debug info?");
2521 emitAbbrevs(Section, &SkeletonAbbrevs);
2524 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2525 // compile units that would normally be in debug_info.
2526 void DwarfDebug::emitDebugInfoDWO() {
2527 assert(useSplitDwarf() && "No split dwarf debug info?");
2528 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2529 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2530 DwarfAbbrevDWOSectionSym);
2533 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2534 // abbreviations for the .debug_info.dwo section.
2535 void DwarfDebug::emitDebugAbbrevDWO() {
2536 assert(useSplitDwarf() && "No split dwarf?");
2537 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2541 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2542 // string section and is identical in format to traditional .debug_str
2544 void DwarfDebug::emitDebugStrDWO() {
2545 assert(useSplitDwarf() && "No split dwarf?");
2546 const MCSection *OffSec = Asm->getObjFileLowering()
2547 .getDwarfStrOffDWOSection();
2548 const MCSymbol *StrSym = DwarfStrSectionSym;
2549 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),