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);
666 // Define start line table label for each Compile Unit.
667 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
668 NewCU->getUniqueID());
669 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
670 NewCU->getUniqueID());
672 // DW_AT_stmt_list is a offset of line number information for this
673 // compile unit in debug_line section.
674 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
675 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
677 else if (NewCU->getUniqueID() == 0)
678 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
680 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
681 LineTableStartSym, Asm->GetTempSymbol("section_line"));
683 if (!CompilationDir.empty())
684 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
685 if (DIUnit.isOptimized())
686 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
688 StringRef Flags = DIUnit.getFlags();
690 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
692 if (unsigned RVer = DIUnit.getRunTimeVersion())
693 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
694 dwarf::DW_FORM_data1, RVer);
699 if (useSplitDwarf()) {
700 // This should be a unique identifier when we want to build .dwp files.
701 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
702 // Now construct the skeleton CU associated.
703 constructSkeletonCU(N);
706 InfoHolder.addUnit(NewCU);
708 CUMap.insert(std::make_pair(N, NewCU));
712 // Construct subprogram DIE.
713 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
715 CompileUnit *&CURef = SPMap[N];
721 if (!SP.isDefinition())
722 // This is a method declaration which will be handled while constructing
726 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
729 TheCU->insertDIE(N, SubprogramDie);
731 // Add to context owner.
732 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
737 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
738 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
739 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
740 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
741 const MDNode *N = NMD->getOperand(i);
742 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
743 constructSubprogramDIE(CU, N);
746 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
747 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
748 const MDNode *N = NMD->getOperand(i);
749 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
750 CU->createGlobalVariableDIE(N);
753 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
754 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
755 DIType Ty(NMD->getOperand(i));
756 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
757 CU->getOrCreateTypeDIE(Ty);
760 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
761 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
762 DIType Ty(NMD->getOperand(i));
763 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
764 CU->getOrCreateTypeDIE(Ty);
768 // Collect debug info using DebugInfoFinder.
769 // FIXME - Remove this when dragonegg switches to DIBuilder.
770 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
771 DebugInfoFinder DbgFinder;
772 DbgFinder.processModule(*M);
774 bool HasDebugInfo = false;
775 // Scan all the compile-units to see if there are any marked as the main
776 // unit. If not, we do not generate debug info.
777 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
778 E = DbgFinder.compile_unit_end(); I != E; ++I) {
779 if (DICompileUnit(*I).isMain()) {
784 if (!HasDebugInfo) return false;
786 // Create all the compile unit DIEs.
787 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
788 E = DbgFinder.compile_unit_end(); I != E; ++I)
789 constructCompileUnit(*I);
791 // Create DIEs for each global variable.
792 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
793 E = DbgFinder.global_variable_end(); I != E; ++I) {
794 const MDNode *N = *I;
795 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
796 CU->createGlobalVariableDIE(N);
799 // Create DIEs for each subprogram.
800 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
801 E = DbgFinder.subprogram_end(); I != E; ++I) {
802 const MDNode *N = *I;
803 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
804 constructSubprogramDIE(CU, N);
810 // Emit all Dwarf sections that should come prior to the content. Create
811 // global DIEs and emit initial debug info sections. This is invoked by
812 // the target AsmPrinter.
813 void DwarfDebug::beginModule() {
814 if (DisableDebugInfoPrinting)
817 const Module *M = MMI->getModule();
819 // If module has named metadata anchors then use them, otherwise scan the
820 // module using debug info finder to collect debug info.
821 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
823 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
824 DICompileUnit CUNode(CU_Nodes->getOperand(i));
825 CompileUnit *CU = constructCompileUnit(CUNode);
826 DIArray GVs = CUNode.getGlobalVariables();
827 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
828 CU->createGlobalVariableDIE(GVs.getElement(i));
829 DIArray SPs = CUNode.getSubprograms();
830 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
831 constructSubprogramDIE(CU, SPs.getElement(i));
832 DIArray EnumTypes = CUNode.getEnumTypes();
833 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
834 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
835 DIArray RetainedTypes = CUNode.getRetainedTypes();
836 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
837 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
839 } else if (!collectLegacyDebugInfo(M))
842 collectInfoFromNamedMDNodes(M);
844 // Tell MMI that we have debug info.
845 MMI->setDebugInfoAvailability(true);
847 // Prime section data.
848 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
851 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
852 void DwarfDebug::computeInlinedDIEs() {
853 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
854 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
855 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
857 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
859 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
860 AE = AbstractSPDies.end(); AI != AE; ++AI) {
861 DIE *ISP = AI->second;
862 if (InlinedSubprogramDIEs.count(ISP))
864 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
868 // Collect info for variables that were optimized out.
869 void DwarfDebug::collectDeadVariables() {
870 const Module *M = MMI->getModule();
871 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
873 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
874 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
875 DICompileUnit TheCU(CU_Nodes->getOperand(i));
876 DIArray Subprograms = TheCU.getSubprograms();
877 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
878 DISubprogram SP(Subprograms.getElement(i));
879 if (ProcessedSPNodes.count(SP) != 0) continue;
880 if (!SP.Verify()) continue;
881 if (!SP.isDefinition()) continue;
882 DIArray Variables = SP.getVariables();
883 if (Variables.getNumElements() == 0) continue;
885 LexicalScope *Scope =
886 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
887 DeadFnScopeMap[SP] = Scope;
889 // Construct subprogram DIE and add variables DIEs.
890 CompileUnit *SPCU = CUMap.lookup(TheCU);
891 assert(SPCU && "Unable to find Compile Unit!");
892 constructSubprogramDIE(SPCU, SP);
893 DIE *ScopeDIE = SPCU->getDIE(SP);
894 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
895 DIVariable DV(Variables.getElement(vi));
896 if (!DV.Verify()) continue;
897 DbgVariable *NewVar = new DbgVariable(DV, NULL);
898 if (DIE *VariableDIE =
899 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
900 ScopeDIE->addChild(VariableDIE);
905 DeleteContainerSeconds(DeadFnScopeMap);
908 void DwarfDebug::finalizeModuleInfo() {
909 // Collect info for variables that were optimized out.
910 collectDeadVariables();
912 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
913 computeInlinedDIEs();
915 // Emit DW_AT_containing_type attribute to connect types with their
916 // vtable holding type.
917 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
918 CUE = CUMap.end(); CUI != CUE; ++CUI) {
919 CompileUnit *TheCU = CUI->second;
920 TheCU->constructContainingTypeDIEs();
923 // Compute DIE offsets and sizes.
924 InfoHolder.computeSizeAndOffsets();
926 SkeletonHolder.computeSizeAndOffsets();
929 void DwarfDebug::endSections() {
930 // Standard sections final addresses.
931 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
932 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
933 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
934 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
936 // End text sections.
937 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
938 Asm->OutStreamer.SwitchSection(SectionMap[I]);
939 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
943 // Emit all Dwarf sections that should come after the content.
944 void DwarfDebug::endModule() {
946 if (!FirstCU) return;
948 // End any existing sections.
949 // TODO: Does this need to happen?
952 // Finalize the debug info for the module.
953 finalizeModuleInfo();
955 // Emit initial sections.
958 if (!useSplitDwarf()) {
959 // Emit all the DIEs into a debug info section.
962 // Corresponding abbreviations into a abbrev section.
965 // Emit info into a debug loc section.
968 // Emit info into a debug aranges section.
971 // Emit info into a debug ranges section.
974 // Emit info into a debug macinfo section.
978 // TODO: When we don't need the option anymore we
979 // can remove all of the code that this section
981 if (useDarwinGDBCompat())
982 emitDebugInlineInfo();
984 // TODO: Fill this in for separated debug sections and separate
985 // out information into new sections.
987 // Emit the debug info section and compile units.
991 // Corresponding abbreviations into a abbrev section.
993 emitDebugAbbrevDWO();
995 // Emit info into a debug loc section.
998 // Emit info into a debug aranges section.
1001 // Emit info into a debug ranges section.
1004 // Emit info into a debug macinfo section.
1007 // Emit DWO addresses.
1008 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1010 // Emit inline info.
1011 // TODO: When we don't need the option anymore we
1012 // can remove all of the code that this section
1014 if (useDarwinGDBCompat())
1015 emitDebugInlineInfo();
1018 // Emit info into the dwarf accelerator table sections.
1019 if (useDwarfAccelTables()) {
1022 emitAccelNamespaces();
1026 // Emit info into a debug pubtypes section.
1027 // TODO: When we don't need the option anymore we can
1028 // remove all of the code that adds to the table.
1029 if (useDarwinGDBCompat())
1030 emitDebugPubTypes();
1032 // Finally emit string information into a string table.
1034 if (useSplitDwarf())
1039 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1040 E = CUMap.end(); I != E; ++I)
1045 // Reset these for the next Module if we have one.
1050 // Find abstract variable, if any, associated with Var.
1051 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1052 DebugLoc ScopeLoc) {
1053 LLVMContext &Ctx = DV->getContext();
1054 // More then one inlined variable corresponds to one abstract variable.
1055 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1056 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1058 return AbsDbgVariable;
1060 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1064 AbsDbgVariable = new DbgVariable(Var, NULL);
1065 addScopeVariable(Scope, AbsDbgVariable);
1066 AbstractVariables[Var] = AbsDbgVariable;
1067 return AbsDbgVariable;
1070 // If Var is a current function argument then add it to CurrentFnArguments list.
1071 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1072 DbgVariable *Var, LexicalScope *Scope) {
1073 if (!LScopes.isCurrentFunctionScope(Scope))
1075 DIVariable DV = Var->getVariable();
1076 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1078 unsigned ArgNo = DV.getArgNumber();
1082 size_t Size = CurrentFnArguments.size();
1084 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1085 // llvm::Function argument size is not good indicator of how many
1086 // arguments does the function have at source level.
1088 CurrentFnArguments.resize(ArgNo * 2);
1089 CurrentFnArguments[ArgNo - 1] = Var;
1093 // Collect variable information from side table maintained by MMI.
1095 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1096 SmallPtrSet<const MDNode *, 16> &Processed) {
1097 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1098 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1099 VE = VMap.end(); VI != VE; ++VI) {
1100 const MDNode *Var = VI->first;
1102 Processed.insert(Var);
1104 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1106 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1108 // If variable scope is not found then skip this variable.
1112 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1113 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1114 RegVar->setFrameIndex(VP.first);
1115 if (!addCurrentFnArgument(MF, RegVar, Scope))
1116 addScopeVariable(Scope, RegVar);
1118 AbsDbgVariable->setFrameIndex(VP.first);
1122 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1124 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1125 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1126 return MI->getNumOperands() == 3 &&
1127 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1128 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1131 // Get .debug_loc entry for the instruction range starting at MI.
1132 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1133 const MCSymbol *FLabel,
1134 const MCSymbol *SLabel,
1135 const MachineInstr *MI) {
1136 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1138 if (MI->getNumOperands() != 3) {
1139 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1140 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1142 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1143 MachineLocation MLoc;
1144 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1145 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1147 if (MI->getOperand(0).isImm())
1148 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1149 if (MI->getOperand(0).isFPImm())
1150 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1151 if (MI->getOperand(0).isCImm())
1152 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1154 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1157 // Find variables for each lexical scope.
1159 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1160 SmallPtrSet<const MDNode *, 16> &Processed) {
1162 // collection info from MMI table.
1163 collectVariableInfoFromMMITable(MF, Processed);
1165 for (SmallVectorImpl<const MDNode*>::const_iterator
1166 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1168 const MDNode *Var = *UVI;
1169 if (Processed.count(Var))
1172 // History contains relevant DBG_VALUE instructions for Var and instructions
1174 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1175 if (History.empty())
1177 const MachineInstr *MInsn = History.front();
1180 LexicalScope *Scope = NULL;
1181 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1182 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1183 Scope = LScopes.getCurrentFunctionScope();
1185 if (DV.getVersion() <= LLVMDebugVersion9)
1186 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1188 if (MDNode *IA = DV.getInlinedAt())
1189 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1191 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1194 // If variable scope is not found then skip this variable.
1198 Processed.insert(DV);
1199 assert(MInsn->isDebugValue() && "History must begin with debug value");
1200 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1201 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1202 if (!addCurrentFnArgument(MF, RegVar, Scope))
1203 addScopeVariable(Scope, RegVar);
1205 AbsVar->setMInsn(MInsn);
1207 // Simplify ranges that are fully coalesced.
1208 if (History.size() <= 1 || (History.size() == 2 &&
1209 MInsn->isIdenticalTo(History.back()))) {
1210 RegVar->setMInsn(MInsn);
1214 // Handle multiple DBG_VALUE instructions describing one variable.
1215 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1217 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1218 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1219 const MachineInstr *Begin = *HI;
1220 assert(Begin->isDebugValue() && "Invalid History entry");
1222 // Check if DBG_VALUE is truncating a range.
1223 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1224 && !Begin->getOperand(0).getReg())
1227 // Compute the range for a register location.
1228 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1229 const MCSymbol *SLabel = 0;
1232 // If Begin is the last instruction in History then its value is valid
1233 // until the end of the function.
1234 SLabel = FunctionEndSym;
1236 const MachineInstr *End = HI[1];
1237 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1238 << "\t" << *Begin << "\t" << *End << "\n");
1239 if (End->isDebugValue())
1240 SLabel = getLabelBeforeInsn(End);
1242 // End is a normal instruction clobbering the range.
1243 SLabel = getLabelAfterInsn(End);
1244 assert(SLabel && "Forgot label after clobber instruction");
1249 // The value is valid until the next DBG_VALUE or clobber.
1250 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1253 DotDebugLocEntries.push_back(DotDebugLocEntry());
1256 // Collect info for variables that were optimized out.
1257 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1258 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1259 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1260 DIVariable DV(Variables.getElement(i));
1261 if (!DV || !DV.Verify() || !Processed.insert(DV))
1263 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1264 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1268 // Return Label preceding the instruction.
1269 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1270 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1271 assert(Label && "Didn't insert label before instruction");
1275 // Return Label immediately following the instruction.
1276 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1277 return LabelsAfterInsn.lookup(MI);
1280 // Process beginning of an instruction.
1281 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1282 // Check if source location changes, but ignore DBG_VALUE locations.
1283 if (!MI->isDebugValue()) {
1284 DebugLoc DL = MI->getDebugLoc();
1285 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1288 if (DL == PrologEndLoc) {
1289 Flags |= DWARF2_FLAG_PROLOGUE_END;
1290 PrologEndLoc = DebugLoc();
1292 if (PrologEndLoc.isUnknown())
1293 Flags |= DWARF2_FLAG_IS_STMT;
1295 if (!DL.isUnknown()) {
1296 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1297 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1299 recordSourceLine(0, 0, 0, 0);
1303 // Insert labels where requested.
1304 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1305 LabelsBeforeInsn.find(MI);
1308 if (I == LabelsBeforeInsn.end())
1311 // Label already assigned.
1316 PrevLabel = MMI->getContext().CreateTempSymbol();
1317 Asm->OutStreamer.EmitLabel(PrevLabel);
1319 I->second = PrevLabel;
1322 // Process end of an instruction.
1323 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1324 // Don't create a new label after DBG_VALUE instructions.
1325 // They don't generate code.
1326 if (!MI->isDebugValue())
1329 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1330 LabelsAfterInsn.find(MI);
1333 if (I == LabelsAfterInsn.end())
1336 // Label already assigned.
1340 // We need a label after this instruction.
1342 PrevLabel = MMI->getContext().CreateTempSymbol();
1343 Asm->OutStreamer.EmitLabel(PrevLabel);
1345 I->second = PrevLabel;
1348 // Each LexicalScope has first instruction and last instruction to mark
1349 // beginning and end of a scope respectively. Create an inverse map that list
1350 // scopes starts (and ends) with an instruction. One instruction may start (or
1351 // end) multiple scopes. Ignore scopes that are not reachable.
1352 void DwarfDebug::identifyScopeMarkers() {
1353 SmallVector<LexicalScope *, 4> WorkList;
1354 WorkList.push_back(LScopes.getCurrentFunctionScope());
1355 while (!WorkList.empty()) {
1356 LexicalScope *S = WorkList.pop_back_val();
1358 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1359 if (!Children.empty())
1360 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1361 SE = Children.end(); SI != SE; ++SI)
1362 WorkList.push_back(*SI);
1364 if (S->isAbstractScope())
1367 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1370 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1371 RE = Ranges.end(); RI != RE; ++RI) {
1372 assert(RI->first && "InsnRange does not have first instruction!");
1373 assert(RI->second && "InsnRange does not have second instruction!");
1374 requestLabelBeforeInsn(RI->first);
1375 requestLabelAfterInsn(RI->second);
1380 // Get MDNode for DebugLoc's scope.
1381 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1382 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1383 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1384 return DL.getScope(Ctx);
1387 // Walk up the scope chain of given debug loc and find line number info
1388 // for the function.
1389 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1390 const MDNode *Scope = getScopeNode(DL, Ctx);
1391 DISubprogram SP = getDISubprogram(Scope);
1393 // Check for number of operands since the compatibility is
1395 if (SP->getNumOperands() > 19)
1396 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1398 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1404 // Gather pre-function debug information. Assumes being called immediately
1405 // after the function entry point has been emitted.
1406 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1407 if (!MMI->hasDebugInfo()) return;
1408 LScopes.initialize(*MF);
1409 if (LScopes.empty()) return;
1410 identifyScopeMarkers();
1412 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1414 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1415 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1416 assert(TheCU && "Unable to find compile unit!");
1417 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1419 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1420 Asm->getFunctionNumber());
1421 // Assumes in correct section after the entry point.
1422 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1424 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1426 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1427 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1428 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1430 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1432 bool AtBlockEntry = true;
1433 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1435 const MachineInstr *MI = II;
1437 if (MI->isDebugValue()) {
1438 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1440 // Keep track of user variables.
1442 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1444 // Variable is in a register, we need to check for clobbers.
1445 if (isDbgValueInDefinedReg(MI))
1446 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1448 // Check the history of this variable.
1449 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1450 if (History.empty()) {
1451 UserVariables.push_back(Var);
1452 // The first mention of a function argument gets the FunctionBeginSym
1453 // label, so arguments are visible when breaking at function entry.
1455 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1456 DISubprogram(getDISubprogram(DV.getContext()))
1457 .describes(MF->getFunction()))
1458 LabelsBeforeInsn[MI] = FunctionBeginSym;
1460 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1461 const MachineInstr *Prev = History.back();
1462 if (Prev->isDebugValue()) {
1463 // Coalesce identical entries at the end of History.
1464 if (History.size() >= 2 &&
1465 Prev->isIdenticalTo(History[History.size() - 2])) {
1466 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1468 << "\t" << *History[History.size() - 2] << "\n");
1472 // Terminate old register assignments that don't reach MI;
1473 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1474 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1475 isDbgValueInDefinedReg(Prev)) {
1476 // Previous register assignment needs to terminate at the end of
1478 MachineBasicBlock::const_iterator LastMI =
1479 PrevMBB->getLastNonDebugInstr();
1480 if (LastMI == PrevMBB->end()) {
1481 // Drop DBG_VALUE for empty range.
1482 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1483 << "\t" << *Prev << "\n");
1487 // Terminate after LastMI.
1488 History.push_back(LastMI);
1493 History.push_back(MI);
1495 // Not a DBG_VALUE instruction.
1497 AtBlockEntry = false;
1499 // First known non-DBG_VALUE and non-frame setup location marks
1500 // the beginning of the function body.
1501 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1502 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1503 PrologEndLoc = MI->getDebugLoc();
1505 // Check if the instruction clobbers any registers with debug vars.
1506 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1507 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1508 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1510 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1511 AI.isValid(); ++AI) {
1513 const MDNode *Var = LiveUserVar[Reg];
1516 // Reg is now clobbered.
1517 LiveUserVar[Reg] = 0;
1519 // Was MD last defined by a DBG_VALUE referring to Reg?
1520 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1521 if (HistI == DbgValues.end())
1523 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1524 if (History.empty())
1526 const MachineInstr *Prev = History.back();
1527 // Sanity-check: Register assignments are terminated at the end of
1529 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1531 // Is the variable still in Reg?
1532 if (!isDbgValueInDefinedReg(Prev) ||
1533 Prev->getOperand(0).getReg() != Reg)
1535 // Var is clobbered. Make sure the next instruction gets a label.
1536 History.push_back(MI);
1543 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1545 SmallVectorImpl<const MachineInstr*> &History = I->second;
1546 if (History.empty())
1549 // Make sure the final register assignments are terminated.
1550 const MachineInstr *Prev = History.back();
1551 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1552 const MachineBasicBlock *PrevMBB = Prev->getParent();
1553 MachineBasicBlock::const_iterator LastMI =
1554 PrevMBB->getLastNonDebugInstr();
1555 if (LastMI == PrevMBB->end())
1556 // Drop DBG_VALUE for empty range.
1559 // Terminate after LastMI.
1560 History.push_back(LastMI);
1563 // Request labels for the full history.
1564 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1565 const MachineInstr *MI = History[i];
1566 if (MI->isDebugValue())
1567 requestLabelBeforeInsn(MI);
1569 requestLabelAfterInsn(MI);
1573 PrevInstLoc = DebugLoc();
1574 PrevLabel = FunctionBeginSym;
1576 // Record beginning of function.
1577 if (!PrologEndLoc.isUnknown()) {
1578 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1579 MF->getFunction()->getContext());
1580 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1581 FnStartDL.getScope(MF->getFunction()->getContext()),
1582 // We'd like to list the prologue as "not statements" but GDB behaves
1583 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1584 DWARF2_FLAG_IS_STMT);
1588 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1589 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1590 ScopeVariables[LS].push_back(Var);
1591 // Vars.push_back(Var);
1594 // Gather and emit post-function debug information.
1595 void DwarfDebug::endFunction(const MachineFunction *MF) {
1596 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1598 // Define end label for subprogram.
1599 FunctionEndSym = Asm->GetTempSymbol("func_end",
1600 Asm->getFunctionNumber());
1601 // Assumes in correct section after the entry point.
1602 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1603 // Set DwarfCompileUnitID in MCContext to default value.
1604 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1606 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1607 collectVariableInfo(MF, ProcessedVars);
1609 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1610 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1611 assert(TheCU && "Unable to find compile unit!");
1613 // Construct abstract scopes.
1614 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1615 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1616 LexicalScope *AScope = AList[i];
1617 DISubprogram SP(AScope->getScopeNode());
1619 // Collect info for variables that were optimized out.
1620 DIArray Variables = SP.getVariables();
1621 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1622 DIVariable DV(Variables.getElement(i));
1623 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1625 // Check that DbgVariable for DV wasn't created earlier, when
1626 // findAbstractVariable() was called for inlined instance of DV.
1627 LLVMContext &Ctx = DV->getContext();
1628 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1629 if (AbstractVariables.lookup(CleanDV))
1631 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1632 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1635 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1636 constructScopeDIE(TheCU, AScope);
1639 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1641 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1642 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1644 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1645 MMI->getFrameMoves()));
1648 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1649 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1650 DeleteContainerPointers(I->second);
1651 ScopeVariables.clear();
1652 DeleteContainerPointers(CurrentFnArguments);
1653 UserVariables.clear();
1655 AbstractVariables.clear();
1656 LabelsBeforeInsn.clear();
1657 LabelsAfterInsn.clear();
1661 // Register a source line with debug info. Returns the unique label that was
1662 // emitted and which provides correspondence to the source line list.
1663 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1669 DIDescriptor Scope(S);
1671 if (Scope.isCompileUnit()) {
1672 DICompileUnit CU(S);
1673 Fn = CU.getFilename();
1674 Dir = CU.getDirectory();
1675 } else if (Scope.isFile()) {
1677 Fn = F.getFilename();
1678 Dir = F.getDirectory();
1679 } else if (Scope.isSubprogram()) {
1681 Fn = SP.getFilename();
1682 Dir = SP.getDirectory();
1683 } else if (Scope.isLexicalBlockFile()) {
1684 DILexicalBlockFile DBF(S);
1685 Fn = DBF.getFilename();
1686 Dir = DBF.getDirectory();
1687 } else if (Scope.isLexicalBlock()) {
1688 DILexicalBlock DB(S);
1689 Fn = DB.getFilename();
1690 Dir = DB.getDirectory();
1692 llvm_unreachable("Unexpected scope info");
1694 Src = getOrCreateSourceID(Fn, Dir);
1696 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1699 //===----------------------------------------------------------------------===//
1701 //===----------------------------------------------------------------------===//
1703 // Compute the size and offset of a DIE.
1705 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1706 // Get the children.
1707 const std::vector<DIE *> &Children = Die->getChildren();
1709 // Record the abbreviation.
1710 assignAbbrevNumber(Die->getAbbrev());
1712 // Get the abbreviation for this DIE.
1713 unsigned AbbrevNumber = Die->getAbbrevNumber();
1714 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1717 Die->setOffset(Offset);
1719 // Start the size with the size of abbreviation code.
1720 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1722 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1723 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1725 // Size the DIE attribute values.
1726 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1727 // Size attribute value.
1728 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1730 // Size the DIE children if any.
1731 if (!Children.empty()) {
1732 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1733 "Children flag not set");
1735 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1736 Offset = computeSizeAndOffset(Children[j], Offset);
1738 // End of children marker.
1739 Offset += sizeof(int8_t);
1742 Die->setSize(Offset - Die->getOffset());
1746 // Compute the size and offset of all the DIEs.
1747 void DwarfUnits::computeSizeAndOffsets() {
1748 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1749 E = CUs.end(); I != E; ++I) {
1751 sizeof(int32_t) + // Length of Compilation Unit Info
1752 sizeof(int16_t) + // DWARF version number
1753 sizeof(int32_t) + // Offset Into Abbrev. Section
1754 sizeof(int8_t); // Pointer Size (in bytes)
1756 computeSizeAndOffset((*I)->getCUDie(), Offset);
1760 // Emit initial Dwarf sections with a label at the start of each one.
1761 void DwarfDebug::emitSectionLabels() {
1762 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1764 // Dwarf sections base addresses.
1765 DwarfInfoSectionSym =
1766 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1767 DwarfAbbrevSectionSym =
1768 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1769 if (useSplitDwarf())
1770 DwarfAbbrevDWOSectionSym =
1771 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1772 "section_abbrev_dwo");
1773 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1775 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1776 emitSectionSym(Asm, MacroInfo);
1778 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1779 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1780 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1781 DwarfStrSectionSym =
1782 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1783 if (useSplitDwarf())
1784 DwarfStrDWOSectionSym =
1785 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1786 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1789 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1790 "section_debug_loc");
1792 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1793 emitSectionSym(Asm, TLOF.getDataSection());
1796 // Recursively emits a debug information entry.
1797 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1798 // Get the abbreviation for this DIE.
1799 unsigned AbbrevNumber = Die->getAbbrevNumber();
1800 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1802 // Emit the code (index) for the abbreviation.
1803 if (Asm->isVerbose())
1804 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1805 Twine::utohexstr(Die->getOffset()) + ":0x" +
1806 Twine::utohexstr(Die->getSize()) + " " +
1807 dwarf::TagString(Abbrev->getTag()));
1808 Asm->EmitULEB128(AbbrevNumber);
1810 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1811 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1813 // Emit the DIE attribute values.
1814 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1815 unsigned Attr = AbbrevData[i].getAttribute();
1816 unsigned Form = AbbrevData[i].getForm();
1817 assert(Form && "Too many attributes for DIE (check abbreviation)");
1819 if (Asm->isVerbose())
1820 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1823 case dwarf::DW_AT_abstract_origin: {
1824 DIEEntry *E = cast<DIEEntry>(Values[i]);
1825 DIE *Origin = E->getEntry();
1826 unsigned Addr = Origin->getOffset();
1827 Asm->EmitInt32(Addr);
1830 case dwarf::DW_AT_ranges: {
1831 // DW_AT_range Value encodes offset in debug_range section.
1832 DIEInteger *V = cast<DIEInteger>(Values[i]);
1834 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1835 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1839 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1841 DwarfDebugRangeSectionSym,
1846 case dwarf::DW_AT_location: {
1847 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1848 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1849 Asm->EmitLabelReference(L->getValue(), 4);
1851 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1853 Values[i]->EmitValue(Asm, Form);
1857 case dwarf::DW_AT_accessibility: {
1858 if (Asm->isVerbose()) {
1859 DIEInteger *V = cast<DIEInteger>(Values[i]);
1860 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1862 Values[i]->EmitValue(Asm, Form);
1866 // Emit an attribute using the defined form.
1867 Values[i]->EmitValue(Asm, Form);
1872 // Emit the DIE children if any.
1873 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1874 const std::vector<DIE *> &Children = Die->getChildren();
1876 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1877 emitDIE(Children[j], Abbrevs);
1879 if (Asm->isVerbose())
1880 Asm->OutStreamer.AddComment("End Of Children Mark");
1885 // Emit the various dwarf units to the unit section USection with
1886 // the abbreviations going into ASection.
1887 void DwarfUnits::emitUnits(DwarfDebug *DD,
1888 const MCSection *USection,
1889 const MCSection *ASection,
1890 const MCSymbol *ASectionSym) {
1891 Asm->OutStreamer.SwitchSection(USection);
1892 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1893 E = CUs.end(); I != E; ++I) {
1894 CompileUnit *TheCU = *I;
1895 DIE *Die = TheCU->getCUDie();
1897 // Emit the compile units header.
1899 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1900 TheCU->getUniqueID()));
1902 // Emit size of content not including length itself
1903 unsigned ContentSize = Die->getSize() +
1904 sizeof(int16_t) + // DWARF version number
1905 sizeof(int32_t) + // Offset Into Abbrev. Section
1906 sizeof(int8_t); // Pointer Size (in bytes)
1908 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1909 Asm->EmitInt32(ContentSize);
1910 Asm->OutStreamer.AddComment("DWARF version number");
1911 Asm->EmitInt16(dwarf::DWARF_VERSION);
1912 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1913 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1915 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1916 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1918 DD->emitDIE(Die, Abbreviations);
1919 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1920 TheCU->getUniqueID()));
1924 // Emit the debug info section.
1925 void DwarfDebug::emitDebugInfo() {
1926 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1928 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1929 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1930 DwarfAbbrevSectionSym);
1933 // Emit the abbreviation section.
1934 void DwarfDebug::emitAbbreviations() {
1935 if (!useSplitDwarf())
1936 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1939 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1942 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1943 std::vector<DIEAbbrev *> *Abbrevs) {
1944 // Check to see if it is worth the effort.
1945 if (!Abbrevs->empty()) {
1946 // Start the debug abbrev section.
1947 Asm->OutStreamer.SwitchSection(Section);
1949 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1950 Asm->OutStreamer.EmitLabel(Begin);
1952 // For each abbrevation.
1953 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1954 // Get abbreviation data
1955 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1957 // Emit the abbrevations code (base 1 index.)
1958 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1960 // Emit the abbreviations data.
1964 // Mark end of abbreviations.
1965 Asm->EmitULEB128(0, "EOM(3)");
1967 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1968 Asm->OutStreamer.EmitLabel(End);
1972 // Emit the last address of the section and the end of the line matrix.
1973 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1974 // Define last address of section.
1975 Asm->OutStreamer.AddComment("Extended Op");
1978 Asm->OutStreamer.AddComment("Op size");
1979 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1980 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1981 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1983 Asm->OutStreamer.AddComment("Section end label");
1985 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1986 Asm->getDataLayout().getPointerSize());
1988 // Mark end of matrix.
1989 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1995 // Emit visible names into a hashed accelerator table section.
1996 void DwarfDebug::emitAccelNames() {
1997 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1998 dwarf::DW_FORM_data4));
1999 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2000 E = CUMap.end(); I != E; ++I) {
2001 CompileUnit *TheCU = I->second;
2002 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2003 for (StringMap<std::vector<DIE*> >::const_iterator
2004 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2005 const char *Name = GI->getKeyData();
2006 const std::vector<DIE *> &Entities = GI->second;
2007 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2008 DE = Entities.end(); DI != DE; ++DI)
2009 AT.AddName(Name, (*DI));
2013 AT.FinalizeTable(Asm, "Names");
2014 Asm->OutStreamer.SwitchSection(
2015 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2016 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2017 Asm->OutStreamer.EmitLabel(SectionBegin);
2019 // Emit the full data.
2020 AT.Emit(Asm, SectionBegin, &InfoHolder);
2023 // Emit objective C classes and categories into a hashed accelerator table
2025 void DwarfDebug::emitAccelObjC() {
2026 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2027 dwarf::DW_FORM_data4));
2028 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2029 E = CUMap.end(); I != E; ++I) {
2030 CompileUnit *TheCU = I->second;
2031 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2032 for (StringMap<std::vector<DIE*> >::const_iterator
2033 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2034 const char *Name = GI->getKeyData();
2035 const std::vector<DIE *> &Entities = GI->second;
2036 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2037 DE = Entities.end(); DI != DE; ++DI)
2038 AT.AddName(Name, (*DI));
2042 AT.FinalizeTable(Asm, "ObjC");
2043 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2044 .getDwarfAccelObjCSection());
2045 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2046 Asm->OutStreamer.EmitLabel(SectionBegin);
2048 // Emit the full data.
2049 AT.Emit(Asm, SectionBegin, &InfoHolder);
2052 // Emit namespace dies into a hashed accelerator table.
2053 void DwarfDebug::emitAccelNamespaces() {
2054 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2055 dwarf::DW_FORM_data4));
2056 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2057 E = CUMap.end(); I != E; ++I) {
2058 CompileUnit *TheCU = I->second;
2059 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2060 for (StringMap<std::vector<DIE*> >::const_iterator
2061 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2062 const char *Name = GI->getKeyData();
2063 const std::vector<DIE *> &Entities = GI->second;
2064 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2065 DE = Entities.end(); DI != DE; ++DI)
2066 AT.AddName(Name, (*DI));
2070 AT.FinalizeTable(Asm, "namespac");
2071 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2072 .getDwarfAccelNamespaceSection());
2073 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2074 Asm->OutStreamer.EmitLabel(SectionBegin);
2076 // Emit the full data.
2077 AT.Emit(Asm, SectionBegin, &InfoHolder);
2080 // Emit type dies into a hashed accelerator table.
2081 void DwarfDebug::emitAccelTypes() {
2082 std::vector<DwarfAccelTable::Atom> Atoms;
2083 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2084 dwarf::DW_FORM_data4));
2085 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2086 dwarf::DW_FORM_data2));
2087 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2088 dwarf::DW_FORM_data1));
2089 DwarfAccelTable AT(Atoms);
2090 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2091 E = CUMap.end(); I != E; ++I) {
2092 CompileUnit *TheCU = I->second;
2093 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2094 = TheCU->getAccelTypes();
2095 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2096 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2097 const char *Name = GI->getKeyData();
2098 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2099 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2100 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2101 AT.AddName(Name, (*DI).first, (*DI).second);
2105 AT.FinalizeTable(Asm, "types");
2106 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2107 .getDwarfAccelTypesSection());
2108 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2109 Asm->OutStreamer.EmitLabel(SectionBegin);
2111 // Emit the full data.
2112 AT.Emit(Asm, SectionBegin, &InfoHolder);
2115 void DwarfDebug::emitDebugPubTypes() {
2116 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2117 E = CUMap.end(); I != E; ++I) {
2118 CompileUnit *TheCU = I->second;
2119 // Start the dwarf pubtypes section.
2120 Asm->OutStreamer.SwitchSection(
2121 Asm->getObjFileLowering().getDwarfPubTypesSection());
2122 Asm->OutStreamer.AddComment("Length of Public Types Info");
2123 Asm->EmitLabelDifference(
2124 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2125 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2127 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2128 TheCU->getUniqueID()));
2130 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2131 Asm->EmitInt16(dwarf::DWARF_VERSION);
2133 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2134 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2135 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2136 TheCU->getUniqueID()),
2137 DwarfInfoSectionSym);
2139 Asm->OutStreamer.AddComment("Compilation Unit Length");
2140 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2141 TheCU->getUniqueID()),
2142 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2143 TheCU->getUniqueID()),
2146 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2147 for (StringMap<DIE*>::const_iterator
2148 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2149 const char *Name = GI->getKeyData();
2150 DIE *Entity = GI->second;
2152 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2153 Asm->EmitInt32(Entity->getOffset());
2155 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2156 // Emit the name with a terminating null byte.
2157 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2160 Asm->OutStreamer.AddComment("End Mark");
2162 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2163 TheCU->getUniqueID()));
2167 // Emit strings into a string section.
2168 void DwarfUnits::emitStrings(const MCSection *StrSection,
2169 const MCSection *OffsetSection = NULL,
2170 const MCSymbol *StrSecSym = NULL) {
2172 if (StringPool.empty()) return;
2174 // Start the dwarf str section.
2175 Asm->OutStreamer.SwitchSection(StrSection);
2177 // Get all of the string pool entries and put them in an array by their ID so
2178 // we can sort them.
2179 SmallVector<std::pair<unsigned,
2180 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2182 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2183 I = StringPool.begin(), E = StringPool.end();
2185 Entries.push_back(std::make_pair(I->second.second, &*I));
2187 array_pod_sort(Entries.begin(), Entries.end());
2189 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2190 // Emit a label for reference from debug information entries.
2191 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2193 // Emit the string itself with a terminating null byte.
2194 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2195 Entries[i].second->getKeyLength()+1));
2198 // If we've got an offset section go ahead and emit that now as well.
2199 if (OffsetSection) {
2200 Asm->OutStreamer.SwitchSection(OffsetSection);
2201 unsigned offset = 0;
2202 unsigned size = 4; // FIXME: DWARF64 is 8.
2203 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2204 Asm->OutStreamer.EmitIntValue(offset, size);
2205 offset += Entries[i].second->getKeyLength() + 1;
2210 // Emit strings into a string section.
2211 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2213 if (AddressPool.empty()) return;
2215 // Start the dwarf addr section.
2216 Asm->OutStreamer.SwitchSection(AddrSection);
2218 // Get all of the string pool entries and put them in an array by their ID so
2219 // we can sort them.
2220 SmallVector<std::pair<unsigned,
2221 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2223 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2224 I = AddressPool.begin(), E = AddressPool.end();
2226 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2228 array_pod_sort(Entries.begin(), Entries.end());
2230 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2231 // Emit a label for reference from debug information entries.
2232 MCSymbol *Sym = Entries[i].second->first;
2234 Asm->EmitLabelReference(Entries[i].second->first,
2235 Asm->getDataLayout().getPointerSize());
2237 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2242 // Emit visible names into a debug str section.
2243 void DwarfDebug::emitDebugStr() {
2244 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2245 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2248 // Emit visible names into a debug loc section.
2249 void DwarfDebug::emitDebugLoc() {
2250 if (DotDebugLocEntries.empty())
2253 for (SmallVector<DotDebugLocEntry, 4>::iterator
2254 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2256 DotDebugLocEntry &Entry = *I;
2257 if (I + 1 != DotDebugLocEntries.end())
2261 // Start the dwarf loc section.
2262 Asm->OutStreamer.SwitchSection(
2263 Asm->getObjFileLowering().getDwarfLocSection());
2264 unsigned char Size = Asm->getDataLayout().getPointerSize();
2265 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2267 for (SmallVector<DotDebugLocEntry, 4>::iterator
2268 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2269 I != E; ++I, ++index) {
2270 DotDebugLocEntry &Entry = *I;
2271 if (Entry.isMerged()) continue;
2272 if (Entry.isEmpty()) {
2273 Asm->OutStreamer.EmitIntValue(0, Size);
2274 Asm->OutStreamer.EmitIntValue(0, Size);
2275 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2277 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2278 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2279 DIVariable DV(Entry.Variable);
2280 Asm->OutStreamer.AddComment("Loc expr size");
2281 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2282 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2283 Asm->EmitLabelDifference(end, begin, 2);
2284 Asm->OutStreamer.EmitLabel(begin);
2285 if (Entry.isInt()) {
2286 DIBasicType BTy(DV.getType());
2288 (BTy.getEncoding() == dwarf::DW_ATE_signed
2289 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2290 Asm->OutStreamer.AddComment("DW_OP_consts");
2291 Asm->EmitInt8(dwarf::DW_OP_consts);
2292 Asm->EmitSLEB128(Entry.getInt());
2294 Asm->OutStreamer.AddComment("DW_OP_constu");
2295 Asm->EmitInt8(dwarf::DW_OP_constu);
2296 Asm->EmitULEB128(Entry.getInt());
2298 } else if (Entry.isLocation()) {
2299 if (!DV.hasComplexAddress())
2301 Asm->EmitDwarfRegOp(Entry.Loc);
2303 // Complex address entry.
2304 unsigned N = DV.getNumAddrElements();
2306 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2307 if (Entry.Loc.getOffset()) {
2309 Asm->EmitDwarfRegOp(Entry.Loc);
2310 Asm->OutStreamer.AddComment("DW_OP_deref");
2311 Asm->EmitInt8(dwarf::DW_OP_deref);
2312 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2313 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2314 Asm->EmitSLEB128(DV.getAddrElement(1));
2316 // If first address element is OpPlus then emit
2317 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2318 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2319 Asm->EmitDwarfRegOp(Loc);
2323 Asm->EmitDwarfRegOp(Entry.Loc);
2326 // Emit remaining complex address elements.
2327 for (; i < N; ++i) {
2328 uint64_t Element = DV.getAddrElement(i);
2329 if (Element == DIBuilder::OpPlus) {
2330 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2331 Asm->EmitULEB128(DV.getAddrElement(++i));
2332 } else if (Element == DIBuilder::OpDeref) {
2333 if (!Entry.Loc.isReg())
2334 Asm->EmitInt8(dwarf::DW_OP_deref);
2336 llvm_unreachable("unknown Opcode found in complex address");
2340 // else ... ignore constant fp. There is not any good way to
2341 // to represent them here in dwarf.
2342 Asm->OutStreamer.EmitLabel(end);
2347 // Emit visible names into a debug aranges section.
2348 void DwarfDebug::emitDebugARanges() {
2349 // Start the dwarf aranges section.
2350 Asm->OutStreamer.SwitchSection(
2351 Asm->getObjFileLowering().getDwarfARangesSection());
2354 // Emit visible names into a debug ranges section.
2355 void DwarfDebug::emitDebugRanges() {
2356 // Start the dwarf ranges section.
2357 Asm->OutStreamer.SwitchSection(
2358 Asm->getObjFileLowering().getDwarfRangesSection());
2359 unsigned char Size = Asm->getDataLayout().getPointerSize();
2360 for (SmallVector<const MCSymbol *, 8>::iterator
2361 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2364 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2366 Asm->OutStreamer.EmitIntValue(0, Size);
2370 // Emit visible names into a debug macinfo section.
2371 void DwarfDebug::emitDebugMacInfo() {
2372 if (const MCSection *LineInfo =
2373 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2374 // Start the dwarf macinfo section.
2375 Asm->OutStreamer.SwitchSection(LineInfo);
2379 // Emit inline info using following format.
2381 // 1. length of section
2382 // 2. Dwarf version number
2385 // Entries (one "entry" for each function that was inlined):
2387 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2388 // otherwise offset into __debug_str for regular function name.
2389 // 2. offset into __debug_str section for regular function name.
2390 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2391 // instances for the function.
2393 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2394 // inlined instance; the die_offset points to the inlined_subroutine die in the
2395 // __debug_info section, and the low_pc is the starting address for the
2396 // inlining instance.
2397 void DwarfDebug::emitDebugInlineInfo() {
2398 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2404 Asm->OutStreamer.SwitchSection(
2405 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2407 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2408 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2409 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2411 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2413 Asm->OutStreamer.AddComment("Dwarf Version");
2414 Asm->EmitInt16(dwarf::DWARF_VERSION);
2415 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2416 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2418 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2419 E = InlinedSPNodes.end(); I != E; ++I) {
2421 const MDNode *Node = *I;
2422 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2423 = InlineInfo.find(Node);
2424 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2425 DISubprogram SP(Node);
2426 StringRef LName = SP.getLinkageName();
2427 StringRef Name = SP.getName();
2429 Asm->OutStreamer.AddComment("MIPS linkage name");
2431 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2432 DwarfStrSectionSym);
2434 Asm->EmitSectionOffset(InfoHolder
2435 .getStringPoolEntry(getRealLinkageName(LName)),
2436 DwarfStrSectionSym);
2438 Asm->OutStreamer.AddComment("Function name");
2439 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2440 DwarfStrSectionSym);
2441 Asm->EmitULEB128(Labels.size(), "Inline count");
2443 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2444 LE = Labels.end(); LI != LE; ++LI) {
2445 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2446 Asm->EmitInt32(LI->second->getOffset());
2448 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2449 Asm->OutStreamer.EmitSymbolValue(LI->first,
2450 Asm->getDataLayout().getPointerSize());
2454 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2457 // DWARF5 Experimental Separate Dwarf emitters.
2459 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2460 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2461 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2462 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2463 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2464 DICompileUnit DIUnit(N);
2465 CompilationDir = DIUnit.getDirectory();
2467 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2468 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2469 DIUnit.getLanguage(), Die, Asm,
2470 this, &SkeletonHolder);
2472 SmallString<16> T(DIUnit.getFilename());
2473 sys::path::replace_extension(T, ".dwo");
2474 StringRef FN = sys::path::filename(T);
2475 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2477 // This should be a unique identifier when we want to build .dwp files.
2478 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2480 // FIXME: The addr base should be relative for each compile unit, however,
2481 // this one is going to be 0 anyhow.
2482 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset, 0);
2484 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2485 // into an entity. We're using 0, or a NULL label for this.
2486 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2488 // DW_AT_stmt_list is a offset of line number information for this
2489 // compile unit in debug_line section.
2490 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2491 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2492 Asm->GetTempSymbol("section_line"));
2494 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2496 if (!CompilationDir.empty())
2497 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2502 SkeletonHolder.addUnit(NewCU);
2507 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2508 assert(useSplitDwarf() && "No split dwarf debug info?");
2509 emitAbbrevs(Section, &SkeletonAbbrevs);
2512 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2513 // compile units that would normally be in debug_info.
2514 void DwarfDebug::emitDebugInfoDWO() {
2515 assert(useSplitDwarf() && "No split dwarf debug info?");
2516 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2517 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2518 DwarfAbbrevDWOSectionSym);
2521 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2522 // abbreviations for the .debug_info.dwo section.
2523 void DwarfDebug::emitDebugAbbrevDWO() {
2524 assert(useSplitDwarf() && "No split dwarf?");
2525 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2529 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2530 // string section and is identical in format to traditional .debug_str
2532 void DwarfDebug::emitDebugStrDWO() {
2533 assert(useSplitDwarf() && "No split dwarf?");
2534 const MCSection *OffSec = Asm->getObjFileLowering()
2535 .getDwarfStrOffDWOSection();
2536 const MCSymbol *StrSym = DwarfStrSectionSym;
2537 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),