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 // Define a unique number for the abbreviation.
242 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
243 // Profile the node so that we can make it unique.
247 // Check the set for priors.
248 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
250 // If it's newly added.
251 if (InSet == &Abbrev) {
252 // Add to abbreviation list.
253 Abbreviations->push_back(&Abbrev);
255 // Assign the vector position + 1 as its number.
256 Abbrev.setNumber(Abbreviations->size());
258 // Assign existing abbreviation number.
259 Abbrev.setNumber(InSet->getNumber());
263 // If special LLVM prefix that is used to inform the asm
264 // printer to not emit usual symbol prefix before the symbol name is used then
265 // return linkage name after skipping this special LLVM prefix.
266 static StringRef getRealLinkageName(StringRef LinkageName) {
268 if (LinkageName.startswith(StringRef(&One, 1)))
269 return LinkageName.substr(1);
273 static bool isObjCClass(StringRef Name) {
274 return Name.startswith("+") || Name.startswith("-");
277 static bool hasObjCCategory(StringRef Name) {
278 if (!isObjCClass(Name)) return false;
280 size_t pos = Name.find(')');
281 if (pos != std::string::npos) {
282 if (Name[pos+1] != ' ') return false;
288 static void getObjCClassCategory(StringRef In, StringRef &Class,
289 StringRef &Category) {
290 if (!hasObjCCategory(In)) {
291 Class = In.slice(In.find('[') + 1, In.find(' '));
296 Class = In.slice(In.find('[') + 1, In.find('('));
297 Category = In.slice(In.find('[') + 1, In.find(' '));
301 static StringRef getObjCMethodName(StringRef In) {
302 return In.slice(In.find(' ') + 1, In.find(']'));
305 // Add the various names to the Dwarf accelerator table names.
306 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
308 if (!SP.isDefinition()) return;
310 TheCU->addAccelName(SP.getName(), Die);
312 // If the linkage name is different than the name, go ahead and output
313 // that as well into the name table.
314 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
315 TheCU->addAccelName(SP.getLinkageName(), Die);
317 // If this is an Objective-C selector name add it to the ObjC accelerator
319 if (isObjCClass(SP.getName())) {
320 StringRef Class, Category;
321 getObjCClassCategory(SP.getName(), Class, Category);
322 TheCU->addAccelObjC(Class, Die);
324 TheCU->addAccelObjC(Category, Die);
325 // Also add the base method name to the name table.
326 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
330 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
331 // and DW_AT_high_pc attributes. If there are global variables in this
332 // scope then create and insert DIEs for these variables.
333 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
334 const MDNode *SPNode) {
335 DIE *SPDie = SPCU->getDIE(SPNode);
337 assert(SPDie && "Unable to find subprogram DIE!");
338 DISubprogram SP(SPNode);
340 // If we're updating an abstract DIE, then we will be adding the children and
341 // object pointer later on. But what we don't want to do is process the
342 // concrete DIE twice.
343 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
344 // Pick up abstract subprogram DIE.
345 SPDie = new DIE(dwarf::DW_TAG_subprogram);
346 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
347 dwarf::DW_FORM_ref4, AbsSPDIE);
350 DISubprogram SPDecl = SP.getFunctionDeclaration();
351 if (!SPDecl.isSubprogram()) {
352 // There is not any need to generate specification DIE for a function
353 // defined at compile unit level. If a function is defined inside another
354 // function then gdb prefers the definition at top level and but does not
355 // expect specification DIE in parent function. So avoid creating
356 // specification DIE for a function defined inside a function.
357 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
358 !SP.getContext().isFile() &&
359 !isSubprogramContext(SP.getContext())) {
360 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
363 DICompositeType SPTy = SP.getType();
364 DIArray Args = SPTy.getTypeArray();
365 unsigned SPTag = SPTy.getTag();
366 if (SPTag == dwarf::DW_TAG_subroutine_type)
367 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
368 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
369 DIType ATy = DIType(Args.getElement(i));
370 SPCU->addType(Arg, ATy);
371 if (ATy.isArtificial())
372 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
373 if (ATy.isObjectPointer())
374 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
375 dwarf::DW_FORM_ref4, Arg);
376 SPDie->addChild(Arg);
378 DIE *SPDeclDie = SPDie;
379 SPDie = new DIE(dwarf::DW_TAG_subprogram);
380 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
381 dwarf::DW_FORM_ref4, SPDeclDie);
387 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
388 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
389 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
390 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
391 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
392 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
393 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
395 // Add name to the name table, we do this here because we're guaranteed
396 // to have concrete versions of our DW_TAG_subprogram nodes.
397 addSubprogramNames(SPCU, SP, SPDie);
402 // Construct new DW_TAG_lexical_block for this scope and attach
403 // DW_AT_low_pc/DW_AT_high_pc labels.
404 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
405 LexicalScope *Scope) {
406 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
407 if (Scope->isAbstractScope())
410 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
414 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
415 if (Ranges.size() > 1) {
416 // .debug_range section has not been laid out yet. Emit offset in
417 // .debug_range as a uint, size 4, for now. emitDIE will handle
418 // DW_AT_ranges appropriately.
419 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
420 DebugRangeSymbols.size()
421 * Asm->getDataLayout().getPointerSize());
422 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
423 RE = Ranges.end(); RI != RE; ++RI) {
424 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
425 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
427 DebugRangeSymbols.push_back(NULL);
428 DebugRangeSymbols.push_back(NULL);
432 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
433 const MCSymbol *End = getLabelAfterInsn(RI->second);
435 if (End == 0) return 0;
437 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
438 assert(End->isDefined() && "Invalid end label for an inlined scope!");
440 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
441 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
446 // This scope represents inlined body of a function. Construct DIE to
447 // represent this concrete inlined copy of the function.
448 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
449 LexicalScope *Scope) {
450 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
451 assert(Ranges.empty() == false &&
452 "LexicalScope does not have instruction markers!");
454 if (!Scope->getScopeNode())
456 DIScope DS(Scope->getScopeNode());
457 DISubprogram InlinedSP = getDISubprogram(DS);
458 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
460 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
464 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
465 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
466 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
468 if (StartLabel == 0 || EndLabel == 0) {
469 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
471 assert(StartLabel->isDefined() &&
472 "Invalid starting label for an inlined scope!");
473 assert(EndLabel->isDefined() &&
474 "Invalid end label for an inlined scope!");
476 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
477 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
478 dwarf::DW_FORM_ref4, OriginDIE);
480 if (Ranges.size() > 1) {
481 // .debug_range section has not been laid out yet. Emit offset in
482 // .debug_range as a uint, size 4, for now. emitDIE will handle
483 // DW_AT_ranges appropriately.
484 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
485 DebugRangeSymbols.size()
486 * Asm->getDataLayout().getPointerSize());
487 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
488 RE = Ranges.end(); RI != RE; ++RI) {
489 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
490 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
492 DebugRangeSymbols.push_back(NULL);
493 DebugRangeSymbols.push_back(NULL);
495 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
497 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
501 InlinedSubprogramDIEs.insert(OriginDIE);
503 // Track the start label for this inlined function.
504 //.debug_inlined section specification does not clearly state how
505 // to emit inlined scope that is split into multiple instruction ranges.
506 // For now, use first instruction range and emit low_pc/high_pc pair and
507 // corresponding .debug_inlined section entry for this pair.
508 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
509 I = InlineInfo.find(InlinedSP);
511 if (I == InlineInfo.end()) {
512 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
513 InlinedSPNodes.push_back(InlinedSP);
515 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
517 DILocation DL(Scope->getInlinedAt());
518 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
519 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
520 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
522 // Add name to the name table, we do this here because we're guaranteed
523 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
524 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
529 // Construct a DIE for this scope.
530 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
531 if (!Scope || !Scope->getScopeNode())
534 SmallVector<DIE *, 8> Children;
535 DIE *ObjectPointer = NULL;
537 // Collect arguments for current function.
538 if (LScopes.isCurrentFunctionScope(Scope))
539 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
540 if (DbgVariable *ArgDV = CurrentFnArguments[i])
542 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
543 Children.push_back(Arg);
544 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
547 // Collect lexical scope children first.
548 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
549 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
551 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
552 Children.push_back(Variable);
553 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
555 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
556 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
557 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
558 Children.push_back(Nested);
559 DIScope DS(Scope->getScopeNode());
560 DIE *ScopeDIE = NULL;
561 if (Scope->getInlinedAt())
562 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
563 else if (DS.isSubprogram()) {
564 ProcessedSPNodes.insert(DS);
565 if (Scope->isAbstractScope()) {
566 ScopeDIE = TheCU->getDIE(DS);
567 // Note down abstract DIE.
569 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
572 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
575 // There is no need to emit empty lexical block DIE.
576 if (Children.empty())
578 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
581 if (!ScopeDIE) return NULL;
584 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
585 E = Children.end(); I != E; ++I)
586 ScopeDIE->addChild(*I);
588 if (DS.isSubprogram() && ObjectPointer != NULL)
589 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
590 dwarf::DW_FORM_ref4, ObjectPointer);
592 if (DS.isSubprogram())
593 TheCU->addPubTypes(DISubprogram(DS));
598 // Look up the source id with the given directory and source file names.
599 // If none currently exists, create a new id and insert it in the
600 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
602 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
604 // If FE did not provide a file name, then assume stdin.
605 if (FileName.empty())
606 return getOrCreateSourceID("<stdin>", StringRef());
608 // TODO: this might not belong here. See if we can factor this better.
609 if (DirName == CompilationDir)
612 unsigned SrcId = SourceIdMap.size()+1;
614 // We look up the file/dir pair by concatenating them with a zero byte.
615 SmallString<128> NamePair;
617 NamePair += '\0'; // Zero bytes are not allowed in paths.
618 NamePair += FileName;
620 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
621 if (Ent.getValue() != SrcId)
622 return Ent.getValue();
624 // Print out a .file directive to specify files for .loc directives.
625 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
630 // Create new CompileUnit for the given metadata node with tag
631 // DW_TAG_compile_unit.
632 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
633 DICompileUnit DIUnit(N);
634 StringRef FN = DIUnit.getFilename();
635 CompilationDir = DIUnit.getDirectory();
636 // Call this to emit a .file directive if it wasn't emitted for the source
637 // file this CU comes from yet.
638 getOrCreateSourceID(FN, CompilationDir);
640 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
641 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
642 DIUnit.getLanguage(), Die, Asm,
644 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
645 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
646 DIUnit.getLanguage());
647 NewCU->addString(Die, dwarf::DW_AT_name, FN);
648 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
650 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
651 // DW_AT_stmt_list is a offset of line number information for this
652 // compile unit in debug_line section.
653 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
654 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
655 Asm->GetTempSymbol("section_line"));
657 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
659 if (!CompilationDir.empty())
660 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
661 if (DIUnit.isOptimized())
662 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
664 StringRef Flags = DIUnit.getFlags();
666 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
668 if (unsigned RVer = DIUnit.getRunTimeVersion())
669 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
670 dwarf::DW_FORM_data1, RVer);
674 if (useSplitDwarf() && !SkeletonCU)
675 SkeletonCU = constructSkeletonCU(N);
677 InfoHolder.addUnit(NewCU);
679 CUMap.insert(std::make_pair(N, NewCU));
683 // Construct subprogram DIE.
684 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
686 CompileUnit *&CURef = SPMap[N];
692 if (!SP.isDefinition())
693 // This is a method declaration which will be handled while constructing
697 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
700 TheCU->insertDIE(N, SubprogramDie);
702 // Add to context owner.
703 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
708 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
709 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
710 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
711 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
712 const MDNode *N = NMD->getOperand(i);
713 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
714 constructSubprogramDIE(CU, N);
717 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
718 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
719 const MDNode *N = NMD->getOperand(i);
720 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
721 CU->createGlobalVariableDIE(N);
724 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
725 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
726 DIType Ty(NMD->getOperand(i));
727 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
728 CU->getOrCreateTypeDIE(Ty);
731 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
732 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
733 DIType Ty(NMD->getOperand(i));
734 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
735 CU->getOrCreateTypeDIE(Ty);
739 // Collect debug info using DebugInfoFinder.
740 // FIXME - Remove this when dragonegg switches to DIBuilder.
741 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
742 DebugInfoFinder DbgFinder;
743 DbgFinder.processModule(*M);
745 bool HasDebugInfo = false;
746 // Scan all the compile-units to see if there are any marked as the main
747 // unit. If not, we do not generate debug info.
748 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
749 E = DbgFinder.compile_unit_end(); I != E; ++I) {
750 if (DICompileUnit(*I).isMain()) {
755 if (!HasDebugInfo) return false;
757 // Create all the compile unit DIEs.
758 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
759 E = DbgFinder.compile_unit_end(); I != E; ++I)
760 constructCompileUnit(*I);
762 // Create DIEs for each global variable.
763 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
764 E = DbgFinder.global_variable_end(); I != E; ++I) {
765 const MDNode *N = *I;
766 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
767 CU->createGlobalVariableDIE(N);
770 // Create DIEs for each subprogram.
771 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
772 E = DbgFinder.subprogram_end(); I != E; ++I) {
773 const MDNode *N = *I;
774 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
775 constructSubprogramDIE(CU, N);
781 // Emit all Dwarf sections that should come prior to the content. Create
782 // global DIEs and emit initial debug info sections. This is invoked by
783 // the target AsmPrinter.
784 void DwarfDebug::beginModule() {
785 if (DisableDebugInfoPrinting)
788 const Module *M = MMI->getModule();
790 // If module has named metadata anchors then use them, otherwise scan the
791 // module using debug info finder to collect debug info.
792 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
794 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
795 DICompileUnit CUNode(CU_Nodes->getOperand(i));
796 CompileUnit *CU = constructCompileUnit(CUNode);
797 DIArray GVs = CUNode.getGlobalVariables();
798 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
799 CU->createGlobalVariableDIE(GVs.getElement(i));
800 DIArray SPs = CUNode.getSubprograms();
801 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
802 constructSubprogramDIE(CU, SPs.getElement(i));
803 DIArray EnumTypes = CUNode.getEnumTypes();
804 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
805 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
806 DIArray RetainedTypes = CUNode.getRetainedTypes();
807 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
808 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
810 } else if (!collectLegacyDebugInfo(M))
813 collectInfoFromNamedMDNodes(M);
815 // Tell MMI that we have debug info.
816 MMI->setDebugInfoAvailability(true);
818 // Prime section data.
819 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
822 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
823 void DwarfDebug::computeInlinedDIEs() {
824 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
825 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
826 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
828 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
830 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
831 AE = AbstractSPDies.end(); AI != AE; ++AI) {
832 DIE *ISP = AI->second;
833 if (InlinedSubprogramDIEs.count(ISP))
835 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
839 // Collect info for variables that were optimized out.
840 void DwarfDebug::collectDeadVariables() {
841 const Module *M = MMI->getModule();
842 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
844 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
845 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
846 DICompileUnit TheCU(CU_Nodes->getOperand(i));
847 DIArray Subprograms = TheCU.getSubprograms();
848 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
849 DISubprogram SP(Subprograms.getElement(i));
850 if (ProcessedSPNodes.count(SP) != 0) continue;
851 if (!SP.Verify()) continue;
852 if (!SP.isDefinition()) continue;
853 DIArray Variables = SP.getVariables();
854 if (Variables.getNumElements() == 0) continue;
856 LexicalScope *Scope =
857 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
858 DeadFnScopeMap[SP] = Scope;
860 // Construct subprogram DIE and add variables DIEs.
861 CompileUnit *SPCU = CUMap.lookup(TheCU);
862 assert(SPCU && "Unable to find Compile Unit!");
863 constructSubprogramDIE(SPCU, SP);
864 DIE *ScopeDIE = SPCU->getDIE(SP);
865 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
866 DIVariable DV(Variables.getElement(vi));
867 if (!DV.Verify()) continue;
868 DbgVariable *NewVar = new DbgVariable(DV, NULL);
869 if (DIE *VariableDIE =
870 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
871 ScopeDIE->addChild(VariableDIE);
876 DeleteContainerSeconds(DeadFnScopeMap);
879 void DwarfDebug::finalizeModuleInfo() {
880 // Collect info for variables that were optimized out.
881 collectDeadVariables();
883 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
884 computeInlinedDIEs();
886 // Emit DW_AT_containing_type attribute to connect types with their
887 // vtable holding type.
888 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
889 CUE = CUMap.end(); CUI != CUE; ++CUI) {
890 CompileUnit *TheCU = CUI->second;
891 TheCU->constructContainingTypeDIEs();
894 // Compute DIE offsets and sizes.
895 InfoHolder.computeSizeAndOffsets();
897 SkeletonHolder.computeSizeAndOffsets();
900 void DwarfDebug::endSections() {
901 // Standard sections final addresses.
902 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
903 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
904 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
905 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
907 // End text sections.
908 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
909 Asm->OutStreamer.SwitchSection(SectionMap[I]);
910 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
914 // Emit all Dwarf sections that should come after the content.
915 void DwarfDebug::endModule() {
917 if (!FirstCU) return;
919 // End any existing sections.
920 // TODO: Does this need to happen?
923 // Finalize the debug info for the module.
924 finalizeModuleInfo();
926 // Emit initial sections.
929 if (!useSplitDwarf()) {
930 // Emit all the DIEs into a debug info section.
933 // Corresponding abbreviations into a abbrev section.
936 // Emit info into a debug loc section.
939 // Emit info into a debug aranges section.
942 // Emit info into a debug ranges section.
945 // Emit info into a debug macinfo section.
949 // TODO: When we don't need the option anymore we
950 // can remove all of the code that this section
952 if (useDarwinGDBCompat())
953 emitDebugInlineInfo();
955 // TODO: Fill this in for separated debug sections and separate
956 // out information into new sections.
958 // Emit the debug info section and compile units.
962 // Corresponding abbreviations into a abbrev section.
964 emitDebugAbbrevDWO();
966 // Emit info into a debug loc section.
969 // Emit info into a debug aranges section.
972 // Emit info into a debug ranges section.
975 // Emit info into a debug macinfo section.
979 // TODO: When we don't need the option anymore we
980 // can remove all of the code that this section
982 if (useDarwinGDBCompat())
983 emitDebugInlineInfo();
986 // Emit info into the dwarf accelerator table sections.
987 if (useDwarfAccelTables()) {
990 emitAccelNamespaces();
994 // Emit info into a debug pubtypes section.
995 // TODO: When we don't need the option anymore we can
996 // remove all of the code that adds to the table.
997 if (useDarwinGDBCompat())
1000 // Finally emit string information into a string table.
1002 if (useSplitDwarf())
1007 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1008 E = CUMap.end(); I != E; ++I)
1013 // Reset these for the next Module if we have one.
1018 // Find abstract variable, if any, associated with Var.
1019 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1020 DebugLoc ScopeLoc) {
1021 LLVMContext &Ctx = DV->getContext();
1022 // More then one inlined variable corresponds to one abstract variable.
1023 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1024 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1026 return AbsDbgVariable;
1028 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1032 AbsDbgVariable = new DbgVariable(Var, NULL);
1033 addScopeVariable(Scope, AbsDbgVariable);
1034 AbstractVariables[Var] = AbsDbgVariable;
1035 return AbsDbgVariable;
1038 // If Var is a current function argument then add it to CurrentFnArguments list.
1039 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1040 DbgVariable *Var, LexicalScope *Scope) {
1041 if (!LScopes.isCurrentFunctionScope(Scope))
1043 DIVariable DV = Var->getVariable();
1044 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1046 unsigned ArgNo = DV.getArgNumber();
1050 size_t Size = CurrentFnArguments.size();
1052 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1053 // llvm::Function argument size is not good indicator of how many
1054 // arguments does the function have at source level.
1056 CurrentFnArguments.resize(ArgNo * 2);
1057 CurrentFnArguments[ArgNo - 1] = Var;
1061 // Collect variable information from side table maintained by MMI.
1063 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1064 SmallPtrSet<const MDNode *, 16> &Processed) {
1065 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1066 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1067 VE = VMap.end(); VI != VE; ++VI) {
1068 const MDNode *Var = VI->first;
1070 Processed.insert(Var);
1072 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1074 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1076 // If variable scope is not found then skip this variable.
1080 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1081 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1082 RegVar->setFrameIndex(VP.first);
1083 if (!addCurrentFnArgument(MF, RegVar, Scope))
1084 addScopeVariable(Scope, RegVar);
1086 AbsDbgVariable->setFrameIndex(VP.first);
1090 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1092 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1093 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1094 return MI->getNumOperands() == 3 &&
1095 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1096 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1099 // Get .debug_loc entry for the instruction range starting at MI.
1100 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1101 const MCSymbol *FLabel,
1102 const MCSymbol *SLabel,
1103 const MachineInstr *MI) {
1104 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1106 if (MI->getNumOperands() != 3) {
1107 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1108 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1110 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1111 MachineLocation MLoc;
1112 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1113 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1115 if (MI->getOperand(0).isImm())
1116 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1117 if (MI->getOperand(0).isFPImm())
1118 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1119 if (MI->getOperand(0).isCImm())
1120 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1122 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1125 // Find variables for each lexical scope.
1127 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1128 SmallPtrSet<const MDNode *, 16> &Processed) {
1130 // collection info from MMI table.
1131 collectVariableInfoFromMMITable(MF, Processed);
1133 for (SmallVectorImpl<const MDNode*>::const_iterator
1134 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1136 const MDNode *Var = *UVI;
1137 if (Processed.count(Var))
1140 // History contains relevant DBG_VALUE instructions for Var and instructions
1142 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1143 if (History.empty())
1145 const MachineInstr *MInsn = History.front();
1148 LexicalScope *Scope = NULL;
1149 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1150 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1151 Scope = LScopes.getCurrentFunctionScope();
1153 if (DV.getVersion() <= LLVMDebugVersion9)
1154 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1156 if (MDNode *IA = DV.getInlinedAt())
1157 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1159 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1162 // If variable scope is not found then skip this variable.
1166 Processed.insert(DV);
1167 assert(MInsn->isDebugValue() && "History must begin with debug value");
1168 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1169 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1170 if (!addCurrentFnArgument(MF, RegVar, Scope))
1171 addScopeVariable(Scope, RegVar);
1173 AbsVar->setMInsn(MInsn);
1175 // Simplify ranges that are fully coalesced.
1176 if (History.size() <= 1 || (History.size() == 2 &&
1177 MInsn->isIdenticalTo(History.back()))) {
1178 RegVar->setMInsn(MInsn);
1182 // handle multiple DBG_VALUE instructions describing one variable.
1183 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1185 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1186 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1187 const MachineInstr *Begin = *HI;
1188 assert(Begin->isDebugValue() && "Invalid History entry");
1190 // Check if DBG_VALUE is truncating a range.
1191 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1192 && !Begin->getOperand(0).getReg())
1195 // Compute the range for a register location.
1196 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1197 const MCSymbol *SLabel = 0;
1200 // If Begin is the last instruction in History then its value is valid
1201 // until the end of the function.
1202 SLabel = FunctionEndSym;
1204 const MachineInstr *End = HI[1];
1205 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1206 << "\t" << *Begin << "\t" << *End << "\n");
1207 if (End->isDebugValue())
1208 SLabel = getLabelBeforeInsn(End);
1210 // End is a normal instruction clobbering the range.
1211 SLabel = getLabelAfterInsn(End);
1212 assert(SLabel && "Forgot label after clobber instruction");
1217 // The value is valid until the next DBG_VALUE or clobber.
1218 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1221 DotDebugLocEntries.push_back(DotDebugLocEntry());
1224 // Collect info for variables that were optimized out.
1225 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1226 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1227 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1228 DIVariable DV(Variables.getElement(i));
1229 if (!DV || !DV.Verify() || !Processed.insert(DV))
1231 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1232 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1236 // Return Label preceding the instruction.
1237 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1238 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1239 assert(Label && "Didn't insert label before instruction");
1243 // Return Label immediately following the instruction.
1244 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1245 return LabelsAfterInsn.lookup(MI);
1248 // Process beginning of an instruction.
1249 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1250 // Check if source location changes, but ignore DBG_VALUE locations.
1251 if (!MI->isDebugValue()) {
1252 DebugLoc DL = MI->getDebugLoc();
1253 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1256 if (DL == PrologEndLoc) {
1257 Flags |= DWARF2_FLAG_PROLOGUE_END;
1258 PrologEndLoc = DebugLoc();
1260 if (PrologEndLoc.isUnknown())
1261 Flags |= DWARF2_FLAG_IS_STMT;
1263 if (!DL.isUnknown()) {
1264 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1265 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1267 recordSourceLine(0, 0, 0, 0);
1271 // Insert labels where requested.
1272 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1273 LabelsBeforeInsn.find(MI);
1276 if (I == LabelsBeforeInsn.end())
1279 // Label already assigned.
1284 PrevLabel = MMI->getContext().CreateTempSymbol();
1285 Asm->OutStreamer.EmitLabel(PrevLabel);
1287 I->second = PrevLabel;
1290 // Process end of an instruction.
1291 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1292 // Don't create a new label after DBG_VALUE instructions.
1293 // They don't generate code.
1294 if (!MI->isDebugValue())
1297 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1298 LabelsAfterInsn.find(MI);
1301 if (I == LabelsAfterInsn.end())
1304 // Label already assigned.
1308 // We need a label after this instruction.
1310 PrevLabel = MMI->getContext().CreateTempSymbol();
1311 Asm->OutStreamer.EmitLabel(PrevLabel);
1313 I->second = PrevLabel;
1316 // Each LexicalScope has first instruction and last instruction to mark
1317 // beginning and end of a scope respectively. Create an inverse map that list
1318 // scopes starts (and ends) with an instruction. One instruction may start (or
1319 // end) multiple scopes. Ignore scopes that are not reachable.
1320 void DwarfDebug::identifyScopeMarkers() {
1321 SmallVector<LexicalScope *, 4> WorkList;
1322 WorkList.push_back(LScopes.getCurrentFunctionScope());
1323 while (!WorkList.empty()) {
1324 LexicalScope *S = WorkList.pop_back_val();
1326 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1327 if (!Children.empty())
1328 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1329 SE = Children.end(); SI != SE; ++SI)
1330 WorkList.push_back(*SI);
1332 if (S->isAbstractScope())
1335 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1338 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1339 RE = Ranges.end(); RI != RE; ++RI) {
1340 assert(RI->first && "InsnRange does not have first instruction!");
1341 assert(RI->second && "InsnRange does not have second instruction!");
1342 requestLabelBeforeInsn(RI->first);
1343 requestLabelAfterInsn(RI->second);
1348 // Get MDNode for DebugLoc's scope.
1349 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1350 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1351 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1352 return DL.getScope(Ctx);
1355 // Walk up the scope chain of given debug loc and find line number info
1356 // for the function.
1357 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1358 const MDNode *Scope = getScopeNode(DL, Ctx);
1359 DISubprogram SP = getDISubprogram(Scope);
1361 // Check for number of operands since the compatibility is
1363 if (SP->getNumOperands() > 19)
1364 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1366 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1372 // Gather pre-function debug information. Assumes being called immediately
1373 // after the function entry point has been emitted.
1374 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1375 if (!MMI->hasDebugInfo()) return;
1376 LScopes.initialize(*MF);
1377 if (LScopes.empty()) return;
1378 identifyScopeMarkers();
1380 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1381 Asm->getFunctionNumber());
1382 // Assumes in correct section after the entry point.
1383 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1385 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1387 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1388 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1389 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1391 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1393 bool AtBlockEntry = true;
1394 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1396 const MachineInstr *MI = II;
1398 if (MI->isDebugValue()) {
1399 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1401 // Keep track of user variables.
1403 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1405 // Variable is in a register, we need to check for clobbers.
1406 if (isDbgValueInDefinedReg(MI))
1407 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1409 // Check the history of this variable.
1410 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1411 if (History.empty()) {
1412 UserVariables.push_back(Var);
1413 // The first mention of a function argument gets the FunctionBeginSym
1414 // label, so arguments are visible when breaking at function entry.
1416 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1417 DISubprogram(getDISubprogram(DV.getContext()))
1418 .describes(MF->getFunction()))
1419 LabelsBeforeInsn[MI] = FunctionBeginSym;
1421 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1422 const MachineInstr *Prev = History.back();
1423 if (Prev->isDebugValue()) {
1424 // Coalesce identical entries at the end of History.
1425 if (History.size() >= 2 &&
1426 Prev->isIdenticalTo(History[History.size() - 2])) {
1427 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1429 << "\t" << *History[History.size() - 2] << "\n");
1433 // Terminate old register assignments that don't reach MI;
1434 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1435 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1436 isDbgValueInDefinedReg(Prev)) {
1437 // Previous register assignment needs to terminate at the end of
1439 MachineBasicBlock::const_iterator LastMI =
1440 PrevMBB->getLastNonDebugInstr();
1441 if (LastMI == PrevMBB->end()) {
1442 // Drop DBG_VALUE for empty range.
1443 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1444 << "\t" << *Prev << "\n");
1448 // Terminate after LastMI.
1449 History.push_back(LastMI);
1454 History.push_back(MI);
1456 // Not a DBG_VALUE instruction.
1458 AtBlockEntry = false;
1460 // First known non-DBG_VALUE and non-frame setup location marks
1461 // the beginning of the function body.
1462 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1463 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1464 PrologEndLoc = MI->getDebugLoc();
1466 // Check if the instruction clobbers any registers with debug vars.
1467 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1468 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1469 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1471 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1472 AI.isValid(); ++AI) {
1474 const MDNode *Var = LiveUserVar[Reg];
1477 // Reg is now clobbered.
1478 LiveUserVar[Reg] = 0;
1480 // Was MD last defined by a DBG_VALUE referring to Reg?
1481 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1482 if (HistI == DbgValues.end())
1484 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1485 if (History.empty())
1487 const MachineInstr *Prev = History.back();
1488 // Sanity-check: Register assignments are terminated at the end of
1490 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1492 // Is the variable still in Reg?
1493 if (!isDbgValueInDefinedReg(Prev) ||
1494 Prev->getOperand(0).getReg() != Reg)
1496 // Var is clobbered. Make sure the next instruction gets a label.
1497 History.push_back(MI);
1504 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1506 SmallVectorImpl<const MachineInstr*> &History = I->second;
1507 if (History.empty())
1510 // Make sure the final register assignments are terminated.
1511 const MachineInstr *Prev = History.back();
1512 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1513 const MachineBasicBlock *PrevMBB = Prev->getParent();
1514 MachineBasicBlock::const_iterator LastMI =
1515 PrevMBB->getLastNonDebugInstr();
1516 if (LastMI == PrevMBB->end())
1517 // Drop DBG_VALUE for empty range.
1520 // Terminate after LastMI.
1521 History.push_back(LastMI);
1524 // Request labels for the full history.
1525 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1526 const MachineInstr *MI = History[i];
1527 if (MI->isDebugValue())
1528 requestLabelBeforeInsn(MI);
1530 requestLabelAfterInsn(MI);
1534 PrevInstLoc = DebugLoc();
1535 PrevLabel = FunctionBeginSym;
1537 // Record beginning of function.
1538 if (!PrologEndLoc.isUnknown()) {
1539 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1540 MF->getFunction()->getContext());
1541 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1542 FnStartDL.getScope(MF->getFunction()->getContext()),
1543 // We'd like to list the prologue as "not statements" but GDB behaves
1544 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1545 DWARF2_FLAG_IS_STMT);
1549 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1550 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1551 ScopeVariables[LS].push_back(Var);
1552 // Vars.push_back(Var);
1555 // Gather and emit post-function debug information.
1556 void DwarfDebug::endFunction(const MachineFunction *MF) {
1557 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1559 // Define end label for subprogram.
1560 FunctionEndSym = Asm->GetTempSymbol("func_end",
1561 Asm->getFunctionNumber());
1562 // Assumes in correct section after the entry point.
1563 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1565 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1566 collectVariableInfo(MF, ProcessedVars);
1568 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1569 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1570 assert(TheCU && "Unable to find compile unit!");
1572 // Construct abstract scopes.
1573 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1574 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1575 LexicalScope *AScope = AList[i];
1576 DISubprogram SP(AScope->getScopeNode());
1578 // Collect info for variables that were optimized out.
1579 DIArray Variables = SP.getVariables();
1580 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1581 DIVariable DV(Variables.getElement(i));
1582 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1584 // Check that DbgVariable for DV wasn't created earlier, when
1585 // findAbstractVariable() was called for inlined instance of DV.
1586 LLVMContext &Ctx = DV->getContext();
1587 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1588 if (AbstractVariables.lookup(CleanDV))
1590 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1591 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1594 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1595 constructScopeDIE(TheCU, AScope);
1598 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1600 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1601 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1603 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1604 MMI->getFrameMoves()));
1607 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1608 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1609 DeleteContainerPointers(I->second);
1610 ScopeVariables.clear();
1611 DeleteContainerPointers(CurrentFnArguments);
1612 UserVariables.clear();
1614 AbstractVariables.clear();
1615 LabelsBeforeInsn.clear();
1616 LabelsAfterInsn.clear();
1620 // Register a source line with debug info. Returns the unique label that was
1621 // emitted and which provides correspondence to the source line list.
1622 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1628 DIDescriptor Scope(S);
1630 if (Scope.isCompileUnit()) {
1631 DICompileUnit CU(S);
1632 Fn = CU.getFilename();
1633 Dir = CU.getDirectory();
1634 } else if (Scope.isFile()) {
1636 Fn = F.getFilename();
1637 Dir = F.getDirectory();
1638 } else if (Scope.isSubprogram()) {
1640 Fn = SP.getFilename();
1641 Dir = SP.getDirectory();
1642 } else if (Scope.isLexicalBlockFile()) {
1643 DILexicalBlockFile DBF(S);
1644 Fn = DBF.getFilename();
1645 Dir = DBF.getDirectory();
1646 } else if (Scope.isLexicalBlock()) {
1647 DILexicalBlock DB(S);
1648 Fn = DB.getFilename();
1649 Dir = DB.getDirectory();
1651 llvm_unreachable("Unexpected scope info");
1653 Src = getOrCreateSourceID(Fn, Dir);
1655 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1658 //===----------------------------------------------------------------------===//
1660 //===----------------------------------------------------------------------===//
1662 // Compute the size and offset of a DIE.
1664 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1665 // Get the children.
1666 const std::vector<DIE *> &Children = Die->getChildren();
1668 // Record the abbreviation.
1669 assignAbbrevNumber(Die->getAbbrev());
1671 // Get the abbreviation for this DIE.
1672 unsigned AbbrevNumber = Die->getAbbrevNumber();
1673 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1676 Die->setOffset(Offset);
1678 // Start the size with the size of abbreviation code.
1679 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1681 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1682 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1684 // Size the DIE attribute values.
1685 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1686 // Size attribute value.
1687 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1689 // Size the DIE children if any.
1690 if (!Children.empty()) {
1691 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1692 "Children flag not set");
1694 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1695 Offset = computeSizeAndOffset(Children[j], Offset);
1697 // End of children marker.
1698 Offset += sizeof(int8_t);
1701 Die->setSize(Offset - Die->getOffset());
1705 // Compute the size and offset of all the DIEs.
1706 void DwarfUnits::computeSizeAndOffsets() {
1707 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1708 E = CUs.end(); I != E; ++I) {
1710 sizeof(int32_t) + // Length of Compilation Unit Info
1711 sizeof(int16_t) + // DWARF version number
1712 sizeof(int32_t) + // Offset Into Abbrev. Section
1713 sizeof(int8_t); // Pointer Size (in bytes)
1715 computeSizeAndOffset((*I)->getCUDie(), Offset);
1719 // Emit initial Dwarf sections with a label at the start of each one.
1720 void DwarfDebug::emitSectionLabels() {
1721 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1723 // Dwarf sections base addresses.
1724 DwarfInfoSectionSym =
1725 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1726 DwarfAbbrevSectionSym =
1727 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1728 if (useSplitDwarf())
1729 DwarfAbbrevDWOSectionSym =
1730 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1731 "section_abbrev_dwo");
1732 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1734 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1735 emitSectionSym(Asm, MacroInfo);
1737 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1738 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1739 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1740 DwarfStrSectionSym =
1741 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1742 if (useSplitDwarf())
1743 DwarfStrDWOSectionSym =
1744 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1745 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1748 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1749 "section_debug_loc");
1751 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1752 emitSectionSym(Asm, TLOF.getDataSection());
1755 // Recursively emits a debug information entry.
1756 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1757 // Get the abbreviation for this DIE.
1758 unsigned AbbrevNumber = Die->getAbbrevNumber();
1759 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1761 // Emit the code (index) for the abbreviation.
1762 if (Asm->isVerbose())
1763 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1764 Twine::utohexstr(Die->getOffset()) + ":0x" +
1765 Twine::utohexstr(Die->getSize()) + " " +
1766 dwarf::TagString(Abbrev->getTag()));
1767 Asm->EmitULEB128(AbbrevNumber);
1769 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1770 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1772 // Emit the DIE attribute values.
1773 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1774 unsigned Attr = AbbrevData[i].getAttribute();
1775 unsigned Form = AbbrevData[i].getForm();
1776 assert(Form && "Too many attributes for DIE (check abbreviation)");
1778 if (Asm->isVerbose())
1779 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1782 case dwarf::DW_AT_abstract_origin: {
1783 DIEEntry *E = cast<DIEEntry>(Values[i]);
1784 DIE *Origin = E->getEntry();
1785 unsigned Addr = Origin->getOffset();
1786 Asm->EmitInt32(Addr);
1789 case dwarf::DW_AT_ranges: {
1790 // DW_AT_range Value encodes offset in debug_range section.
1791 DIEInteger *V = cast<DIEInteger>(Values[i]);
1793 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1794 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1798 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1800 DwarfDebugRangeSectionSym,
1805 case dwarf::DW_AT_location: {
1806 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1807 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1808 Asm->EmitLabelReference(L->getValue(), 4);
1810 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1812 Values[i]->EmitValue(Asm, Form);
1816 case dwarf::DW_AT_accessibility: {
1817 if (Asm->isVerbose()) {
1818 DIEInteger *V = cast<DIEInteger>(Values[i]);
1819 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1821 Values[i]->EmitValue(Asm, Form);
1825 // Emit an attribute using the defined form.
1826 Values[i]->EmitValue(Asm, Form);
1831 // Emit the DIE children if any.
1832 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1833 const std::vector<DIE *> &Children = Die->getChildren();
1835 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1836 emitDIE(Children[j], Abbrevs);
1838 if (Asm->isVerbose())
1839 Asm->OutStreamer.AddComment("End Of Children Mark");
1844 // Emit the various dwarf units to the unit section USection with
1845 // the abbreviations going into ASection.
1846 void DwarfUnits::emitUnits(DwarfDebug *DD,
1847 const MCSection *USection,
1848 const MCSection *ASection,
1849 const MCSymbol *ASectionSym) {
1850 Asm->OutStreamer.SwitchSection(USection);
1851 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1852 E = CUs.end(); I != E; ++I) {
1853 CompileUnit *TheCU = *I;
1854 DIE *Die = TheCU->getCUDie();
1856 // Emit the compile units header.
1858 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1859 TheCU->getUniqueID()));
1861 // Emit size of content not including length itself
1862 unsigned ContentSize = Die->getSize() +
1863 sizeof(int16_t) + // DWARF version number
1864 sizeof(int32_t) + // Offset Into Abbrev. Section
1865 sizeof(int8_t); // Pointer Size (in bytes)
1867 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1868 Asm->EmitInt32(ContentSize);
1869 Asm->OutStreamer.AddComment("DWARF version number");
1870 Asm->EmitInt16(dwarf::DWARF_VERSION);
1871 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1872 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1874 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1875 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1877 DD->emitDIE(Die, Abbreviations);
1878 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1879 TheCU->getUniqueID()));
1883 // Emit the debug info section.
1884 void DwarfDebug::emitDebugInfo() {
1885 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1887 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1888 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1889 DwarfAbbrevSectionSym);
1892 // Emit the abbreviation section.
1893 void DwarfDebug::emitAbbreviations() {
1894 if (!useSplitDwarf())
1895 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1898 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1901 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1902 std::vector<DIEAbbrev *> *Abbrevs) {
1903 // Check to see if it is worth the effort.
1904 if (!Abbrevs->empty()) {
1905 // Start the debug abbrev section.
1906 Asm->OutStreamer.SwitchSection(Section);
1908 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1909 Asm->OutStreamer.EmitLabel(Begin);
1911 // For each abbrevation.
1912 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1913 // Get abbreviation data
1914 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1916 // Emit the abbrevations code (base 1 index.)
1917 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1919 // Emit the abbreviations data.
1923 // Mark end of abbreviations.
1924 Asm->EmitULEB128(0, "EOM(3)");
1926 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1927 Asm->OutStreamer.EmitLabel(End);
1931 // Emit the last address of the section and the end of the line matrix.
1932 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1933 // Define last address of section.
1934 Asm->OutStreamer.AddComment("Extended Op");
1937 Asm->OutStreamer.AddComment("Op size");
1938 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1939 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1940 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1942 Asm->OutStreamer.AddComment("Section end label");
1944 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1945 Asm->getDataLayout().getPointerSize());
1947 // Mark end of matrix.
1948 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1954 // Emit visible names into a hashed accelerator table section.
1955 void DwarfDebug::emitAccelNames() {
1956 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1957 dwarf::DW_FORM_data4));
1958 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1959 E = CUMap.end(); I != E; ++I) {
1960 CompileUnit *TheCU = I->second;
1961 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1962 for (StringMap<std::vector<DIE*> >::const_iterator
1963 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1964 const char *Name = GI->getKeyData();
1965 const std::vector<DIE *> &Entities = GI->second;
1966 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1967 DE = Entities.end(); DI != DE; ++DI)
1968 AT.AddName(Name, (*DI));
1972 AT.FinalizeTable(Asm, "Names");
1973 Asm->OutStreamer.SwitchSection(
1974 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1975 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1976 Asm->OutStreamer.EmitLabel(SectionBegin);
1978 // Emit the full data.
1979 AT.Emit(Asm, SectionBegin, &InfoHolder);
1982 // Emit objective C classes and categories into a hashed accelerator table
1984 void DwarfDebug::emitAccelObjC() {
1985 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1986 dwarf::DW_FORM_data4));
1987 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1988 E = CUMap.end(); I != E; ++I) {
1989 CompileUnit *TheCU = I->second;
1990 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1991 for (StringMap<std::vector<DIE*> >::const_iterator
1992 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1993 const char *Name = GI->getKeyData();
1994 const std::vector<DIE *> &Entities = GI->second;
1995 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1996 DE = Entities.end(); DI != DE; ++DI)
1997 AT.AddName(Name, (*DI));
2001 AT.FinalizeTable(Asm, "ObjC");
2002 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2003 .getDwarfAccelObjCSection());
2004 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2005 Asm->OutStreamer.EmitLabel(SectionBegin);
2007 // Emit the full data.
2008 AT.Emit(Asm, SectionBegin, &InfoHolder);
2011 // Emit namespace dies into a hashed accelerator table.
2012 void DwarfDebug::emitAccelNamespaces() {
2013 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2014 dwarf::DW_FORM_data4));
2015 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2016 E = CUMap.end(); I != E; ++I) {
2017 CompileUnit *TheCU = I->second;
2018 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2019 for (StringMap<std::vector<DIE*> >::const_iterator
2020 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2021 const char *Name = GI->getKeyData();
2022 const std::vector<DIE *> &Entities = GI->second;
2023 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2024 DE = Entities.end(); DI != DE; ++DI)
2025 AT.AddName(Name, (*DI));
2029 AT.FinalizeTable(Asm, "namespac");
2030 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2031 .getDwarfAccelNamespaceSection());
2032 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2033 Asm->OutStreamer.EmitLabel(SectionBegin);
2035 // Emit the full data.
2036 AT.Emit(Asm, SectionBegin, &InfoHolder);
2039 // Emit type dies into a hashed accelerator table.
2040 void DwarfDebug::emitAccelTypes() {
2041 std::vector<DwarfAccelTable::Atom> Atoms;
2042 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2043 dwarf::DW_FORM_data4));
2044 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2045 dwarf::DW_FORM_data2));
2046 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2047 dwarf::DW_FORM_data1));
2048 DwarfAccelTable AT(Atoms);
2049 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2050 E = CUMap.end(); I != E; ++I) {
2051 CompileUnit *TheCU = I->second;
2052 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2053 = TheCU->getAccelTypes();
2054 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2055 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2056 const char *Name = GI->getKeyData();
2057 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2058 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2059 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2060 AT.AddName(Name, (*DI).first, (*DI).second);
2064 AT.FinalizeTable(Asm, "types");
2065 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2066 .getDwarfAccelTypesSection());
2067 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2068 Asm->OutStreamer.EmitLabel(SectionBegin);
2070 // Emit the full data.
2071 AT.Emit(Asm, SectionBegin, &InfoHolder);
2074 void DwarfDebug::emitDebugPubTypes() {
2075 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2076 E = CUMap.end(); I != E; ++I) {
2077 CompileUnit *TheCU = I->second;
2078 // Start the dwarf pubtypes section.
2079 Asm->OutStreamer.SwitchSection(
2080 Asm->getObjFileLowering().getDwarfPubTypesSection());
2081 Asm->OutStreamer.AddComment("Length of Public Types Info");
2082 Asm->EmitLabelDifference(
2083 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2084 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2086 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2087 TheCU->getUniqueID()));
2089 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2090 Asm->EmitInt16(dwarf::DWARF_VERSION);
2092 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2093 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2094 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2095 TheCU->getUniqueID()),
2096 DwarfInfoSectionSym);
2098 Asm->OutStreamer.AddComment("Compilation Unit Length");
2099 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2100 TheCU->getUniqueID()),
2101 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2102 TheCU->getUniqueID()),
2105 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2106 for (StringMap<DIE*>::const_iterator
2107 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2108 const char *Name = GI->getKeyData();
2109 DIE *Entity = GI->second;
2111 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2112 Asm->EmitInt32(Entity->getOffset());
2114 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2115 // Emit the name with a terminating null byte.
2116 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2119 Asm->OutStreamer.AddComment("End Mark");
2121 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2122 TheCU->getUniqueID()));
2126 // Emit strings into a string section.
2127 void DwarfUnits::emitStrings(const MCSection *StrSection,
2128 const MCSection *OffsetSection = NULL,
2129 const MCSymbol *StrSecSym = NULL) {
2131 if (StringPool.empty()) return;
2133 // Start the dwarf str section.
2134 Asm->OutStreamer.SwitchSection(StrSection);
2136 // Get all of the string pool entries and put them in an array by their ID so
2137 // we can sort them.
2138 SmallVector<std::pair<unsigned,
2139 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2141 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2142 I = StringPool.begin(), E = StringPool.end();
2144 Entries.push_back(std::make_pair(I->second.second, &*I));
2146 array_pod_sort(Entries.begin(), Entries.end());
2148 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2149 // Emit a label for reference from debug information entries.
2150 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2152 // Emit the string itself with a terminating null byte.
2153 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2154 Entries[i].second->getKeyLength()+1));
2157 // If we've got an offset section go ahead and emit that now as well.
2158 if (OffsetSection) {
2159 Asm->OutStreamer.SwitchSection(OffsetSection);
2160 unsigned offset = 0;
2162 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2163 Asm->OutStreamer.EmitIntValue(offset, size);
2164 offset += Entries[i].second->getKeyLength() + 1;
2169 // Emit visible names into a debug str section.
2170 void DwarfDebug::emitDebugStr() {
2171 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2172 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2175 // Emit visible names into a debug loc section.
2176 void DwarfDebug::emitDebugLoc() {
2177 if (DotDebugLocEntries.empty())
2180 for (SmallVector<DotDebugLocEntry, 4>::iterator
2181 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2183 DotDebugLocEntry &Entry = *I;
2184 if (I + 1 != DotDebugLocEntries.end())
2188 // Start the dwarf loc section.
2189 Asm->OutStreamer.SwitchSection(
2190 Asm->getObjFileLowering().getDwarfLocSection());
2191 unsigned char Size = Asm->getDataLayout().getPointerSize();
2192 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2194 for (SmallVector<DotDebugLocEntry, 4>::iterator
2195 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2196 I != E; ++I, ++index) {
2197 DotDebugLocEntry &Entry = *I;
2198 if (Entry.isMerged()) continue;
2199 if (Entry.isEmpty()) {
2200 Asm->OutStreamer.EmitIntValue(0, Size);
2201 Asm->OutStreamer.EmitIntValue(0, Size);
2202 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2204 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2205 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2206 DIVariable DV(Entry.Variable);
2207 Asm->OutStreamer.AddComment("Loc expr size");
2208 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2209 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2210 Asm->EmitLabelDifference(end, begin, 2);
2211 Asm->OutStreamer.EmitLabel(begin);
2212 if (Entry.isInt()) {
2213 DIBasicType BTy(DV.getType());
2215 (BTy.getEncoding() == dwarf::DW_ATE_signed
2216 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2217 Asm->OutStreamer.AddComment("DW_OP_consts");
2218 Asm->EmitInt8(dwarf::DW_OP_consts);
2219 Asm->EmitSLEB128(Entry.getInt());
2221 Asm->OutStreamer.AddComment("DW_OP_constu");
2222 Asm->EmitInt8(dwarf::DW_OP_constu);
2223 Asm->EmitULEB128(Entry.getInt());
2225 } else if (Entry.isLocation()) {
2226 if (!DV.hasComplexAddress())
2228 Asm->EmitDwarfRegOp(Entry.Loc);
2230 // Complex address entry.
2231 unsigned N = DV.getNumAddrElements();
2233 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2234 if (Entry.Loc.getOffset()) {
2236 Asm->EmitDwarfRegOp(Entry.Loc);
2237 Asm->OutStreamer.AddComment("DW_OP_deref");
2238 Asm->EmitInt8(dwarf::DW_OP_deref);
2239 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2240 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2241 Asm->EmitSLEB128(DV.getAddrElement(1));
2243 // If first address element is OpPlus then emit
2244 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2245 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2246 Asm->EmitDwarfRegOp(Loc);
2250 Asm->EmitDwarfRegOp(Entry.Loc);
2253 // Emit remaining complex address elements.
2254 for (; i < N; ++i) {
2255 uint64_t Element = DV.getAddrElement(i);
2256 if (Element == DIBuilder::OpPlus) {
2257 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2258 Asm->EmitULEB128(DV.getAddrElement(++i));
2259 } else if (Element == DIBuilder::OpDeref) {
2260 if (!Entry.Loc.isReg())
2261 Asm->EmitInt8(dwarf::DW_OP_deref);
2263 llvm_unreachable("unknown Opcode found in complex address");
2267 // else ... ignore constant fp. There is not any good way to
2268 // to represent them here in dwarf.
2269 Asm->OutStreamer.EmitLabel(end);
2274 // Emit visible names into a debug aranges section.
2275 void DwarfDebug::emitDebugARanges() {
2276 // Start the dwarf aranges section.
2277 Asm->OutStreamer.SwitchSection(
2278 Asm->getObjFileLowering().getDwarfARangesSection());
2281 // Emit visible names into a debug ranges section.
2282 void DwarfDebug::emitDebugRanges() {
2283 // Start the dwarf ranges section.
2284 Asm->OutStreamer.SwitchSection(
2285 Asm->getObjFileLowering().getDwarfRangesSection());
2286 unsigned char Size = Asm->getDataLayout().getPointerSize();
2287 for (SmallVector<const MCSymbol *, 8>::iterator
2288 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2291 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2293 Asm->OutStreamer.EmitIntValue(0, Size);
2297 // Emit visible names into a debug macinfo section.
2298 void DwarfDebug::emitDebugMacInfo() {
2299 if (const MCSection *LineInfo =
2300 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2301 // Start the dwarf macinfo section.
2302 Asm->OutStreamer.SwitchSection(LineInfo);
2306 // Emit inline info using following format.
2308 // 1. length of section
2309 // 2. Dwarf version number
2312 // Entries (one "entry" for each function that was inlined):
2314 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2315 // otherwise offset into __debug_str for regular function name.
2316 // 2. offset into __debug_str section for regular function name.
2317 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2318 // instances for the function.
2320 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2321 // inlined instance; the die_offset points to the inlined_subroutine die in the
2322 // __debug_info section, and the low_pc is the starting address for the
2323 // inlining instance.
2324 void DwarfDebug::emitDebugInlineInfo() {
2325 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2331 Asm->OutStreamer.SwitchSection(
2332 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2334 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2335 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2336 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2338 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2340 Asm->OutStreamer.AddComment("Dwarf Version");
2341 Asm->EmitInt16(dwarf::DWARF_VERSION);
2342 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2343 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2345 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2346 E = InlinedSPNodes.end(); I != E; ++I) {
2348 const MDNode *Node = *I;
2349 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2350 = InlineInfo.find(Node);
2351 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2352 DISubprogram SP(Node);
2353 StringRef LName = SP.getLinkageName();
2354 StringRef Name = SP.getName();
2356 Asm->OutStreamer.AddComment("MIPS linkage name");
2358 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2359 DwarfStrSectionSym);
2361 Asm->EmitSectionOffset(InfoHolder
2362 .getStringPoolEntry(getRealLinkageName(LName)),
2363 DwarfStrSectionSym);
2365 Asm->OutStreamer.AddComment("Function name");
2366 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2367 DwarfStrSectionSym);
2368 Asm->EmitULEB128(Labels.size(), "Inline count");
2370 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2371 LE = Labels.end(); LI != LE; ++LI) {
2372 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2373 Asm->EmitInt32(LI->second->getOffset());
2375 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2376 Asm->OutStreamer.EmitSymbolValue(LI->first,
2377 Asm->getDataLayout().getPointerSize());
2381 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2384 // DWARF5 Experimental Separate Dwarf emitters.
2386 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2387 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2388 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2389 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2390 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2391 DICompileUnit DIUnit(N);
2392 StringRef FN = DIUnit.getFilename();
2393 CompilationDir = DIUnit.getDirectory();
2395 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2396 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2397 DIUnit.getLanguage(), Die, Asm,
2398 this, &SkeletonHolder);
2399 // FIXME: This should be the .dwo file.
2400 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2402 // FIXME: We also need DW_AT_addr_base and DW_AT_dwo_id.
2404 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2406 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2407 // DW_AT_stmt_list is a offset of line number information for this
2408 // compile unit in debug_line section.
2409 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2410 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
2411 Asm->GetTempSymbol("section_line"));
2413 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
2415 if (!CompilationDir.empty())
2416 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2418 SkeletonHolder.addUnit(NewCU);
2423 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2424 Asm->OutStreamer.SwitchSection(Section);
2425 DIE *Die = SkeletonCU->getCUDie();
2427 // Emit the compile units header.
2428 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2429 SkeletonCU->getUniqueID()));
2431 // Emit size of content not including length itself
2432 unsigned ContentSize = Die->getSize() +
2433 sizeof(int16_t) + // DWARF version number
2434 sizeof(int32_t) + // Offset Into Abbrev. Section
2435 sizeof(int8_t); // Pointer Size (in bytes)
2437 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2438 Asm->EmitInt32(ContentSize);
2439 Asm->OutStreamer.AddComment("DWARF version number");
2440 Asm->EmitInt16(dwarf::DWARF_VERSION);
2441 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2443 const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2444 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2445 DwarfAbbrevSectionSym);
2446 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2447 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2449 emitDIE(Die, &SkeletonAbbrevs);
2450 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2451 SkeletonCU->getUniqueID()));
2454 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2455 assert(useSplitDwarf() && "No split dwarf debug info?");
2456 emitAbbrevs(Section, &SkeletonAbbrevs);
2459 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2460 // compile units that would normally be in debug_info.
2461 void DwarfDebug::emitDebugInfoDWO() {
2462 assert(useSplitDwarf() && "No split dwarf debug info?");
2463 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2464 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2465 DwarfAbbrevDWOSectionSym);
2468 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2469 // abbreviations for the .debug_info.dwo section.
2470 void DwarfDebug::emitDebugAbbrevDWO() {
2471 assert(useSplitDwarf() && "No split dwarf?");
2472 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2476 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2477 // string section and is identical in format to traditional .debug_str
2479 void DwarfDebug::emitDebugStrDWO() {
2480 assert(useSplitDwarf() && "No split dwarf?");
2481 const MCSection *OffSec = Asm->getObjFileLowering()
2482 .getDwarfStrOffDWOSection();
2483 const MCSymbol *StrSym = DwarfStrSectionSym;
2484 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),